From b9d0f70b3ef1917b75673dfa57b8278da6cffb36 Mon Sep 17 00:00:00 2001 From: MIT-Consulting Date: Sun, 22 Nov 2026 01:27:02 -0500 Subject: [PATCH 01/96] fix(mobile): replace undefined text-foreground-subtle token with text-foreground-muted (#40676) Co-authored-by: Julius Marminge --- apps/mobile/src/features/threads/thread-command-output.tsx | 2 +- apps/mobile/src/features/threads/thread-work-log.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/threads/thread-command-output.tsx b/apps/mobile/src/features/threads/thread-command-output.tsx index ee74a86e3db5b..2a929d96e5f7c 100644 --- a/apps/mobile/src/features/threads/thread-command-output.tsx +++ b/apps/mobile/src/features/threads/thread-command-output.tsx @@ -73,7 +73,7 @@ export function ThreadCommandOutput(props: { }} > {data?.output.truncated ? ( - + Earlier output not shown ) : null} diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index 8f22d0b511651..f0bc00e11385e 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -971,7 +971,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( ) : null} {timestamp.toLocaleString(undefined, { month: "short", @@ -1185,7 +1185,7 @@ const ThreadWorkLogRow = function ThreadWorkLogRow( row.workEntry.questionAnswer && hasQuestionAnswer(row.workEntry.questionAnswer) ? "text-foreground" - : "text-foreground-subtle" + : "text-foreground-muted" } >{` ${answerPreview}`} ) : null} From df67c4f7f9153cc203bf1198c7c18bf775f11de5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 22:34:14 -0800 Subject: [PATCH 02/96] fix(antigravity): a long shell command keeps its start, not its last 8,000 characters (#40702) --- .../provider/acp/AntigravityProtocol.test.ts | 24 +++++++++++++-- .../src/provider/acp/AntigravityProtocol.ts | 29 +++++++++++++++---- 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index cfe47280fc4f1..93f7d1fc377c8 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -535,24 +535,42 @@ describe("Antigravity tool results", () => { ); }); + it("keeps the start of a long command line, where the program and target are", () => { + const head = "cat > notes.md <<'EOF'"; + const commandLine = `${head}\n${"note line\n".repeat(1_000)}EOF`; + const toolCall = normalizeAntigravityToolCall( + parseToolUpdate({ + ...commandStarted, + update: { ...commandStarted.update, rawInput: { CommandLine: commandLine } }, + }).toolCall, + ); + expect(toolCall.command?.startsWith(head)).toBe(true); + expect(toolCall.command).not.toContain("[Earlier output truncated]"); + expect((toolCall.data.rawInput as { CommandLine: string }).CommandLine.startsWith(head)).toBe( + true, + ); + }); + it("keeps 1.5 command input and output valid Unicode when cut", () => { const tail = `${"x".repeat(7_982)}build completed\r\n`; const output = `Command output:\nprefix\r\n๐Ÿš€${tail}`; const expected = `[Earlier output truncated]\n\n${tail}`; + const head = "x".repeat(7_999); + const expectedCommand = `${head}\n\n[Command truncated]`; const toolCall = normalizeAntigravityToolCall( parseToolUpdate({ ...commandCompleted, update: { ...commandCompleted.update, - rawInput: { CommandLine: output }, + rawInput: { CommandLine: `${head}๐Ÿš€ --flag` }, rawOutput: { output, exit_code: 0 }, content: [{ type: "content", content: { type: "text", text: output } }], }, }).toolCall, ); - expect(toolCall.command).toBe(expected.trimEnd()); + expect(toolCall.command).toBe(expectedCommand); expect(toolCall.data).toMatchObject({ - rawInput: { CommandLine: expected }, + rawInput: { CommandLine: expectedCommand }, rawOutput: { output: expected }, content: [{ content: { text: expected.trimEnd() } }], }); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 2ba17c8a86db5..c718667dcf42e 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -21,6 +21,7 @@ import { const TOOL_TEXT_LIMIT = 8_000; const TOOL_TEXT_TRUNCATED = "[Earlier output truncated]\n\n"; +const COMMAND_LINE_TRUNCATED = "\n\n[Command truncated]"; const QUESTION_LABEL_LIMIT = 512; const NativeToolFields = Schema.Struct({ @@ -194,11 +195,21 @@ function boundCommandText(text: string, limit = TOOL_TEXT_LIMIT): string { return copyBoundedText(`${TOOL_TEXT_TRUNCATED}${tail}`); } +// A command line's program and target are at its start, so it keeps its head. +function boundCommandLine(text: string, limit = TOOL_TEXT_LIMIT): string { + if ( + text.length <= limit || + (text.length <= limit + COMMAND_LINE_TRUNCATED.length && text.endsWith(COMMAND_LINE_TRUNCATED)) + ) { + return text; + } + const head = text.slice(0, limit).replace(/[\uD800-\uDBFF]$/u, ""); + return copyBoundedText(`${head}${COMMAND_LINE_TRUNCATED}`); +} + +const COMMAND_LINE_FIELDS = new Set(["CommandLine", "command_line", "commandLine", "command"]); + const COMMAND_TEXT_FIELDS = new Set([ - "CommandLine", - "command_line", - "commandLine", - "command", "aggregatedOutput", "combinedOutput", "combined_output", @@ -231,7 +242,13 @@ function sanitizeToolValue( return undefined; } const bound = - field !== undefined && COMMAND_TEXT_FIELDS.has(field) ? boundCommandText : boundText; + field === undefined + ? boundText + : COMMAND_LINE_FIELDS.has(field) + ? boundCommandLine + : COMMAND_TEXT_FIELDS.has(field) + ? boundCommandText + : boundText; const text = bound(value, Math.min(TOOL_TEXT_LIMIT, budget.text)); budget.text -= text.length; return text; @@ -468,7 +485,7 @@ export function normalizeAntigravityToolCall( output?.commandLine ?? output?.command_line ?? toolCall.command; - const command = nativeCommand?.trim() ? boundCommandText(nativeCommand.trim()) : undefined; + const command = nativeCommand?.trim() ? boundCommandLine(nativeCommand.trim()) : undefined; const nativeCwd = input?.Cwd ?? input?.WorkingDirectory ?? From 4e28da0de1098285b71338ff24c77c16e065815c Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:39:18 +0100 Subject: [PATCH 03/96] fix(server): setup script output no longer ends in half an emoji (#40701) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/project/ProjectSetupScriptRunner.test.ts | 10 ++++++++++ .../src/project/ProjectSetupScriptRunner.ts | 15 +++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index 0628030b8f91c..c495feb4cef66 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -197,6 +197,16 @@ describe("ProjectSetupScriptRunner", () => { }), ); + it.effect("keeps emoji whole when capping a long output line or partial-line buffer", () => + Effect.gen(function* () { + const { outputLines, emit } = yield* setup(); + yield* emit({ ...event, type: "output", data: `x${"๐Ÿ™‚".repeat(250)}\r\n` }); + yield* emit({ ...event, type: "output", data: `${"๐Ÿ™‚".repeat(2_100)}x` }); + yield* emit({ ...event, type: "output", data: "\r\n" }); + expect(yield* Queue.takeAll(outputLines)).toEqual([`x${"๐Ÿ™‚".repeat(199)}`, "๐Ÿ™‚".repeat(200)]); + }), + ); + it.effect("types into a quiet shell that has no line editor", () => Effect.gen(function* () { const { writes } = yield* setup(); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 0f2e58d121402..1c94a3f118757 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -1,4 +1,5 @@ import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { projectScriptRuntimeEnv, projectScriptTerminalInput, @@ -310,7 +311,14 @@ export const make = Effect.gen(function* () { ) { return Effect.void; } - return input.onOutputLine(cleaned.slice(0, OUTPUT_LINE_MAX_LENGTH)); + return input.onOutputLine( + cleaned.slice( + 0, + splitsSurrogatePair(cleaned, OUTPUT_LINE_MAX_LENGTH) + ? OUTPUT_LINE_MAX_LENGTH - 1 + : OUTPUT_LINE_MAX_LENGTH, + ), + ); }); const unsubscribe = yield* terminalManager.subscribe((event) => { @@ -324,7 +332,10 @@ export const make = Effect.gen(function* () { lineBuffer = lines.pop() ?? ""; // Bound newline-free output; the sentinel has its own line, so retaining the tail is safe. if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) { - lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH); + const start = lineBuffer.length - PARTIAL_LINE_MAX_LENGTH; + lineBuffer = lineBuffer.slice( + splitsSurrogatePair(lineBuffer, start) ? start + 1 : start, + ); } return Effect.forEach(lines, handleLine, { discard: true }).pipe( Effect.andThen( From 504589183e83bd5dc33b8963b393d1977acf4e95 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:01:32 +0100 Subject: [PATCH 04/96] fix(server): text generation no longer falls back to a model that cannot generate text (#40699) Co-authored-by: Julius Marminge --- .../CodexTextGeneration.test.ts | 32 +++++++++++++++++-- .../src/textGeneration/TextGeneration.ts | 11 +++++-- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index dc3d5914a8297..1462983e949b1 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -1,4 +1,5 @@ import { + DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER, ProjectId, ProviderDriverKind, type ModelSelection, @@ -660,11 +661,13 @@ const PREFLIGHT_PRIMARY_STATES = [ "exhausted", "not installed", "not installed, fallback disabled for project", + "not installed, fallback model cannot generate text", "signed out", "signed out, fallback failed", "cannot generate text", "model cannot generate text", "disabled", + "disabled, thread default model cannot generate text", "disabled, fallback disabled for project", ] as const; @@ -726,6 +729,21 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima ], } : {}), + ...((primaryState === "not installed, fallback model cannot generate text" || + primaryState === "disabled, thread default model cannot generate text") && + instanceId === fallback + ? { + models: [ + { + slug: threadDefault.model, + name: threadDefault.model, + isCustom: true, + supportsTextGeneration: false, + capabilities: null, + }, + ], + } + : {}), ...(primaryState.startsWith("disabled") && instanceId === primary ? { enabled: false, status: "disabled" } : {}), @@ -797,7 +815,10 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima cwd: "/tmp", message: "hello", linkedContext: "", - modelSelection: selection, + modelSelection: + primaryState === "disabled, thread default model cannot generate text" + ? threadDefault + : selection, projectId, }) .pipe(Effect.exit); @@ -813,7 +834,14 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima primaryState === "not installed, fallback disabled for project" || primaryState === "signed out, fallback failed" ? selection - : threadDefault, + : primaryState === "not installed, fallback model cannot generate text" || + primaryState === "disabled, thread default model cannot generate text" + ? { + instanceId: fallback, + model: + DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[ProviderDriverKind.make("claudeAgent")], + } + : threadDefault, ]); }), ); diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index f994b7743c503..0436c552a6b7b 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -126,13 +126,14 @@ export const make = Effect.gen(function* () { }), ), ); - selection = + const rejected = selection; + const fallbackWhere = (sameInstance: boolean) => fallbackTextGenerationModelSelection( settings.providerInstances, (instanceId, driver, model) => { const provider = snapshots.find((candidate) => candidate.instanceId === instanceId); return ( - instanceId !== selection.instanceId && + (sameInstance ? model !== rejected.model : instanceId !== rejected.instanceId) && provider?.enabled === true && resolveProjectProviderInstanceEnabled(settings, projectId ?? null, instanceId) && provider.installed && @@ -140,12 +141,16 @@ export const make = Effect.gen(function* () { provider.status !== "error" && isProviderAvailable(provider) && isProviderTextGenerationCapable(provider) && + provider.models.find((candidate) => candidate.slug === model) + ?.supportsTextGeneration !== false && (operation !== "generateReviewGuide" || INVESTIGATING_DRIVERS.has(driver)) && !exhaustedUsageWindow(provider, now, model) ); }, { defaultModelSelection: settings.defaultModelSelection }, - ) ?? selection; + ); + // Another instance first; the rejected instance's other models only when none qualifies. + selection = fallbackWhere(false) ?? fallbackWhere(true) ?? selection; } if (textGeneratorCannotRun && selection.instanceId === textGeneratorId) { return yield* new TextGenerationError({ From 4ac5e6e791c0aa7ec926d8c535e6416fc9c57a15 Mon Sep 17 00:00:00 2001 From: bruno Date: Sun, 22 Nov 2026 07:04:26 +0000 Subject: [PATCH 05/96] fix(client-runtime): typing a bare Windows drive lists its folders (#40682) Co-authored-by: Julius Marminge --- apps/web/src/components/CommandPalette.tsx | 4 ++-- .../components/settings/ProjectRepositoriesSettings.tsx | 4 +++- packages/client-runtime/src/state/filesystem.test.ts | 7 +++++++ packages/client-runtime/src/state/filesystem.ts | 8 ++++++-- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 3349902aeea05..cc839c6d92c3c 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2379,7 +2379,7 @@ function OpenCommandPaletteDialog(props: { cloneDirectoryName: pinnedCloneDirectoryName, caseSensitive: !isWindowsPlatform(browseEnvironmentPlatform), }) - : appendBrowsePathSegment(query, name); + : appendBrowsePathSegment(browsePath.directoryPath, name); await browseNavigation.run( () => prefetchBrowsePath(getBrowseDirectoryPath(nextQuery)), () => { @@ -2797,7 +2797,7 @@ function OpenCommandPaletteDialog(props: { void browseTo(completion.name); } else if (completion && !pinnedCloneDirectoryName) { setHighlightedItemValue(null); - setQuery(`${getBrowseDirectoryPath(query)}${completion.name}`); + setQuery(`${browsePath.directoryPath}${completion.name}`); } return; } diff --git a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx index ea6868ed3dc93..6ea4694620c23 100644 --- a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx +++ b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx @@ -338,7 +338,9 @@ function AddTrackedFolderDialog(props: { key={entry.fullPath} type="button" className={rowClassName} - onClick={() => setQuery(appendBrowsePathSegment(query, entry.name))} + onClick={() => + setQuery(appendBrowsePathSegment(browsePath.directoryPath, entry.name)) + } > {entry.name} diff --git a/packages/client-runtime/src/state/filesystem.test.ts b/packages/client-runtime/src/state/filesystem.test.ts index f0c87f7c7f447..4b4547490f41c 100644 --- a/packages/client-runtime/src/state/filesystem.test.ts +++ b/packages/client-runtime/src/state/filesystem.test.ts @@ -78,6 +78,13 @@ describe("filesystem browse model", () => { parentPath: "~/", canBrowseUp: true, }); + expect(getFilesystemBrowsePath("D:", "Win32")).toEqual({ + isBrowsing: true, + directoryPath: "D:\\", + filterQuery: "", + parentPath: null, + canBrowseUp: false, + }); expect(getFilesystemBrowsePath("C:\\Users\\test", "MacIntel").isBrowsing).toBe(false); expect(getFilesystemBrowsePath("~/projects/", "", false).isBrowsing).toBe(false); }); diff --git a/packages/client-runtime/src/state/filesystem.ts b/packages/client-runtime/src/state/filesystem.ts index 1ee87c85d5507..d2bddeeb75ad4 100644 --- a/packages/client-runtime/src/state/filesystem.ts +++ b/packages/client-runtime/src/state/filesystem.ts @@ -70,9 +70,13 @@ export function resolveFilesystemReadAccess( export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) { const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform); - const directoryPath = isBrowsing ? getBrowseDirectoryPath(query) : ""; + // A bare drive has no separator, so it would otherwise filter its own listing by "D:". + const browseQuery = /^[a-zA-Z]:$/.test(query) ? `${query}\\` : query; + const directoryPath = isBrowsing ? getBrowseDirectoryPath(browseQuery) : ""; const filterQuery = - isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : ""; + isBrowsing && !hasTrailingPathSeparator(browseQuery) + ? getBrowseLeafPathSegment(browseQuery) + : ""; const parentPath = isBrowsing ? getBrowseParentPath(directoryPath) : null; return { From c9e9e7d36a91044bdcd9c7e1163c97de297f5bde Mon Sep 17 00:00:00 2001 From: Jaroslav Brtis <6890442+Jardo-51@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:08:26 +0100 Subject: [PATCH 06/96] fix(web): a click outside the scheduled task editor no longer discards the draft (#40708) Co-authored-by: Julius Marminge --- .../ScheduledTasksSettings.browser.test.tsx | 14 ++++++++++++++ .../components/settings/ScheduledTasksSettings.tsx | 2 ++ 2 files changed, 16 insertions(+) diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx index 7ba2d17d7291d..417868799a18d 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx @@ -279,4 +279,18 @@ describe("ScheduledTasksSettings", () => { await expect.element(dialog.getByRole("heading", { name: "New task" })).toBeInTheDocument(); await expect.element(name).toHaveValue("My draft"); }); + + it("keeps a new task's draft when the user clicks outside the editor", async () => { + setup(); + await using _screen = await render(); + await userEvent.click(page.getByRole("button", { name: "New task" })); + const dialog = page.getByRole("dialog"); + const name = dialog.getByRole("textbox", { name: "Name" }); + await userEvent.fill(name, "My draft"); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + await expect.element(dialog).toHaveAttribute("data-open"); + await expect.element(name).toHaveValue("My draft"); + }); }); diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 4f70815684faa..a2ffce32e68cd 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -1270,6 +1270,8 @@ function ScheduledTaskEditorDialog({ return ( { if (!open && !saving) onClose(); }} From 7966f202ef99afee2fa877fce2886b9876e8373a Mon Sep 17 00:00:00 2001 From: Charles Bine <8898759+charlesbine@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:17:39 -0400 Subject: [PATCH 07/96] fix(antigravity): pre-approve T3 MCP tools in Auto and Auto-accept edits (#39822) Co-authored-by: Julius Marminge Co-authored-by: charlesbine --- .../acp/AntigravityAcpSupport.test.ts | 41 +++++++++++++++++++ .../src/provider/acp/AntigravityAcpSupport.ts | 31 +++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 05f12ec278fd9..7201d1edc0ba0 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -133,6 +133,47 @@ describe("Antigravity Auto", () => { ).toBe("deny"); }, ); + + it.each(["auto", "auto-accept-edits"] as const)( + "runs only server-qualified T3 MCP calls unasked in %s", + (runtimeMode) => { + const policy = { runtimeMode, cwd: "/workspace" }; + const request = ( + title: string, + rawInput?: Record, + ): EffectAcpSchema.RequestPermissionRequest => ({ + sessionId: "session-1", + toolCall: { toolCallId: "call-1", title, kind: "execute", rawInput }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + }); + for (const t3Call of [ + request("Run mcp_t3-code_t3_thread_list?"), + request("MCP Tool delegate_task", { ServerName: "t3-code", ToolName: "delegate_task" }), + ]) { + expect(antigravityPermissionDisposition(policy, t3Call)).toBe("allow"); + expect( + antigravityPermissionDisposition({ ...policy, approvalPolicy: "on-request" }, t3Call), + ).toBe("ask"); + expect( + antigravityPermissionDisposition( + { ...policy, sandboxPolicy: { type: "readOnly" } }, + t3Call, + ), + ).toBe("deny"); + } + for (const otherCall of [ + // Names no server, so another MCP server's tool of the same name looks identical. + request("Running preview_status"), + request("Run mcp_github_create_issue"), + request("MCP Tool preview_status", { ServerName: "other", ToolName: "preview_status" }), + request("Run mcp_t3-code_preview_status", { + CommandLine: "Run mcp_t3-code_preview_status", + }), + ]) { + expect(antigravityPermissionDisposition(policy, otherCall)).toBe("ask"); + } + }, + ); }); describe("applyAntigravityAcpModelSelection", () => { diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7434e23b5eda9..4d57305f7e0ec 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -25,9 +25,11 @@ import { import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { acpPermissionDisposition, + unknownRecord, type AcpRuntimePolicy, } from "@t3tools/provider-acp/server/clientPolicy"; import type { AcpSessionModeState } from "@t3tools/provider-acp/server/runtimeModel"; +import { T3_MCP_TOOL_NAMES } from "@t3tools/shared/t3McpToolPresentation"; import packageJson from "../../../package.json" with { type: "json" }; import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts"; @@ -181,13 +183,40 @@ export function antigravitySessionMode( return modeId === "yolo" || modeId === "auto_edit" ? "default" : modeId; } +// Only calls that name T3's server: before agy 1.5.8 "Running " names no server, so another +// MCP server's tool of the same name would pass. +const ANTIGRAVITY_T3_MCP_TITLE = /^Run mcp_t3-code_(?[A-Za-z0-9_]+)\??$/; + +function isAntigravityT3McpRequest(request: EffectAcpSchema.RequestPermissionRequest): boolean { + const rawInput = unknownRecord(request.toolCall.rawInput); + if (rawInput?.ServerName !== undefined) { + return ( + rawInput.ServerName === "t3-code" && + typeof rawInput.ToolName === "string" && + T3_MCP_TOOL_NAMES.has(rawInput.ToolName) + ); + } + if (typeof rawInput?.CommandLine === "string") return false; + const tool = ANTIGRAVITY_T3_MCP_TITLE.exec(request.toolCall.title?.trim() ?? "")?.groups?.tool; + return tool !== undefined && T3_MCP_TOOL_NAMES.has(tool); +} + export function antigravityPermissionDisposition( policy: AcpRuntimePolicy, request: EffectAcpSchema.RequestPermissionRequest, ) { const disposition = acpPermissionDisposition(policy, request); + if (disposition === "deny") return "deny"; + // T3 authorizes its own MCP server, so Auto and Auto-accept edits run it unasked, as Claude does. + if ( + (policy.runtimeMode === "auto" || policy.runtimeMode === "auto-accept-edits") && + (policy.approvalPolicy === undefined || policy.approvalPolicy === "never") && + isAntigravityT3McpRequest(request) + ) { + return "allow"; + } // agy's Auto has already reviewed what it sends; the user decides unless the sandbox forbids it. - return policy.runtimeMode === "auto" && disposition !== "deny" ? "ask" : disposition; + return policy.runtimeMode === "auto" ? "ask" : disposition; } /** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */ From ad1b1f9ca4219babe21f0beee73df253d052f994 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 23:18:42 -0800 Subject: [PATCH 08/96] fix(server): Antigravity keeps Auto in the mode picker after a restart (#40154) Co-authored-by: Claude Opus 5.5 --- .../src/provider/AntigravityProvider.test.ts | 27 +++++++ .../src/provider/AntigravityProvider.ts | 70 +++++++++++-------- .../src/provider/Drivers/AntigravityDriver.ts | 30 ++++++++ 3 files changed, 99 insertions(+), 28 deletions(-) diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 522be29a8b187..88589d1c9a773 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -7,6 +7,7 @@ import { ProviderDriverKind, ProviderInstanceId, ProviderSetupError, + type RuntimeMode, type ServerProviderUsageLimits, } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; @@ -138,8 +139,10 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( readonly enabled?: boolean; readonly safe?: boolean; readonly probeUsage?: Effect.Effect; + readonly rememberedRuntimeModes?: ReadonlyArray; } = {}, ) { + const savedRuntimeModes = yield* Ref.make>>([]); const initialProbe = yield* Deferred.make(); const probeCalls = yield* Ref.make(0); const safetyCalls = yield* Ref.make(0); @@ -153,6 +156,10 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( stampIdentity: (snapshot) => Effect.succeed({ ...snapshot, instanceId, driver }), ...(options.auth ? { auth: options.auth } : {}), ...(options.probeUsage ? { probeUsage: options.probeUsage } : {}), + ...(options.rememberedRuntimeModes + ? { rememberedRuntimeModes: options.rememberedRuntimeModes } + : {}), + rememberRuntimeModes: (modes) => Ref.update(savedRuntimeModes, (saved) => [...saved, modes]), probe: Ref.update(probeCalls, (count) => count + 1).pipe( Effect.andThen(Ref.get(probe)), Effect.flatten, @@ -187,6 +194,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( initialUpdate, initialize, nextPublish, + savedRuntimeModes, }; }); @@ -381,6 +389,25 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { yield* harness.provider.onSessionStarted(startedWithAuto); yield* harness.provider.onSignedOut; expect(yield* supportedModes).toEqual(withoutAuto); + const withAuto: ReadonlyArray = [ + "approval-required", + "auto-accept-edits", + "auto", + "full-access", + ]; + expect(yield* Ref.get(harness.savedRuntimeModes)).toEqual([ + withAuto, + withoutAuto, + withAuto, + withoutAuto, + ]); + + // A restart offers what the last session advertised before any session starts. + const restarted = yield* makeHarness({ rememberedRuntimeModes: withAuto }); + yield* restarted.initialize; + expect(yield* restarted.provider.snapshot.getSnapshot).toMatchObject({ + supportedRuntimeModes: withAuto, + }); }), ); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index b3b68d46e8ba8..f5e18f6bece9d 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -172,6 +172,9 @@ interface AntigravityProviderOptions { readonly clearUsage?: Effect.Effect; readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities; readonly auth?: { readonly type: string; readonly label: string }; + /** Modes the last session advertised, saved because initialize alone does not report them. */ + readonly rememberedRuntimeModes?: ReadonlyArray; + readonly rememberRuntimeModes?: (modes: ReadonlyArray) => Effect.Effect; } const RUNTIME_MODES_WITHOUT_AUTO = [ @@ -209,7 +212,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func presentation: { displayName: "Antigravity", showInteractionModeToggle: false, - supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, + supportedRuntimeModes: options.rememberedRuntimeModes ?? RUNTIME_MODES_WITHOUT_AUTO, }, enabled: settings.enabled, checkedAt, @@ -246,6 +249,14 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null); } }; + const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* ( + previous: ReadonlyArray | undefined, + next: ReadonlyArray, + ) { + if (options.rememberRuntimeModes && previous?.join() !== next.join()) { + yield* options.rememberRuntimeModes(next); + } + }); const getSnapshot = SubscriptionRef.get(metadata).pipe( Effect.flatMap((state) => options.stampIdentity(state.draft)), ); @@ -400,17 +411,18 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func const before = yield* SubscriptionRef.get(metadata); const supportsTextGeneration = yield* options.supportsTextGeneration; const updatedAt = DateTime.formatIso(yield* DateTime.now); - yield* SubscriptionRef.update(metadata, (state) => { + const supportedRuntimeModes = antigravityRuntimeModes(started.sessionSetupResult); + const previousModes = yield* SubscriptionRef.modify(metadata, (state) => { if ( state.authRevision !== before.authRevision && state.draft.auth.status === "unauthenticated" ) { - return state; + return [supportedRuntimeModes, state] as const; } const { message: _previousMessage, ...draft } = state.draft; const workspaces = draft.workspaceSnapshots ?? []; const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined; - return { + const next = { authRevision: state.authRevision + 1, draft: { ...draft, @@ -424,7 +436,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func }, checkedAt: updatedAt, models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels), - supportedRuntimeModes: antigravityRuntimeModes(started.sessionSetupResult), + supportedRuntimeModes, supportsTextGeneration, ...(cwd ? { @@ -441,7 +453,9 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func : {}), }, } satisfies AntigravityProviderState; + return [draft.supportedRuntimeModes, next] as const; }); + yield* rememberRuntimeModes(previousModes, supportedRuntimeModes); if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage(); }); @@ -495,30 +509,30 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func yield* resetUsage; if (!settings.enabled) return; const updatedAt = DateTime.formatIso(yield* DateTime.now); - yield* SubscriptionRef.update( - metadata, - (state) => - ({ - authRevision: state.authRevision + 1, - draft: { - ...state.draft, - auth: { - status: "unauthenticated", - ...(usesCredentials ? options.auth : {}), - }, - status: "warning", - message: signInMessage, - checkedAt: updatedAt, - models: [], - slashCommands: [], - skills: [], - workspaceSnapshots: [], - supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, - supportsTextGeneration: false, - usageLimits: undefined, + const previousModes = yield* SubscriptionRef.modify(metadata, (state) => [ + state.draft.supportedRuntimeModes, + { + authRevision: state.authRevision + 1, + draft: { + ...state.draft, + auth: { + status: "unauthenticated", + ...(usesCredentials ? options.auth : {}), }, - }) satisfies AntigravityProviderState, - ); + status: "warning", + message: signInMessage, + checkedAt: updatedAt, + models: [], + slashCommands: [], + skills: [], + workspaceSnapshots: [], + supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO, + supportsTextGeneration: false, + usageLimits: undefined, + }, + } satisfies AntigravityProviderState, + ]); + yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO); discoveredSkills.clear(); thinkingLevels.clear(); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 3d426785813c3..b0d11b453dc61 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -3,8 +3,10 @@ import { AntigravitySettings, ProviderDriverKind, ProviderSetupError, + RuntimeMode, settingsSecretLiteral, } from "@t3tools/contracts"; +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import { @@ -17,6 +19,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; @@ -86,6 +89,11 @@ const isNodeRuntimeUnavailableError = Schema.is(NodeRuntimeUnavailableError); const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); const isProviderSetupError = Schema.is(ProviderSetupError); const isAcpErrorDetails = Schema.is(Schema.Struct({ details: Schema.String })); +const RememberedRuntimeModes = Schema.fromJsonString( + Schema.Struct({ authMethod: Schema.String, modes: Schema.Array(RuntimeMode) }), +); +const decodeRememberedRuntimeModes = Schema.decodeUnknownOption(RememberedRuntimeModes); +const encodeRememberedRuntimeModes = Schema.encodeSync(RememberedRuntimeModes); const REFRESH_FAILED = "Could not refresh Antigravity models. The previous model list is unchanged."; const PYTHON_SOCKS_REQUIRED = "python-socks is required to use a SOCKS proxy"; @@ -178,6 +186,18 @@ export const AntigravityDriver: ProviderDriver< ), ); const profileDirectory = directories.profile; + // Only a session reports whether agy offers Auto, so keep the last answer across restarts. + const runtimeModesPath = path.join(profileDirectory, "t3-runtime-modes.json"); + const rememberedRuntimeModes = yield* fileSystem.readFileString(runtimeModesPath).pipe( + Effect.map((contents) => + decodeRememberedRuntimeModes(contents).pipe( + Option.filter((saved) => saved.authMethod === auth.authMethod), + Option.map((saved) => saved.modes), + Option.getOrUndefined, + ), + ), + Effect.orElseSucceed(() => undefined), + ); for (const directory of [ directories.runtimeTemp, path.join(profileDirectory, "antigravity-acp", "tmp"), @@ -572,6 +592,16 @@ export const AntigravityDriver: ProviderDriver< probeUsage: usage.probe, clearUsage: usage.clear, auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, + ...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}), + rememberRuntimeModes: (modes) => + writeFileStringAtomically({ + filePath: runtimeModesPath, + contents: encodeRememberedRuntimeModes({ authMethod: auth.authMethod, modes }), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.catch(() => Effect.logWarning("Could not save Antigravity permission modes.")), + ), supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), From 11224f63d2a3d444ca1fd1f67cd3ff21c1f5f8a1 Mon Sep 17 00:00:00 2001 From: Tgoh Date: Sun, 22 Nov 2026 17:31:26 +1000 Subject: [PATCH 09/96] fix(client-runtime): a new thread's first message and a queued send-now or steer survive a dropped socket (#40703) Co-authored-by: Julius Marminge --- .../src/components/ChatView.browser.test.tsx | 14 ++- .../src/operations/commands.test.ts | 119 ++++++++++++++++++ .../client-runtime/src/operations/commands.ts | 91 ++++++++------ 3 files changed, 181 insertions(+), 43 deletions(-) diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index cfd06a8864e0d..60c3c24ce5c2d 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -17,6 +17,7 @@ import { mergeWithDefaultKeybindings, } from "@t3tools/shared/keybindings"; import type * as Context from "effect/Context"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import { expect, it, vi } from "vite-plus/test"; import { cdp, page, userEvent } from "vite-plus/test/browser"; @@ -89,6 +90,8 @@ function acceptAttachmentUploads(): Disposable { const insertText = (text: string) => cdp().send("Input.insertText", { text }); /** Holds every call to `method` until `release`, then ends it with `end`, until disposed. */ +class LaunchRefused extends Schema.TaggedError()("LaunchRefused", {}) {} + function holdRpc(method: string, end: Effect.Effect) { let release = () => {}; const held = new Promise((resolve) => { @@ -406,7 +409,7 @@ it("a new draft does not load its reserved thread before the server lists it", a expect(threadRequests).toEqual([]); }); -it("an interrupted image-only first send of a new thread says it may not have been sent", async () => { +it("a failed image-only first send of a new thread keeps the new draft", async () => { using _environment = installFakeEnvironment([]); __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, @@ -418,8 +421,11 @@ it("an interrupted image-only first send of a new thread says it may not have be .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId: ThreadId.make("thread-image-only-interrupted"), }); - // A dropped connection interrupts a new thread's launch, which is not resent. - using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + // A refusal fails at once; an interrupted launch would wait for a reconnect and be resent. + using launch = holdRpc( + ORCHESTRATION_V2_WS_METHODS.launchThread, + Effect.fail(new LaunchRefused()), + ); const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] })); await router.load(); await using _app = await render(, { @@ -445,7 +451,7 @@ it("an interrupted image-only first send of a new thread says it may not have be await expect.element(editor).toHaveTextContent("next draft"); launch.release(); - await expect.element(page.getByText("Message may not have been sent")).toBeVisible(); + await expect.element(page.getByText("Message not sent")).toBeVisible(); await expect.element(editor).toHaveTextContent("next draft"); // With no text there is nothing to copy. expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index b2535a81123e1..941fdcd9b389e 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -28,6 +28,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as TestClock from "effect/testing/TestClock"; import { RpcClientError } from "effect/rpc"; @@ -45,6 +46,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix import { archiveThread, interruptThreadTurn, + promoteQueuedRun, revertThreadCheckpoint, resumeThreadQueue, startThreadTurn, @@ -55,6 +57,8 @@ const layerTestRandom = Layer.succeed( SecureRandom.make((size) => new Uint8Array(size)), ); +class Refused extends Schema.TaggedError()("Refused", {}) {} + const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), label: "Test environment", @@ -634,6 +638,121 @@ describe("V2 environment commands", () => { }).pipe(Effect.provide(layerTestRandom)), ); + const turnSends = [ + { + name: "new thread's first message", + method: ORCHESTRATION_V2_WS_METHODS.launchThread, + send: (commandId: CommandId) => + startThreadTurn({ + commandId, + threadId: v2ThreadId, + message: { + messageId: MessageId.make(commandId), + role: "user", + text: "hi", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: v2Projection.thread.modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-06-20T00:00:00.000Z", + }, + }, + }), + }, + { + name: "queued message sent now", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }), + }, + { + name: "queued message steered", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + promoteQueuedRun({ + commandId, + threadId: v2ThreadId, + queuedRunId: RunId.make("queued"), + targetRunId: RunId.make("running"), + }), + }, + ] as const; + + const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")( + function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect) { + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] }); + const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session)); + const attempts: string[] = []; + const firstAttemptFailed = yield* Deferred.make(); + const healthyMethod = ( + healthySession.client as unknown as Record< + string, + (input: unknown) => Effect.Effect + > + )[turnSend.method]!; + const failingClient = { + ...healthySession.client, + [turnSend.method]: (input: { readonly commandId: CommandId }) => + Effect.gen(function* () { + attempts.push(input.commandId); + if (attempts.length > 1) return yield* healthyMethod(input); + yield* SubscriptionRef.set(supervisor.session, Option.none()); + yield* Deferred.succeed(firstAttemptFailed, undefined); + return yield* failure; + }), + } as unknown as WsRpcProtocolClient; + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + const sendFiber = yield* turnSend + .send(CommandId.make("command-turn-send")) + .pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.forkChild, + ); + yield* Deferred.await(firstAttemptFailed); + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + return { exit: yield* Fiber.await(sendFiber), attempts }; + }, + ); + + it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSend, + Effect.failCause(Cause.interrupt()), + ); + + expect(attempts).toEqual(["command-turn-send", "command-turn-send"]); + expect(Exit.isSuccess(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + + it.effect("doesn't resend a new thread's first message the server refused", () => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSends[0], + Effect.fail(new Refused()), + ); + + expect(attempts).toEqual(["command-turn-send"]); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + it.effect("Stop with no run left ends the thread's pull request watches", () => Effect.gen(function* () { const link = { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index ee17123e8839f..50e1449e3d5fc 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -315,28 +315,12 @@ const MAX_LOST_TRANSPORT_RESENDS = 2; // alone would leave the send pending forever. const MESSAGE_DISPATCH_TIMEOUT = "60 seconds"; -const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( - command: Extract, - resendAfterSocketLoss: boolean, -) { +const resendAfterSocketLoss = Effect.fn("EnvironmentCommands.resendAfterSocketLoss")(function* < + A, + E, + R, +>(attempt: Effect.Effect) { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const attempt = dispatch(command).pipe( - Effect.timeoutOrElse({ - duration: MESSAGE_DISPATCH_TIMEOUT, - orElse: () => - Effect.fail( - new EnvironmentRpcUnavailableError({ - environmentId: supervisor.target.environmentId, - ...translatableMessage( - msg("{host} did not confirm the message within 60 seconds.", { - host: supervisor.target.label, - }), - ), - }), - ), - }), - ); - if (!resendAfterSocketLoss) return yield* attempt; for (let resends = 0; ; resends += 1) { const attemptSession = yield* SubscriptionRef.get(supervisor.session); const exit = yield* Effect.exit(attempt); @@ -365,6 +349,30 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio } }); +const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( + command: Extract, + resend: boolean, +) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const attempt = dispatch(command).pipe( + Effect.timeoutOrElse({ + duration: MESSAGE_DISPATCH_TIMEOUT, + orElse: () => + Effect.fail( + new EnvironmentRpcUnavailableError({ + environmentId: supervisor.target.environmentId, + ...translatableMessage( + msg("{host} did not confirm the message within 60 seconds.", { + host: supervisor.target.label, + }), + ), + }), + ), + }), + ); + return yield* resend ? resendAfterSocketLoss(attempt) : attempt; +}); + const getProjection = (threadId: ThreadId) => request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); @@ -784,6 +792,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( input.message.attachments, attachments, ); + const resend = input.resendAfterSocketLoss ?? true; const bootstrap = input.bootstrap?.createThread; const prepareWorktree = input.bootstrap?.prepareWorktree; if (bootstrap !== undefined || prepareWorktree !== undefined) { @@ -815,7 +824,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ? {} : { branch: bootstrap.branch }), }; - return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { + const launch = request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -834,10 +843,10 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( attachments, }, }); + return yield* resend ? resendAfterSocketLoss(launch) : launch; } const requestedMode = input.dispatchMode ?? "auto"; - const resendAfterSocketLoss = input.resendAfterSocketLoss ?? true; if (requestedMode === "start") { return yield* dispatchMessage( { @@ -868,7 +877,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.freshContext ? { freshContext: true } : {}), dispatchMode: { type: "start_immediately" }, }, - resendAfterSocketLoss, + resend, ); } @@ -899,7 +908,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}), dispatchMode, }, - resendAfterSocketLoss, + resend, ); }); @@ -1156,25 +1165,29 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")( export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* ( input: ResumeThreadQueueInput, ) { - return yield* dispatch({ - ...(input.runId === undefined - ? { type: "queue.resume" as const } - : { type: "queued-run.start" as const, runId: input.runId }), - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + ...(input.runId === undefined + ? { type: "queue.resume" as const } + : { type: "queued-run.start" as const, runId: input.runId }), + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + }), + ); }); export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* ( input: PromoteQueuedRunInput, ) { - return yield* dispatch({ - type: "queued-message.promote-to-steer", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - queuedRunId: input.queuedRunId, - targetRunId: input.targetRunId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + type: "queued-message.promote-to-steer", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + queuedRunId: input.queuedRunId, + targetRunId: input.targetRunId, + }), + ); }); export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* ( From 02ea261f09d11a613c252c949c62627e56986fce Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:13:40 +0100 Subject: [PATCH 10/96] fix(server): long webhook prompts in the delivery log no longer end in a broken character (#40726) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../scheduledTasks/ScheduledTaskService.ts | 12 ++- .../ScheduledTaskService.webhook.test.ts | 22 ++++++ .../webhook-log-keeps-whole-emoji.e2e.ts | 75 +++++++++++++++++++ 3 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 68c95748d0ce8..3db6f783f649a 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -35,6 +35,7 @@ import * as Mac from "effect/crypto/Mac"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Exit from "effect/Exit"; import * as Duration from "effect/Duration"; @@ -90,6 +91,13 @@ const WEBHOOK_DEDUPE_LOG_PER_MINUTE = 10; const WEBHOOK_FILTERED_LOG_PER_MINUTE = 10; const WEBHOOK_DELIVERY_LOG_BODY_LIMIT = 64 * 1024; const WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT = 64 * 1024; +const loggedWebhookPrompt = (prompt: string) => + prompt.slice( + 0, + splitsSurrogatePair(prompt, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT) + ? WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT - 1 + : WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT, + ); const WEBHOOK_MAX_QUEUED_PER_TASK = 20; // Enforce the relay's per-task/minute limit here too; tunnel hostnames are public. const WEBHOOK_RATE_LIMIT_PER_MINUTE = 60; @@ -1947,7 +1955,7 @@ export const layer = Layer.effect( ${loggedBody}, ${input.request.body.byteLength}, ${truncated ? 1 : 0}, ${input.outcome}, ${input.signatureVerified ? 1 : 0}, ${encodeMissingFieldsJson(input.missing)}, - ${input.renderedPrompt?.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT) ?? null}, + ${input.renderedPrompt === null ? null : loggedWebhookPrompt(input.renderedPrompt)}, ${input.error ?? null} WHERE EXISTS (SELECT 1 FROM scheduled_tasks WHERE task_id = ${input.taskId}) -- A held request retried after a rate limit reuses its relay @@ -2636,7 +2644,7 @@ export const layer = Layer.effect( } else { if (taskJson !== null) yield* sql`UPDATE scheduled_task_webhook_pending SET task_json = ${taskJson} WHERE delivery_id = ${entry.delivery_id}`; - yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${rendered.prompt.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; + yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${loggedWebhookPrompt(rendered.prompt)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; if (!(yield* runWebhookDelivery(task, entry.delivery_id, rendered.prompt))) return; } yield* remove; diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts index e06ed817ac4f4..82db6f5e16407 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts @@ -571,6 +571,28 @@ it.effect("drops a character split by the delivery log's body limit", () => ), ); +it.effect("drops an emoji split by the delivery log's prompt limit", () => + withService(({ service }) => + Effect.gen(function* () { + const { task } = yield* service.upsert(yield* webhookTaskInput({ prompt: "{{body.text}}" })); + const limit = 64 * 1024; + const frameOpen = "".length; + // The emoji's high surrogate is the last code unit the log keeps. + const bodyText = JSON.stringify({ text: `${"a".repeat(limit - 1 - frameOpen)}๐Ÿ˜€ tail` }); + yield* service.triggerWebhook( + requestFor(task, { bodyText, body: new TextEncoder().encode(bodyText) }), + ); + const [summary] = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; + const { delivery } = yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: summary!.id, + }); + assert.equal(delivery.renderedPrompt!.slice(-3), "aaa"); + assert.equal(delivery.renderedPrompt!.length, limit - 1); + }), + ), +); + const queuedDeliveryCases = [ { change: "paused", diff --git a/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts new file mode 100644 index 0000000000000..acd9096465978 --- /dev/null +++ b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts @@ -0,0 +1,75 @@ +import { ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROMPT_LOG_LIMIT = 64 * 1024; +const FRAME_OPEN = "".length; + +const deliverStraddlingEmoji = Effect.fn("scenario.deliverStraddlingEmoji")( + function* (origin: string) { + const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); + const { projects } = yield* HttpClient.execute( + HttpClientRequest.get(`${origin}/api/projects`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)), + ); + const client = yield* rpcClient(T3_HOME, origin); + const { task } = yield* client["scheduledTasks.upsert"]({ + title: "Webhook log", + prompt: "{{body.text}}", + enabled: true, + schedule: { type: "webhook" }, + projectId: projects.find((project) => project.title === "webhook-log")!.id, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + // The emoji's high surrogate is the last code unit the delivery log keeps. + const text = `${"a".repeat(PROMPT_LOG_LIMIT - 1 - FRAME_OPEN)}๐Ÿ˜€ tail`; + yield* HttpClient.execute( + HttpClientRequest.post(`${origin}${task.webhook!.path}`).pipe( + HttpClientRequest.bodyJsonUnsafe({ text }), + ), + ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + }, + Effect.scoped, + Effect.provide(FetchHttpClient.layer), +); + +test( + "A long webhook prompt in the delivery log does not end in a broken character", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("webhook-log"); + await runPromise(deliverStraddlingEmoji(app.baseUrl ?? "")); + + await t3.open("/settings/scheduled-tasks"); + await screen.getByRole("button", "Actions for Webhook log").tap(); + await screen.getByRole("menuitem", "Deliveries").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByRole("button", /POST/).tap(); + const prompt = dialog.getByText(/^ { + const block = [...document.querySelectorAll("pre")].find((pre) => + pre.textContent?.startsWith(" Date: Sun, 22 Nov 2026 00:20:29 -0800 Subject: [PATCH 11/96] fix(server): a released ACP session no longer leaves its run stuck running (#40734) --- .../RunExecutionService.test.ts | 42 +++++++++++++++++++ .../orchestration-v2/RunExecutionService.ts | 14 +++---- 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 1d13620b75623..3667867904ec9 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -3596,6 +3596,48 @@ it.effect("ends a running root command when the provider stream fails mid-turn", }), ); +it.effect("fails the run when a released session's interrupt exits interrupted", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const key = "released-session-interrupted-interrupt"; + const { observed, finalEvents } = yield* captureRootRunTermination({ + key, + shouldFinalizeRun: () => Effect.succeed(true), + events: (ids) => + Stream.make({ + type: "provider_turn.updated" as const, + driver, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + nodeId: ids.rootNodeId, + runAttemptId: ids.attemptId, + nativeTurnRef: null, + ordinal: 1, + status: "running" as const, + startedAt: now, + completedAt: null, + }, + }).pipe( + Stream.concat( + Stream.fail( + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver, + providerSessionId: ProviderSessionId.make(`session:${key}`), + raisedByT3: true, + cause: "Provider sign-in changed.", + }), + ), + ), + ), + // An ACP session whose scope is already closing interrupts the join. + interruptTurn: () => Effect.interrupt, + }); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + assert.isTrue(finalEvents.some((event) => event.type === "run.updated")); + }), +); + it.effect("keeps a running root command open when a write fails under a live provider", () => Effect.gen(function* () { const key = "write-error-running-command"; diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 34cc31f98fa09..1e301e12fa8fe 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -2135,13 +2135,13 @@ export const layer: Layer.Layer< }) .pipe( Effect.as(true), - Effect.catchCauseIf( - (interruptCause) => !Cause.hasInterruptsOnly(interruptCause), - (interruptCause) => - Effect.logWarning( - "orchestration V2 failed to interrupt turn after ingestion failure", - { runId: input.run.id, cause: interruptCause }, - ).pipe(Effect.as(false)), + // An adapter whose session scope is closing exits interrupted. That is + // its fiber, not this one: Effect never hands a fiber its own interrupt. + Effect.catchCause((interruptCause) => + Effect.logWarning( + "orchestration V2 failed to interrupt turn after ingestion failure", + { runId: input.run.id, cause: interruptCause }, + ).pipe(Effect.as(false)), ), // A failed interrupt leaves the stored turn running so the next start // retries it. The snapshot is cached before it is published, so it may From cd3a57ac7221b4151fb7c64a132d9ba59d98beaa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 00:26:39 -0800 Subject: [PATCH 12/96] feat(web): sidebar thread rows show the environment instead of the branch (#40736) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/Sidebar.tsx | 16 -------- .../src/components/ThreadStatusIndicators.tsx | 38 +---------------- .../components/sidebar/SidebarThreadRow.tsx | 41 +++++++------------ apps/web/src/i18n/translations/de.json | 2 - apps/web/src/i18n/translations/en.json | 2 - apps/web/src/i18n/translations/es.json | 2 - apps/web/src/i18n/translations/fr.json | 2 - apps/web/src/i18n/translations/ja.json | 2 - apps/web/src/i18n/translations/ko.json | 2 - apps/web/src/i18n/translations/pt-BR.json | 2 - apps/web/src/i18n/translations/ru.json | 2 - apps/web/src/i18n/translations/sv.json | 2 - apps/web/src/i18n/translations/zh.json | 2 - 13 files changed, 15 insertions(+), 100 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 45e00246e2c6d..98ed2224169cd 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -171,7 +171,6 @@ import { resolveThreadRouteTarget, } from "../threadRoutes"; import type { SidebarThreadSummary } from "../types"; -import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { ProjectRowActions } from "./ProjectComboboxRow"; @@ -1162,19 +1161,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); - const scratchMachineLabelFor = ( - thread: Pick, - ) => { - if (!showProjectEnvironments) return null; - const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`); - if ( - !project || - !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot) - ) { - return null; - } - return environmentLabelById.get(thread.environmentId) ?? null; - }; // Pinning from a row keeps rows in place while the menu is open. const projectScopeItems = useOrderWhileOpen( lookupProjectScopeItems, @@ -3523,14 +3509,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve jumpLabel={ showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null } - currentEnvironmentId={primaryEnvironmentId} environmentLabel={ environmentLabelById.get(thread.environmentId) ?? null } environmentMachine={ environmentMachineById.get(thread.environmentId) ?? "server" } - scratchMachineLabel={scratchMachineLabelFor(thread)} project={ projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 9c5e7fa3d830d..905d9cb2131fe 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -19,7 +19,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; import { msg, T, useGT, useMessages } from "gt-react"; -import { FolderGit2Icon, TerminalIcon } from "lucide-react"; +import { TerminalIcon } from "lucide-react"; import { m, type MessageResolver } from "../i18n/messages"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; @@ -53,7 +53,6 @@ import { } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; -import { formatWorktreePathForDisplay } from "../worktreeCleanup"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { PULL_REQUEST_STATE_PRESENTATION, @@ -770,41 +769,6 @@ export function ThreadTerminalStatusButton({ ); } -export function ThreadWorktreeIndicator({ - thread, -}: { - thread: Pick; -}) { - const gt = useGT(); - const worktreePath = thread.worktreePath?.trim(); - if (!worktreePath) { - return null; - } - - const displayPath = formatWorktreePathForDisplay(worktreePath); - const tooltip = thread.branch - ? gt("Worktree: {path} ({branch})", { path: displayPath, branch: thread.branch }) - : gt("Worktree: {path}", { path: displayPath }); - - return ( - - - } - > - - - {tooltip} - - ); -} - function ThreadStatusLabel({ status, compact = false, diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 878cbc894bb88..2aa9be4c244a6 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -3,6 +3,7 @@ import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; import { discardComposerDraft } from "../../lib/discardComposerDraft"; +import { formatWorktreePathForDisplay } from "../../worktreeCleanup"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { requestCustomSnooze } from "../CustomSnoozeDialog"; import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; @@ -47,6 +48,7 @@ import { CircleDashedIcon, CircleDotDashedIcon, ClockIcon, + FolderGit2Icon, GitBranchIcon, MessageCircleQuestionIcon, PinIcon, @@ -105,7 +107,6 @@ import { resolveLocalCheckoutBranchMismatch } from "../BranchToolbar.logic"; import { ThreadPullRequestBadgeControl, ThreadPullRequestsMiniList, - ThreadWorktreeIndicator, prStatusIndicator, resolveThreadPullRequestBadge, terminalStatusFromRunningIds, @@ -285,6 +286,7 @@ function SidebarThreadTooltip({ terminalProcessCount: number; }) { const driverKind = providerEntry?.driverKind ?? null; + const worktreePath = thread.worktreePath?.trim(); const previousProviderNames = thread.providerInstanceHistory .filter((instanceId) => instanceId !== modelInstanceId) .map((instanceId) => providerEntryByInstanceId.get(instanceId)?.displayName ?? instanceId); @@ -324,6 +326,12 @@ function SidebarThreadTooltip({ ) : null} + {worktreePath ? ( +
+ + +
+ ) : null} {branchMismatch ? (
@@ -575,7 +583,7 @@ function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: type SidebarThreadRowProps = { thread: SidebarThreadSummary; // "folder" is a one-line row inside a boring sidebar project folder; - // "folder-multiline" adds the card's branch and PR line under it. + // "folder-multiline" adds the card's environment and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; @@ -598,10 +606,8 @@ type SidebarThreadRowProps = { // Read at click time; a prop would re-render every row on entering or leaving a thread route. readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; - currentEnvironmentId: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; - scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; @@ -863,9 +869,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; - const isRemote = thread.environmentId !== props.currentEnvironmentId; - const showsScratchMachine = !checkoutThread.branch && props.scratchMachineLabel !== null; - const detailsTooltip = ( - - - ) : null; const diff = latestRunDiff(thread); // Only the trailing icons would remain, so the row moves them to the title line instead. const metaLineEmpty = - !checkoutThread.branch && - !showsScratchMachine && + props.environmentLabel === null && prBadge === null && issueBadge === null && diff === null && runningTerminalIds.length === 0; const metaLine = metaLineEmpty ? null : (
- {checkoutThread.branch ? ( - <> - - - - - - ) : showsScratchMachine ? ( + {props.environmentLabel !== null ? ( <> - {props.scratchMachineLabel} + {props.environmentLabel} ) : ( @@ -1305,7 +1294,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP aria-hidden className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" > - {remoteMachineIcon} - {remoteMachineIcon} Date: Sun, 22 Nov 2026 00:52:35 -0800 Subject: [PATCH 13/96] fix: a failed checkpoint capture keeps Edit from here for conversation rewind (#40745) --- .../CheckpointCaptureService.test.ts | 17 ++++++++++ .../CheckpointRollbackService.test.ts | 31 ++++++++++++++++--- .../CheckpointRollbackService.ts | 4 ++- .../src/orchestration-v2/Orchestrator.ts | 3 +- .../src/orchestration-v2/ProjectionStore.ts | 4 +-- .../src/orchestration-v2/runtimeLayer.test.ts | 22 +++++++++++++ apps/web/src/session-logic.test.ts | 10 +++++- apps/web/src/session-logic.ts | 6 ++-- .../client-runtime/src/operations/commands.ts | 4 +-- 9 files changed, 86 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index aa85cd675dc1a..2110bc3eca027 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -956,6 +956,23 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { scopeId: cancelledScopeId, }); assert.deepEqual(afterRewind.preservedCheckpointOrdinals, [0]); + + // A failed capture still records which run ended there; the next capture must keep that link. + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-cancelled:captured-error"), + type: "checkpoint.captured", + threadId: cancelledThreadId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + providerInstanceId, + occurredAt: cancelledAt, + payload: { ...captured, status: "error" }, + }); + const afterFailedCapture = yield* projectionStore.getCheckpointCaptureContext( + cancelledThreadId, + { runId: cancelledRunId, scopeId: cancelledScopeId }, + ); + assert.deepEqual([...afterFailedCapture.preservedCheckpointOrdinals].toSorted(), [0, 1]); }), ); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index 2f41a9a379306..ff368dccb64d9 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -401,9 +401,14 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( - "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles", - ({ restoreFiles }) => +it.effect.each([ + { restoreFiles: true, status: "ready" }, + { restoreFiles: false, status: "ready" }, + // A failed capture still pins the conversation. + { restoreFiles: false, status: "error" }, +])( + "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles to a $status checkpoint", + ({ restoreFiles, status }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -438,7 +443,7 @@ it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( providerInstanceId, }, providerSession: undefined, - checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }, + checkpoint: { id: checkpointId, scopeId, status, appRunOrdinal: 0 }, scope: { id: scopeId, cwd: worktreePath }, runsToRollback: [], targetAttempt: undefined, @@ -840,7 +845,7 @@ const seedRollbackHistory = Effect.gen(function* () { ), ), ); - const rollback = (ordinal: number) => + const rollback = (ordinal: number, restoreFiles?: boolean) => Effect.gen(function* () { const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; yield* service.execute({ @@ -848,6 +853,7 @@ const seedRollbackHistory = Effect.gen(function* () { providerThreadId, scopeId, checkpointId: checkpointId(ordinal), + ...(restoreFiles === undefined ? {} : { restoreFiles }), }); }).pipe(Effect.provide(serviceLayer)); @@ -943,6 +949,21 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe }), ); + it.effect("rewinds the conversation to a run whose snapshot capture failed", () => + Effect.gen(function* () { + const history = yield* seedRollbackHistory; + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE orchestration_v2_projection_checkpoints + SET status = 'error', payload_json = json_set(payload_json, '$.status', 'error') + WHERE checkpoint_id = ${history.checkpointId(2)}`; + + yield* history.rollback(2, false); + + assert.deepEqual(history.rollbackCounts, [4]); + assert.deepEqual(history.restored, []); + }), + ); + it.effect( "rewinds stopped runs repeatedly without counting discarded provider turns again", () => diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 6f9fe79cfde3b..8d6fd1c09441d 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -178,8 +178,10 @@ export const layer: Layer.Layer< // A repository's checkpoints follow the thread's; they are not a place to rewind to. typeof scope.repositoryPath === "string" || checkpoint.scopeId !== scope.id || - // Missing snapshots support conversation rewind, and restoring a task folder's repositories. + // Missing or failed snapshots support conversation rewind; missing ones also restoring a + // task folder's repositories. (checkpoint.status !== "ready" && + !(checkpoint.status === "error" && !restoreFiles) && !(checkpoint.status === "missing" && (!restoreFiles || linkedProjectFolder))) ) { return yield* invalidTarget(); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 995ff63b25747..61f5027793569 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14534,9 +14534,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio targetCheckpoint.appRunOrdinal ?? 0, ) !== null, ); - // Missing snapshots otherwise support conversation rewind only. + // Missing or failed snapshots otherwise support conversation rewind only. if ( targetCheckpoint.status !== "ready" && + !(targetCheckpoint.status === "error" && command.restoreFiles === false) && !( targetCheckpoint.status === "missing" && (command.restoreFiles === false || restoresRepositories) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 6c8308706b651..a42679d304765 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -6379,7 +6379,7 @@ export const layer: Layer.Layer = runRows[0] === undefined ? undefined : yield* decodeRunPayload(runRows[0].payload_json); - const preservedCheckpoint = sql`(status = 'ready' OR (status = 'missing' AND run_id IS NOT NULL))`; + const preservedCheckpoint = sql`(status = 'ready' OR (status IN ('missing', 'error') AND run_id IS NOT NULL))`; const [ nodeRows, scopeRows, @@ -6491,7 +6491,7 @@ export const layer: Layer.Layer = checkpoint === undefined || scope === undefined || checkpoint.scopeId !== scope.id || - (checkpoint.status !== "ready" && checkpoint.status !== "missing") || + checkpoint.status === "stale" || providerThread.id !== thread.activeProviderThreadId || providerThread.providerInstanceId !== thread.modelSelection.instanceId ) diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b5072355659ef..843e51da40423 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1878,6 +1878,28 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { [], ); assert.deepEqual(yield* outbox.listByCommandId(commandId), []); + if (status === "error") { + // A failed capture still pins the conversation. + const conversationCommandId = CommandId.make("runtime-rollback-error-conversation"); + const conversationOnly = yield* orchestrator.dispatch({ + type: "checkpoint.rollback", + commandId: conversationCommandId, + threadId, + checkpointId, + scopeId: scope.id, + restoreFiles: false, + }); + assert.deepEqual( + conversationOnly.storedEvents.map((stored) => stored.event.type), + ["thread.metadata-updated", "checkpoint.rollback-requested"], + ); + assert.deepEqual( + (yield* outbox.listByCommandId(conversationCommandId)).map( + (effect) => effect.request.type, + ), + ["provider-thread.rollback"], + ); + } } } }).pipe(Effect.provide(Layer.fresh(layerTest))), diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index f4670665add6c..2155fedaa83c1 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -290,7 +290,10 @@ describe("V2 session presentation", () => { }, }; }); - const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({ + const checkpoint = ( + ordinal: number, + status: "ready" | "missing" | "stale" | "error" = "ready", + ) => ({ runId: runId(ordinal), checkpointTurnCount: ordinal, checkpointRef: `checkpoint-${ordinal}` as never, @@ -326,6 +329,11 @@ describe("V2 session presentation", () => { "user-1": 0, "user-2": 1, }); + // A failed snapshot capture still pins the conversation; only file restore needs one. + expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({ + "user-1": 0, + "user-2": 1, + }); }); it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 1122c3122aca0..5196ee43458d8 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1153,10 +1153,10 @@ export function deriveRevertTurnCountByUserMessageId(input: { return byUserMessageId; } -// A missing snapshot (no git, or a side chat) still pins a conversation position; only -// restoring files needs a ready one. +// A missing or failed snapshot (no git, a side chat, a capture error) still pins a +// conversation position; only restoring files needs a ready one. function isRewindableCheckpoint(checkpoint: Pick) { - return checkpoint.status === "ready" || checkpoint.status === "missing"; + return checkpoint.status !== "stale"; } export function findRevertCheckpoint( diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 50e1449e3d5fc..0ea95420460a7 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1074,9 +1074,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea ); if ( checkpoint === undefined || - // Missing snapshots support conversation rewind only. + // Missing or failed snapshots support conversation rewind only. (checkpoint.status !== "ready" && - !(input.restoreFiles === false && checkpoint.status === "missing")) + !(input.restoreFiles === false && checkpoint.status !== "stale")) ) { const target = input.checkpointId === undefined From 15a3daa32a745bc56be9d7dbb346d80661e6b7bd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:00:28 -0800 Subject: [PATCH 14/96] docs(claude): mobile shows the compact chip too (#40755) --- docs/user/providers-claude.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 84c13d30c4c84..00b27e02ae23d 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -63,8 +63,8 @@ When you return to a large thread after Claude's prompt cache expires, a **Compact** chip with the thread's token count shows next to the send button. While it is on, Enter summarizes the history first, then sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows no chip: an eligible message sent -from it summarizes first. The cache lasts about an hour on a Claude +history for that message. The mobile app shows the same chip, labelled with the +token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using composer commands. From e3f9db2447fcfd82e76f7782ca5254e2c7ad80a6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:08:22 -0800 Subject: [PATCH 15/96] fix(server): TanStack Source pull requests open from every client, and private ones work end to end (#40741) --- .../pull-requests/PullRequestListRow.tsx | 12 ++ .../pull-requests/PullRequestRouteScreen.tsx | 11 ++ .../pull-requests/pullRequestGlyphs.ts | 1 + .../features/pull-requests/pullRequestList.ts | 1 + apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/server/src/git/GitManager.test.ts | 133 ++++++++++++++++ apps/server/src/git/GitManager.ts | 144 +++++++++++++++++- .../toolkits/pullRequests/handlers.test.ts | 15 +- .../src/mcp/toolkits/pullRequests/handlers.ts | 2 + .../src/mcp/toolkits/pullRequests/tools.ts | 8 + .../src/provider/agentContextBudget.json | 2 +- .../src/pullRequest/PullRequestService.ts | 4 + .../SourceControlProviderRegistry.ts | 9 ++ .../pullRequest/PullRequestDetailLayout.tsx | 29 +++- .../pullRequest/PullRequestDetailPanel.tsx | 2 + .../components/pullRequest/PullRequestRow.tsx | 4 + docs/user/source-control.md | 4 +- packages/contracts/src/pullRequest.ts | 8 + .../src/server/PullRequestProvider.ts | 3 + .../src/server/SourceControlProvider.ts | 14 ++ .../TanStackSourcePullRequestProvider.test.ts | 138 +++++++++++++++++ ...anStackSourceSourceControlProvider.test.ts | 107 ++++++++++++- .../TanStackSourceSourceControlProvider.ts | 46 +++++- .../src/server/tanStackSourceHosts.test.ts | 19 +++ .../src/server/tanStackSourceHosts.ts | 16 +- .../src/server/tanStackSourceJson.test.ts | 1 + .../src/server/tanStackSourceJson.ts | 27 +++- .../src/shared/definition.test.ts | 16 ++ .../src/shared/definition.ts | 19 ++- 38 files changed, 774 insertions(+), 31 deletions(-) create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx index 5daf5ef20565b..7b904c8e33105 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx @@ -122,6 +122,7 @@ export const PullRequestListRow = memo( ), item.title, status.label, + item.visibility === "private" ? gt("Private") : null, conflict ? conflict.label.toLowerCase() : null, gt("by {author}", { author: item.author?.login ?? gt("unknown author") }), review ? review.accessibleLabel : null, @@ -178,6 +179,17 @@ export const PullRequestListRow = memo( {item.repository} #{item.number} + {item.visibility === "private" ? ( + + + + ) : null} {item.stack ? ( {status.label} )} + {"visibility" in pr && pr.visibility === "private" ? ( + + + {gt("Private")} + + ) : null} {"changedFiles" in pr && pr.changedFiles !== undefined ? ( diff --git a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts index fa79d882cc23d..16b84c596d627 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts @@ -7,4 +7,5 @@ export const PullRequestGlyph = { merged: "arrow.triangle.merge", stack: "square.3.layers.3d", conflicting: "exclamationmark.triangle", + private: { ios: "lock.fill", android: "lock" }, } as const satisfies Record; diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts index e7c2f5de769c4..3b30c11d65e64 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts @@ -190,6 +190,7 @@ export function pullRequestListRowsAreEqual( previous.title === next.title && previous.url === next.url && previous.state === next.state && + previous.visibility === next.visibility && previous.isDraft === next.isDraft && previous.mergeability === next.mergeability && previous.baseBranch === next.baseBranch && diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f538b87920412..039e1ddadd0bf 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tippe auf eine Person, um ein Review anzufordern. Tippe auf einen angefragten Reviewer, um die Anfrage zu entfernen. ร„nderungen werden beim SchlieรŸen dieses Fensters gesendet.", "8d3770f150f0bcb4": "Angefragt", "fff1c3d17603f394": "Dieser Anbieter akzeptiert eine Reviewer-ID, kann aber keine Kandidaten auflisten.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Basis-Branch {branch} kopieren", "06a684782801e8f7": "Head-Branch {branch} kopieren", "8e4f3c862193b8a5": "Bearbeiten", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 745201ad99094..91170171c1621 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tap someone to request a review. Tap a requested reviewer to remove the request. Changes are sent when you close this sheet.", "8d3770f150f0bcb4": "Requested", "fff1c3d17603f394": "This provider accepts a reviewer ID but cannot list candidates.", + "bbb7d40a7ad7ab71": "Private", "85ae9979ad3b0c1e": "Copy base branch {branch}", "06a684782801e8f7": "Copy head branch {branch}", "8e4f3c862193b8a5": "Edit", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index fb134339cd3c4..398c20ce17f1f 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Toca a alguien para solicitarle una revisiรณn. Toca a un revisor solicitado para quitar la solicitud. Los cambios se envรญan al cerrar esta hoja.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este proveedor acepta un ID de revisor, pero no puede listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar la rama base {branch}", "06a684782801e8f7": "Copiar la rama head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index d6aef220df3a2..1734d91934a04 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Touchez une personne pour lui demander une revue. Touchez un relecteur sollicitรฉ pour retirer la demande. Les modifications sont envoyรฉes ร  la fermeture de ce panneau.", "8d3770f150f0bcb4": "Sollicitรฉ", "fff1c3d17603f394": "Ce fournisseur accepte un ID de relecteur mais ne peut pas lister les candidats.", + "bbb7d40a7ad7ab71": "Privรฉ", "85ae9979ad3b0c1e": "Copier la branche de base {branch}", "06a684782801e8f7": "Copier la branche de tรชte {branch}", "8e4f3c862193b8a5": "Modifier", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 8cd9fba5c8332..113ada551f17d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -2844,6 +2844,7 @@ "f9d3c8aa453829ce": "ใƒฆใƒผใ‚ถใƒผใ‚’ใ‚ฟใƒƒใƒ—ใ™ใ‚‹ใจใƒฌใƒ“ใƒฅใƒผใ‚’ใƒชใ‚ฏใ‚จใ‚นใƒˆใ—ใพใ™ใ€‚ใƒชใ‚ฏใ‚จใ‚นใƒˆๆธˆใฟใฎใƒฌใƒ“ใƒฅใ‚ขใƒผใ‚’ใ‚ฟใƒƒใƒ—ใ™ใ‚‹ใจใƒชใ‚ฏใ‚จใ‚นใƒˆใ‚’ๅ‰Š้™คใ—ใพใ™ใ€‚ๅค‰ๆ›ดใฏใ“ใฎใ‚ทใƒผใƒˆใ‚’้–‰ใ˜ใŸใจใใซ้€ไฟกใ•ใ‚Œใพใ™ใ€‚", "8d3770f150f0bcb4": "ใƒชใ‚ฏใ‚จใ‚นใƒˆๆธˆใฟ", "fff1c3d17603f394": "ใ“ใฎใƒ—ใƒญใƒใ‚คใƒ€ใƒผใฏใƒฌใƒ“ใƒฅใ‚ขใƒผ ID ใ‚’ๅ—ใ‘ไป˜ใ‘ใพใ™ใŒใ€ๅ€™่ฃœใ‚’ไธ€่ฆง่กจ็คบใงใใพใ›ใ‚“ใ€‚", + "bbb7d40a7ad7ab71": "ใƒ—ใƒฉใ‚คใƒ™ใƒผใƒˆ", "85ae9979ad3b0c1e": "ใƒ™ใƒผใ‚นใƒ–ใƒฉใƒณใƒ {branch} ใ‚’ใ‚ณใƒ”ใƒผ", "06a684782801e8f7": "ใƒ˜ใƒƒใƒ‰ใƒ–ใƒฉใƒณใƒ {branch} ใ‚’ใ‚ณใƒ”ใƒผ", "8e4f3c862193b8a5": "็ทจ้›†", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 731eaeecaec22..7768bd410d434 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -2848,6 +2848,7 @@ "f9d3c8aa453829ce": "๊ฒ€ํ† ๋ฅผ ์š”์ฒญํ•˜๋ ค๋ฉด ์‚ฌ๋žŒ์„ ํƒญํ•˜์„ธ์š”. ์š”์ฒญ์„ ์ œ๊ฑฐํ•˜๋ ค๋ฉด ์š”์ฒญ๋œ ๊ฒ€ํ† ์ž๋ฅผ ํƒญํ•˜์„ธ์š”. ๋ณ€๊ฒฝ ์‚ฌํ•ญ์€ ์ด ์‹œํŠธ๋ฅผ ๋‹ซ์„ ๋•Œ ์ „์†ก๋ฉ๋‹ˆ๋‹ค.", "8d3770f150f0bcb4": "์š”์ฒญ๋จ", "fff1c3d17603f394": "์ด ์ œ๊ณต์ž๋Š” ๊ฒ€ํ† ์ž ID๋ฅผ ๋ฐ›์ง€๋งŒ ํ›„๋ณด๋ฅผ ๋‚˜์—ดํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", + "bbb7d40a7ad7ab71": "๋น„๊ณต๊ฐœ", "85ae9979ad3b0c1e": "๊ธฐ์ค€ ๋ธŒ๋žœ์น˜ {branch} ๋ณต์‚ฌ", "06a684782801e8f7": "ํ—ค๋“œ ๋ธŒ๋žœ์น˜ {branch} ๋ณต์‚ฌ", "8e4f3c862193b8a5": "ํŽธ์ง‘", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 2c4ee1bc64fc4..88dbb8da5cd87 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Toque em alguรฉm para solicitar uma revisรฃo. Toque em um revisor solicitado para remover a solicitaรงรฃo. As alteraรงรตes sรฃo enviadas quando vocรช fecha esta folha.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este provedor aceita um ID de revisor, mas nรฃo consegue listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar branch base {branch}", "06a684782801e8f7": "Copiar branch head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c4f78e560083b..2d0fb55302031 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -2899,6 +2899,7 @@ "f9d3c8aa453829ce": "ะะฐะถะผะธั‚ะต ะฝะฐ ั‡ะตะปะพะฒะตะบะฐ, ั‡ั‚ะพะฑั‹ ะทะฐะฟั€ะพัะธั‚ัŒ ั€ะตะฒัŒัŽ. ะะฐะถะผะธั‚ะต ะฝะฐ ะทะฐะฟั€ะพัˆะตะฝะฝะพะณะพ ั€ะตะฒัŒัŽะตั€ะฐ, ั‡ั‚ะพะฑั‹ ะพั‚ะผะตะฝะธั‚ัŒ ะทะฐะฟั€ะพั. ะ˜ะทะผะตะฝะตะฝะธั ะพั‚ะฟั€ะฐะฒะปััŽั‚ัั ะฟั€ะธ ะทะฐะบั€ั‹ั‚ะธะธ ัั‚ะพะน ะฟะฐะฝะตะปะธ.", "8d3770f150f0bcb4": "ะ—ะฐะฟั€ะพัˆะตะฝ", "fff1c3d17603f394": "ะญั‚ะพั‚ ะฟั€ะพะฒะฐะนะดะตั€ ะฟั€ะธะฝะธะผะฐะตั‚ ID ั€ะตะฒัŒัŽะตั€ะฐ, ะฝะพ ะฝะต ะผะพะถะตั‚ ะฟะพะบะฐะทะฐั‚ัŒ ัะฟะธัะพะบ ะบะฐะฝะดะธะดะฐั‚ะพะฒ.", + "bbb7d40a7ad7ab71": "ะŸั€ะธะฒะฐั‚ะฝั‹ะน", "85ae9979ad3b0c1e": "ะšะพะฟะธั€ะพะฒะฐั‚ัŒ ะฑะฐะทะพะฒัƒัŽ ะฒะตั‚ะบัƒ {branch}", "06a684782801e8f7": "ะšะพะฟะธั€ะพะฒะฐั‚ัŒ head-ะฒะตั‚ะบัƒ {branch}", "8e4f3c862193b8a5": "ะ˜ะทะผะตะฝะธั‚ัŒ", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index fa3a3dd6d039f..70617afd183ca 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tryck pรฅ nรฅgon fรถr att begรคra en granskning. Tryck pรฅ en begรคrd granskare fรถr att ta bort begรคran. ร„ndringarna skickas nรคr du stรคnger det hรคr bladet.", "8d3770f150f0bcb4": "Begรคrd", "fff1c3d17603f394": "Leverantรถren accepterar ett granskar-id men kan inte lista kandidater.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Kopiera basgrenen {branch}", "06a684782801e8f7": "Kopiera huvudgrenen {branch}", "8e4f3c862193b8a5": "Redigera", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f36e76805c298..485d4206bf054 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -2848,6 +2848,7 @@ "f9d3c8aa453829ce": "่ฝป็‚นๆŸไบบไปฅ่ฏทๆฑ‚ๅฎกๆŸฅใ€‚่ฝป็‚นๅทฒ่ฏทๆฑ‚็š„ๅฎกๆŸฅ่€…ไปฅ็งป้™ค่ฏทๆฑ‚ใ€‚ๅ…ณ้—ญๆญค้ขๆฟๆ—ถไผšๅ‘้€ๆ›ดๆ”นใ€‚", "8d3770f150f0bcb4": "ๅทฒ่ฏทๆฑ‚", "fff1c3d17603f394": "ๆญคๆไพ›ๆ–นๆŽฅๅ—ๅฎกๆŸฅ่€… ID๏ผŒไฝ†ๆ— ๆณ•ๅˆ—ๅ‡บๅ€™้€‰ไบบใ€‚", + "bbb7d40a7ad7ab71": "็งๆœ‰", "85ae9979ad3b0c1e": "ๅคๅˆถๅŸบ็ก€ๅˆ†ๆ”ฏ {branch}", "06a684782801e8f7": "ๅคๅˆถๅคด้ƒจๅˆ†ๆ”ฏ {branch}", "8e4f3c862193b8a5": "็ผ–่พ‘", diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 94247273e1ca0..1bce13cb0f020 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -86,6 +86,8 @@ interface FakeProviderScenario { kind?: string; /** False for a host that opens every change request ready for review. */ createsDraftChangeRequests?: boolean; + /** The companion repository of a host with private change requests. */ + privateRemote?: { readonly url: string; readonly repository: string }; /** Answers to successive change request listings, whatever their head selector. */ prListSequence?: ReadonlyArray>; prListByHeadSelector?: Record>; @@ -124,6 +126,7 @@ type FakeProviderCall = readonly headSelector: string; readonly title: string; readonly draft: unknown; + readonly private?: boolean; } | { readonly operation: "getChangeRequest"; readonly reference: string } | { @@ -483,6 +486,9 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { service: { kind, createsDraftChangeRequests: scenario.createsDraftChangeRequests ?? true, + ...(scenario.privateRemote === undefined + ? {} + : { privateChangeRequestRemote: () => Effect.succeed(scenario.privateRemote!) }), ...headBranchProbe, listChangeRequests: (input) => record(input.cwd, { @@ -517,6 +523,7 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { headSelector: input.headSelector, title: input.title, draft: "draft" in input ? input.draft : undefined, + ...(input.private === undefined ? {} : { private: input.private }), }), getDefaultBranch: (input) => record(input.cwd, { operation: "getDefaultBranch" }).pipe( @@ -5106,6 +5113,132 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect( + "createPullRequest opens a private PR from the companion and never pushes to origin", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const companionDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "sec/fix"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "fix.txt"), "fix\n"); + yield* runGit(repoDir, ["add", "fix.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fix"]); + const heads = (remote: string) => + runGit(repoDir, ["ls-remote", "--heads", remote]).pipe( + Effect.map((result) => + result.stdout + .split("\n") + .flatMap((line) => (line ? [line.split("\t")[1]] : [])) + .toSorted(), + ), + ); + const createPrivate = (manager: GitManager.GitManager["Service"]) => + manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + private: true, + }); + + // A host without private pull requests refuses before anything is pushed. + const unsupported = yield* makeManager({ providerScenario: { prListSequence: [[]] } }); + const refused = yield* Effect.flip(createPrivate(unsupported.manager)); + expect(refused.message).toContain("has no private pull requests"); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(unsupported.providerCalls)).toEqual([]); + + const privateRemote = { url: companionDir, repository: "pingdotgg/codething-mvp.private" }; + const open = { + number: 9, + title: "Fix", + url: "https://source.tanstack.com/@pingdotgg/codething-mvp/pull/9", + baseRefName: "main", + headRefName: "sec/fix", + headRepositoryNameWithOwner: privateRemote.repository, + }; + const supported = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[], [open]] }, + }); + expect(yield* createPrivate(supported.manager)).toMatchObject({ + status: "created", + number: 9, + }); + expect(yield* heads(companionDir)).toEqual(["refs/heads/sec/fix"]); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + // The branch tracks the companion, which is how status finds its pull request. + expect( + (yield* runGit(repoDir, [ + "rev-parse", + "--abbrev-ref", + "sec/fix@{upstream}", + ])).stdout.trim(), + ).toBe("pingdotgg/sec/fix"); + expect( + (yield* runGit(repoDir, ["config", "--get", "branch.sec/fix.pushRemote"])).stdout.trim(), + ).toBe("pingdotgg"); + expect( + supported.providerCalls.flatMap((call) => + call.operation === "createChangeRequest" ? [call] : [], + ), + ).toMatchObject([{ baseRefName: "main", headSelector: "sec/fix", private: true }]); + + // Later commits follow the recorded push remote. + NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n"); + yield* runGit(repoDir, ["add", "late.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Late"]); + const again = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[open]] }, + }); + expect(yield* createPrivate(again.manager)).toMatchObject({ + status: "opened_existing", + number: 9, + }); + const localHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim(); + expect( + (yield* runGit(repoDir, ["ls-remote", companionDir, "refs/heads/sec/fix"])).stdout, + ).toContain(localHead); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(again.providerCalls)).toEqual([]); + + // A lookup answered before the create must not hide the pull request the create returns. + yield* runGit(repoDir, ["checkout", "-b", "sec/two", "main"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "two.txt"), "two\n"); + yield* runGit(repoDir, ["add", "two.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Two"]); + const two = { ...open, number: 10, headRefName: "sec/two" }; + const warmed = yield* makeManager({ + providerScenario: { privateRemote, prListByHeadSelector: { "sec/two": [two] } }, + }); + const lookup = warmed.manager.branchPullRequest({ cwd: repoDir, branch: "sec/two" }); + expect(yield* lookup).toBeNull(); + expect(yield* createPrivate(warmed.manager)).toMatchObject({ status: "opened_existing" }); + expect(yield* lookup).toMatchObject({ number: 10 }); + yield* runGit(repoDir, ["checkout", "sec/fix"]); + + // So does a create that forgets to ask for private: it never publishes the branch. + NodeFS.writeFileSync(NodePath.join(repoDir, "later.txt"), "later\n"); + yield* runGit(repoDir, ["add", "later.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Later"]); + const forgetful = yield* makeManager({ + providerScenario: { privateRemote, prListOtherwise: [open] }, + }); + yield* Effect.exit( + forgetful.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + }), + ); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + }), + ); + it.effect("createPullRequest pushes to the push remote and never to the base branch", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index db62af1f79b69..dedf2d19f54ed 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -199,6 +199,12 @@ export class GitManager extends Context.Service< readonly body: string; readonly baseBranch?: string | undefined; readonly draft?: boolean | undefined; + /** + * Opens it where only people with write access see it. The branch goes to the host's + * private companion repository and never to the repository itself. Fails on a host + * without private pull requests. + */ + readonly private?: boolean | undefined; }) => Effect.Effect; readonly subscribePullRequestStateChanges: Effect.Effect< Stream.Stream, @@ -2881,9 +2887,131 @@ export const make = Effect.gen(function* () { }), ); - const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( - "GitManager.createPullRequest", - )(function* (input) { + const openPrivatePullRequest = Effect.fn("GitManager.openPrivatePullRequest")(function* ( + input: Parameters[0], + ) { + const { cwd } = input; + const provider = yield* sourceControlProvider(cwd); + const definition = sourceControlDefinitions.get(provider.kind); + const terms = definition.changeRequest; + const fail = (detail: string, cause?: unknown) => + new GitManagerError({ + operation: "createPullRequest", + cwd, + detail, + ...(cause === undefined ? {} : { cause }), + }); + if (provider.privateChangeRequestRemote === undefined) { + return yield* fail( + `${definition.label} has no private ${terms.plural}. Nothing was pushed. Leave out private to open a public one.`, + ); + } + const status = yield* gitCore.statusDetails(cwd); + const branch = status.branch; + if (!branch) return yield* fail("Cannot create a pull request from detached HEAD."); + const resolved = yield* resolvePrBase(cwd, branch, status.upstreamRef, { + isCrossRepository: false, + remoteName: publishedRemoteName( + yield* readConfigValueNullable(cwd, `branch.${branch}.remote`), + ), + }); + const baseBranch = input.baseBranch ?? resolved.baseBranch; + if (baseBranch === branch) { + return yield* fail( + `${branch} is the base branch. Check out a feature branch to create ${terms.shortLabelWithArticle}.`, + ); + } + const companion = yield* provider.privateChangeRequestRemote({ cwd }); + const remoteName = yield* gitCore.ensureRemote({ + cwd, + preferredName: companion.repository.split("/")[0] || "private", + url: companion.url, + }); + // Recorded before the push, so a later push of this branch, by T3 or by plain `git push`, + // goes to the companion too and never publishes the branch. + yield* gitCore.writeConfigValue({ + cwd, + key: `branch.${branch}.pushRemote`, + value: remoteName, + }); + yield* gitCore + .execute({ + operation: "GitManager.openPrivatePullRequest.push", + cwd, + args: ["push", "--", remoteName, `refs/heads/${branch}:refs/heads/${branch}`], + timeoutMs: null, + }) + .pipe( + Effect.mapError((cause) => + fail(`Could not push ${branch} to ${companion.repository}: ${cause.detail}`, cause), + ), + Effect.tapError(() => invalidateStatus(cwd)), + ); + // The companion branch is the pull request's head, so status finds it through the upstream. + yield* gitCore + .setBranchUpstream({ cwd, branch, remoteName, remoteBranch: branch }) + .pipe(Effect.ensuring(invalidateStatus(cwd))); + const findOpen = provider + .listChangeRequests({ cwd, headSelector: branch, state: "open" }) + .pipe( + Effect.map( + (listed) => + listed.find( + (pr) => + pr.headRefName === branch && + pr.headRepositoryNameWithOwner?.toLowerCase() === + companion.repository.toLowerCase(), + ) ?? null, + ), + ); + const existing = yield* findOpen; + if (existing) { + return { + status: "opened_existing" as const, + url: existing.url, + number: existing.number, + baseBranch: existing.baseRefName, + headBranch: existing.headRefName, + title: existing.title, + }; + } + const bodyFile = path.join( + tempDir, + `t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`, + ); + yield* fileSystem + .writeFileString(bodyFile, input.body) + .pipe( + Effect.mapError((cause) => fail("Failed to write pull request body temp file.", cause)), + ); + yield* provider + .createChangeRequest({ + cwd, + baseRefName: baseBranch, + headSelector: branch, + title: input.title, + bodyFile, + private: true, + ...(input.draft === true ? { draft: true } : {}), + }) + .pipe( + Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.ignore)), + Effect.ensuring(invalidateStatus(cwd)), + ); + // The PR already exists at this point, so a failed lookup only loses its metadata. + const created = yield* findOpen.pipe(Effect.orElseSucceed(() => null)); + return { + status: "created" as const, + ...(created ? { url: created.url, number: created.number } : {}), + baseBranch: created?.baseRefName ?? baseBranch, + headBranch: created?.headRefName ?? branch, + title: created?.title ?? input.title, + }; + }); + + const pushAndOpenPullRequest = Effect.fn("GitManager.pushAndOpenPullRequest")(function* ( + input: Parameters[0], + ) { const status = yield* gitCore.statusDetails(input.cwd); const needsPush = yield* createPrNeedsPush(input.cwd, status); if (needsPush && status.branch) { @@ -2935,6 +3063,16 @@ export const make = Effect.gen(function* () { : Effect.void, ), ); + return result; + }); + + const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( + "GitManager.createPullRequest", + )(function* (input) { + const result = + input.private === true + ? yield* openPrivatePullRequest(input) + : yield* pushAndOpenPullRequest(input); const openedAsDraft = result.status === "created" && (yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true; diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index b7edff187579d..7caa425d32f2e 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -837,6 +837,7 @@ describe("source control tools", () => { body: "Adds tools.", state: "open", isDraft: false, + visibility: "private", author: null, headBranch: "tools", baseBranch: "main", @@ -892,6 +893,7 @@ describe("source control tools", () => { }); const compact = yield* harness.call("pull_request_read", {}); expect(compact).toMatchObject({ + visibility: "private", headSha: "abc123", checks: { passed: 2, pending: 1, failed: ["Lint", "E2E"], incomplete: true }, unresolvedThreads: 1, @@ -1178,7 +1180,11 @@ describe("source control tools", () => { it.effect("opens a PR from the thread's worktree and links it even if dismissed", () => Effect.gen(function* () { - const opened: Array<{ readonly cwd: string; readonly draft: boolean | undefined }> = []; + const opened: Array<{ + readonly cwd: string; + readonly draft: boolean | undefined; + readonly private: boolean | undefined; + }> = []; const harness = yield* makeHarness({ thread: { ...makeThread([makeLink(43, { source: "stack-dismissed" })]), @@ -1186,7 +1192,9 @@ describe("source control tools", () => { }, git: { createPullRequest: (input) => - Effect.sync(() => opened.push({ cwd: input.cwd, draft: input.draft })).pipe( + Effect.sync(() => + opened.push({ cwd: input.cwd, draft: input.draft, private: input.private }), + ).pipe( Effect.as({ status: "created" as const, url: "https://github.com/t3tools/t3code/pull/43", @@ -1202,9 +1210,10 @@ describe("source control tools", () => { title: "Add tools", body: "Adds tools.", draft: true, + private: true, }); expect(result).toMatchObject({ number: 43, created: true }); - expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true }]); + expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true, private: true }]); expect(yield* Ref.get(harness.commands)).toMatchObject([ { type: "thread.pull-request.link", number: 43, source: "created" }, ]); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index f85d8f0abac4a..e422a799f3d9a 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -617,6 +617,7 @@ const make = Effect.gen(function* () { title: detail.title, state: detail.state, isDraft: detail.isDraft, + ...(detail.visibility === undefined ? {} : { visibility: detail.visibility }), author: detail.author?.login ?? null, headBranch: detail.headBranch, baseBranch: detail.baseBranch, @@ -1052,6 +1053,7 @@ const make = Effect.gen(function* () { body: input.body, baseBranch: input.base, draft: input.draft, + private: input.private, }) .pipe(Effect.mapError(forgeFailure)); if (created.url === undefined) { diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 71d0a28d4e392..847ae4ef19e7d 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -16,6 +16,7 @@ import { PullRequestReviewGuideRun, PullRequestState, PullRequestUnavailableError, + PullRequestVisibility, PullRequestWatchUntil, ThreadPullRequestLinkSource, TrimmedNonEmptyString, @@ -517,6 +518,9 @@ export const ReadPullRequestResult = Schema.Struct({ title: Schema.String, state: PullRequestState, isDraft: Schema.Boolean, + visibility: Schema.optional(PullRequestVisibility).annotate({ + description: "Only on a host with private PRs.", + }), author: Schema.NullOr(Schema.String), headBranch: Schema.String, baseBranch: Schema.String, @@ -675,6 +679,10 @@ const CreatePullRequestTool = Tool.make("pull_request_create", { body: Schema.String, base: Schema.optional(TrimmedNonEmptyString), draft: Schema.optional(Schema.Boolean), + private: Schema.optional(Schema.Boolean).annotate({ + description: + "Visible to writers only; the branch never reaches origin. Fails on a host without private PRs.", + }), }), success: CreatePullRequestResult, failure: PullRequestToolError, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 139eba175bc8a..9ec6f6509f48c 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59052 + "mcpToolListJsonBytes": 59192 } diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index e30938735c765..59ece029219df 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1370,6 +1370,7 @@ export const make = Effect.gen(function* () { ...(input.item.checksState === undefined || input.item.checksState === null ? {} : { checksState: input.item.checksState }), + ...(input.item.visibility === undefined ? {} : { visibility: input.item.visibility }), viewerReviewRequested: input.item.author?.login.toLowerCase() !== viewer && input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer), @@ -1993,6 +1994,9 @@ export const make = Effect.gen(function* () { ...(changeRequest.mergeQueueRemoval === undefined ? {} : { mergeQueueRemoval: changeRequest.mergeQueueRemoval }), + ...(changeRequest.visibility === undefined + ? {} + : { visibility: changeRequest.visibility }), })), ), ), diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index 06616a914b1e9..98c560cbf4973 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -222,6 +222,15 @@ function bindProviderContext( context: input.context ?? context, }); }), + ...(provider.privateChangeRequestRemote === undefined + ? {} + : { + privateChangeRequestRemote: (input) => + provider.privateChangeRequestRemote!({ + ...input, + context: input.context ?? context, + }), + }), getRepositoryCloneUrls: Effect.fnUntraced(function* (input) { return yield* provider.getRepositoryCloneUrls({ ...input, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx index a797a7984cbce..250240d2849fa 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx @@ -1,12 +1,39 @@ import { useGT } from "gt-react"; -import { ArrowLeftIcon, FileDiffIcon } from "lucide-react"; +import { ArrowLeftIcon, FileDiffIcon, LockIcon } from "lucide-react"; import { useEffect, useRef, type ComponentProps, type ReactNode } from "react"; import { cn } from "~/lib/utils"; +import { Badge } from "../ui/badge"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestMetaLine } from "./pullRequestPresentation"; +export function PullRequestPrivateMark({ className }: { className?: string }) { + const gt = useGT(); + const label = gt("Private"); + return ( + + } + /> + {label} + + ); +} + +export function PullRequestPrivateBadge() { + const gt = useGT(); + return ( + + + + {gt("Private")} + + + ); +} + export function PullRequestDetailHeaderBody({ title, author, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index cbf9de56dbbb2..1e14ab19d9012 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -90,6 +90,7 @@ import { MiddleTruncate } from "../ui/middle-truncate"; import { PullRequestChecksStatusLine, PullRequestDetailHeaderBody, + PullRequestPrivateBadge, PullRequestDetailTabBar, } from "./PullRequestDetailLayout"; import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts"; @@ -1578,6 +1579,7 @@ export function PullRequestDetailPanel({
{detail ? ( + {detail.visibility === "private" ? : null} {context === "page" ? ( + {entry.visibility === "private" ? ( + + ) : null} {entry.checksState === undefined ? null : ( ; readonly reviewDecision?: PullRequestReviewDecision | null | undefined; readonly checksState?: PullRequestChecksState | null | undefined; + /** Absent where the host has no private change requests or names no visibility. */ + readonly visibility?: PullRequestVisibility; } export interface ProviderChangeRequestSummary { diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index 4a6e93ab74f45..ccf23f59b2258 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service< }) => Effect.Effect; /** True when `createChangeRequest` opens the change request as a draft when asked. */ readonly createsDraftChangeRequests?: boolean; + /** + * The private companion of the checkout's repository, made when it has none. The branch of + * a private change request is pushed to `url` and never to the repository itself, which + * everyone can read. Absent on a host without private change requests. + */ + readonly privateChangeRequestRemote?: (input: { + readonly cwd: string; + readonly context?: SourceControlProviderContext; + }) => Effect.Effect< + { readonly url: string; readonly repository: string }, + SourceControlProviderError + >; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service< readonly bodyFile: string; /** Honored only by a provider with `createsDraftChangeRequests`. */ readonly draft?: boolean; + /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */ + readonly private?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts new file mode 100644 index 0000000000000..838309b037617 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts @@ -0,0 +1,138 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; + +const HOST = "source.tanstack.com"; + +/** + * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the + * companion repository, and Source has stored no file or line counts for it. + */ +const PRIVATE_PULL = { + number: 42, + title: "Fix the thing", + state: "open", + visibility: "private", + draft: false, + author: "bob", + head: "acme:fix/thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "acme/web.private", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, + changedLines: null, +}; + +const FILES = { + baseSha: "b".repeat(40), + headSha: "c".repeat(40), + mergeBaseSha: "b".repeat(40), + available: true, + truncated: false, + files: [ + { path: "a.ts", status: "modified", additions: 3, deletions: 1 }, + { path: "b.ts", status: "added", additions: 4, deletions: 0 }, + ], +}; + +const RESPONSES: Record = { + "/repos/acme/web/pulls/42": PRIVATE_PULL, + "/repos/acme/web/pulls/42/files": FILES, + "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true }, + "/repos/acme/web/pulls/42/stack": { members: [] }, + [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [], + "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null }, + "/repos/acme/web/issues/42": { + timeline: [ + { id: 1, comment: "Looks good", author: "alice", at: 2_000 }, + { event: "head_updated", actor: "bob", at: 3_000 }, + ], + next: null, + }, + "/repos/acme/web/pulls/42/comments": [], + "/repos/acme/web/pulls/42/commits": { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commits: [], + }, + "/user": { username: "alice" }, +}; + +const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path in RESPONSES + ? Effect.succeed(JSON.stringify(RESPONSES[input.path])) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), +}); + +const provider = TanStackSourcePullRequestProvider.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provideService( + Credentials.TanStackSourceCredentials, + Credentials.TanStackSourceCredentials.of({ + get: () => Effect.die("unexpected credential read"), + invalidate: () => Effect.void, + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected http request")), + ), +); + +describe("TanStackSourcePullRequestProvider.getChangeRequest", () => { + // A client without this host's definition percent-encodes the owner's `@`; stored links + // keep the web's own spelling. + it.effect.each(["acme/web", "@acme/web", "%40acme/web"])( + "reads a private pull request of %s", + (repository) => + Effect.gen(function* () { + const detail = yield* (yield* provider).getChangeRequest({ + host: HOST, + repository, + number: 42, + cwd: "/repo", + }); + assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`); + assert.strictEqual(detail.visibility, "private"); + assert.strictEqual(detail.headBranch, "fix/thing"); + assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private"); + // Source stores no counts for it, so they come from its files. + assert.deepStrictEqual( + [detail.changedFiles, detail.additions, detail.deletions], + [2, 7, 1], + ); + }), + ); +}); + +describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => { + it.effect("reads the comments of a timeline that also holds events", () => + Effect.gen(function* () { + const activity = yield* (yield* provider).getChangeRequestActivity({ + host: HOST, + repository: "acme/web", + number: 42, + cwd: "/repo", + }); + assert.deepStrictEqual( + activity.comments.map((comment) => comment.body), + ["Looks good"], + ); + }), + ); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 509e03e1f41f4..0529ce6df17c7 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -35,6 +35,8 @@ const PULL = { function checkout(options: { readonly recordedOwner: string | null; readonly isAncestor: boolean; + readonly pull?: Partial; + readonly force?: boolean; }) { const git: Array = []; const config = new Map( @@ -43,14 +45,28 @@ function checkout(options: { const api = TanStackSourceApi.TanStackSourceApi.of({ request: (input) => input.path === "/repos/acme/web/pulls/42" - ? Effect.succeed(JSON.stringify(PULL)) + ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull })) : Effect.die(`unexpected ${input.path}`), response: () => Effect.die("unexpected response read"), }); const host = TestSourceControlHost.layer({ git: { resolvePrimaryRemoteName: () => Effect.succeed("origin"), - ensureRemote: () => Effect.succeed("origin"), + ensureRemote: (input) => + Effect.sync(() => { + git.push(`remote ${input.preferredName} ${input.url}`); + return input.url === REMOTE ? "origin" : input.preferredName; + }), + fetchRemoteBranch: (input) => + Effect.sync( + () => + void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`), + ), + fetchRemoteTrackingBranch: () => Effect.void, + setBranchUpstream: (input) => + Effect.sync( + () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`), + ), readConfigValue: (_cwd, key) => Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)), writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)), @@ -86,7 +102,13 @@ function checkout(options: { }, }); const run = TanStackSourceSourceControlProvider.make.pipe( - Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.flatMap((provider) => + provider.checkoutChangeRequest({ + cwd: "/repo", + reference: "42", + ...(options.force === undefined ? {} : { force: options.force }), + }), + ), Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), ); @@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.isFalse(git.some((command) => command.startsWith("checkout"))); }); }); + + // Source publishes no `refs/pull//head` for a private pull request, on either repository. + it.effect("takes a private pull request's branch from the companion repository", () => { + const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); + const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); + return Effect.gen(function* () { + yield* forced.run; + assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --"); + yield* run; + assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); + assert.deepStrictEqual(git, [ + `remote source ${REMOTE}`, + "remote acme https://source.tanstack.com/@acme/web.private.git", + "fetch acme fix-thing:fix-thing", + "upstream fix-thing acme/fix-thing", + "switch fix-thing", + ]); + }); + }); +}); + +describe("TanStackSourceSourceControlProvider private pull requests", () => { + it.effect("asks Source for the companion and opens the pull request as private", () => { + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => { + requests.push({ method: input.method ?? "GET", path: input.path, body: input.body }); + return Effect.succeed( + JSON.stringify({ + owner: "acme", + name: "web.private", + defaultBranch: null, + cloneUrl: "https://source.tanstack.com/@acme/web.private.git", + }), + ); + }, + response: () => Effect.die("unexpected response read"), + }); + const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") }); + return Effect.gen(function* () { + const provider = yield* TanStackSourceSourceControlProvider.make; + const companion = provider.privateChangeRequestRemote; + assert.isDefined(companion); + assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), { + url: "https://source.tanstack.com/@acme/web.private.git", + repository: "acme/web.private", + }); + yield* provider.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "sec/fix", + title: "Fix", + bodyFile: "/tmp/body.md", + private: true, + }); + assert.deepStrictEqual(requests, [ + { method: "POST", path: "/repos/acme/web/private-remote", body: undefined }, + { + method: "POST", + path: "/repos/acme/web/pulls", + body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true }, + }, + ]); + }).pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide( + Layer.merge( + TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + readConfigValue: () => Effect.succeed(REMOTE), + }, + }), + files, + ), + ), + ); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index a1abb376b472d..f194848611361 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -395,6 +395,18 @@ export const make = Effect.gen(function* () { }, ), createsDraftChangeRequests: true, + privateChangeRequestRemote: Effect.fn( + "TanStackSourceSourceControlProvider.privateChangeRequestRemote", + )(function* (input) { + const target = yield* resolveTarget("privateChangeRequestRemote", input); + const companion = yield* read( + "privateChangeRequestRemote", + input.cwd, + { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` }, + Repository, + ); + return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` }; + }), createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( function* (input) { const target = yield* resolveTarget("createChangeRequest", { @@ -437,6 +449,7 @@ export const make = Effect.gen(function* () { base: input.target?.refName ?? input.baseRefName, ...(body.trim().length === 0 ? {} : { body }), ...(input.draft === true ? { draft: true } : {}), + ...(input.private === true ? { private: true } : {}), }, }) .pipe( @@ -494,7 +507,8 @@ export const make = Effect.gen(function* () { return repository.defaultBranch; }, ), - // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A + // private one has no such ref: its branch is read from the companion repository. checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( function* (input) { const pull = yield* getPull(input); @@ -519,9 +533,26 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - if (!pull.isCrossRepository) { + const companion = + pullRepository !== null && + pull.headRepositoryNameWithOwner?.toLowerCase() === + `${pullRepository}.private`.toLowerCase() + ? pull.headRepositoryNameWithOwner + : null; + if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; - const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + const remoteBranch = { + cwd: input.cwd, + remoteName: + companion === null + ? remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: companion.split("/")[0] ?? "private", + url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`, + }), + remoteBranch: localBranch, + }; if (input.force !== true && !branches.includes(localBranch)) yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); else yield* git.fetchRemoteTrackingBranch(remoteBranch); @@ -535,11 +566,18 @@ export const make = Effect.gen(function* () { "--no-track", "-B", localBranch, - `refs/remotes/${remoteName}/${localBranch}`, + `refs/remotes/${remoteBranch.remoteName}/${localBranch}`, "--", ], }); yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + // Whatever push defaults say, this branch must not be published to the public remote. + if (companion !== null) + yield* git.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localBranch}.pushRemote`, + value: remoteBranch.remoteName, + }); yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); return; } diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts new file mode 100644 index 0000000000000..ac43a46ccdcad --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts"; + +describe("tanStackSourceRepositoryPath", () => { + it.each([ + ["acme/web", "acme/web"], + ["@acme/web", "acme/web"], + // Clients without this host's definition percent-encode the owner's `@`. + ["%40acme/web", "acme/web"], + ["/@acme/web.git/", "acme/web"], + ["acme/web.private", "acme/web.private"], + ["acme", null], + ["acme/web/extra", null], + ["acme/..", null], + ])("reads %s as %s", (path, repository) => { + expect(tanStackSourceRepositoryPath(path)).toBe(repository); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts index 22923264629bf..dfa6d4e9031a0 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -1,4 +1,4 @@ -import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; +import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts"; export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; @@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null { const SEGMENT = /^[A-Za-z0-9_.-]+$/u; -/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */ export function tanStackSourceRepositoryPath(path: string): string | null { - const [owner, name, ...rest] = path - .trim() - .replace(/^\/+|\/+$/gu, "") - .replace(/\.git$/u, "") - .replace(/^@/u, "") - .split("/"); + const [owner, name, ...rest] = withoutOwnerMark( + path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, ""), + ).split("/"); return rest.length === 0 && owner !== undefined && name !== undefined && diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts index 4d698fb881dfb..24c93e6aac83d 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -146,6 +146,7 @@ describe("toActivity", () => { ["4", "review-comment", null], ]); expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`); expect(activity.reviewThreads).toMatchObject([ { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, ]); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts index acf3c4158f95c..51537627ca3e7 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -16,6 +16,8 @@ import type { import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; +import { withoutOwnerMark } from "../shared/definition.ts"; + /** Source sends times as epoch milliseconds. */ const EpochMillis = Schema.Finite; const Login = Schema.String; @@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({ labels: Schema.optional(Schema.Array(Schema.String)), head: Schema.String, createdAt: EpochMillis, + visibility: Schema.optional(Schema.String), }); export type SourcePull = typeof SourcePull.Type; @@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({ type TimelineEntry = typeof TimelineEntry.Type; export const SourceTimeline = Schema.Struct({ - timeline: Schema.Array(TimelineEntry), + // Events such as `head_updated` sit between the comments and carry no id. + timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])), next: Schema.NullOr(Schema.String), }); @@ -239,10 +243,20 @@ export const SourceUser = Schema.Struct({ username: Schema.String }); export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); export const pullUrl = (host: string, repository: string, number: number) => - `https://${host}/@${repository}/pull/${number}`; + `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`; -/** A GitHub-synced pull request from a fork names its head only by its pull ref. */ -export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, ""); +/** + * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private + * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede. + */ +export const headBranchName = (head: string) => + head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, ""); + +/** Absent when Source names no visibility, so a reader tells unknown from public. */ +const visibilityOf = (pull: Pick) => + pull.visibility === "private" || pull.visibility === "public" + ? { visibility: pull.visibility } + : {}; export function toActor(login: string | null, host: string): PullRequestActor | null { if (login === null || login.trim() === "") return null; @@ -280,6 +294,7 @@ export function toChangeRequest( baseBranch: pull.base ?? "", state: pull.state, isDraft: pull.draft, + ...visibilityOf(pull), mergeability: "unknown", additions: 0, deletions: 0, @@ -380,7 +395,9 @@ export function toActivity(input: { }): ProviderChangeRequestActivity { const { host } = input; const page = pullUrl(host, input.repository, input.number); - const entries = input.timeline.timeline.filter(visible); + const entries = input.timeline.timeline.filter( + (entry): entry is TimelineEntry => "id" in entry && visible(entry), + ); const comments: Array = entries.map((entry: TimelineEntry) => ({ id: String(entry.id), kind: diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts index e3ce5c867fa5c..6e09a89fa2cda 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.test.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -31,7 +31,23 @@ describe("TanStack Source definition", () => { number: 7, }), ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + // A stored link or an older client may name the repository as the web spells it. + for (const repository of ["@TanStack/router", "%40TanStack/router"]) + expect( + definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }), + repository, + ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7"); expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull(); }); + + it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])( + "keys %s as the API's owner/name", + (repository) => { + expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe( + "source.tanstack.com/tanstack/router", + ); + expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull(); + }, + ); }); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts index 1aee00c968dc6..032adc5a45cdd 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) { : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; } +/** + * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this + * definition percent-encodes that as `%40owner/name`. + */ +export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, ""); + +/** Links stored with the web's spelling compare equal to the project's own key. */ +function canonicalRepositoryKey(key: string): string | null { + const slash = key.indexOf("/"); + return slash > 0 && isTanStackSourceHost(key.slice(0, slash)) + ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}` + : null; +} + /** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */ function repositoryKeyFromRemote(key: string): string | null { // Remote parsing spells the `@` percent-encoded. @@ -80,13 +94,13 @@ export const definition = defineSourceControl({ ? null : webUrl ? changeRequestUrlBelow(webUrl, `pull/${number}`) - : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`, parseChangeRequestUrl, commitUrl: (input) => buildCommitUrl( input.webUrl ? input - : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` }, "commit", ), parseIssueUrl: (url) => @@ -122,6 +136,7 @@ export const definition = defineSourceControl({ checkoutChangeRequestHost: () => null, changeRequestHeadRef: (number) => `refs/pull/${number}/head`, repositoryKeyFromRemote, + canonicalRepositoryKey, recognizeRemote: ({ hostname }) => isTanStackSourceHost(hostname) ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } From 976aca331aa15d41f4383def7afeafcfcab5575e Mon Sep 17 00:00:00 2001 From: Wu Shuwen Date: Sun, 22 Nov 2026 17:08:53 +0800 Subject: [PATCH 16/96] fix: include delegated threads in CLI listing (#40738) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 97 ++++++++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 6 +- 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 7231ea7f2b3e0..49887ee0bb7cc 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -53,6 +53,103 @@ vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { const threadId = ThreadId.make("thread-1"); const runId = RunId.make("run-1"); +it.effect("list includes delegated threads across pages and still leaves out subagents", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-list-" }); + yield* persistServerRuntimeState({ + path: path.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }), + }); + const projectId = ProjectId.make("project-1"); + const item = (id: string) => ({ + threadId: id, + projectId, + title: id, + createdBy: "user", + creationSource: "web", + status: "idle", + latestRunId: null, + providerInstanceId: "codex", + model: "test", + runtimeMode: "full-access", + interactionMode: "default", + linkedPullRequest: null, + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 0, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + const root = item("root"); + const delegated = { + ...item("delegated"), + delegatedFrom: { environmentId: "env-1", threadId: "remote", title: "Remote" }, + }; + const subagent = { ...item("child"), parentThreadId: "root", relationshipToParent: "subagent" }; + using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( + Effect.succeed({ + call: (tool, args) => { + if (tool === "t3_project_list") + return Effect.succeed({ + structuredContent: { + projects: [{ id: projectId, title: "Project", workspaceRoot: baseDir }], + nextCursor: null, + }, + }); + if (tool === "t3_thread_list") { + const all = args.includeSubagents ? [root, subagent, delegated] : [root]; + const cursor = Number(args.cursor); + return Effect.succeed({ + structuredContent: { + projectId, + currentThreadId: null, + threads: all.slice(cursor, cursor + 2), + nextCursor: cursor + 2 < all.length ? cursor + 2 : null, + total: all.length, + }, + }); + } + return Effect.die(`unexpected ${tool} call`); + }, + }), + ); + yield* Command.runWith(threadCommand, { version: "0.0.0" })([ + "list", + "--project", + projectId, + "--json", + "--base-dir", + baseDir, + ]); + const listed = JSON.parse(String((yield* TestConsole.logLines).at(-1))) as Array<{ + threadId: string; + }>; + assert.deepStrictEqual( + listed.map((entry) => entry.threadId), + ["root", "delegated"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })), + ), + ), + ), +); + it.effect( "start resolves home-relative project paths while preserving ids and relative paths", () => diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 8849f10c6a5ec..e63e762237e85 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -850,10 +850,12 @@ const threadListCommand = Command.make("list", { while (cursor !== null) { const page: OrchestratorMcpThreadListResult = yield* tools.call( "t3_thread_list", - { projectId: project.id, includeSubagents: false, limit: 100, cursor }, + { projectId: project.id, includeSubagents: true, limit: 100, cursor }, OrchestratorMcpThreadListResult, ); - threads.push(...page.threads); + threads.push( + ...page.threads.filter((thread) => thread.relationshipToParent !== "subagent"), + ); cursor = page.nextCursor; } if (flags.json) { From bcace0787ee37f4e4dd9a1f68b7be8f871934926 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:23:15 -0800 Subject: [PATCH 17/96] fix(pi): turn token usage counts cached tokens as input and stays per turn (#40758) --- .../testkit/fixtures/simple/pi_output.ts | 55 +++++++++------ .../provider-pi/src/server/adapter.test.ts | 56 ++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 67 ++++++++++++------- 3 files changed, 133 insertions(+), 45 deletions(-) diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts index c7579914964ee..bed80f2be65ef 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts @@ -24,32 +24,45 @@ function lastPiResponseData(transcript: ProviderReplayTranscript, command: strin return field(frame, "data"); } -/** Settled Pi usage uses each recorded get_session_stats response in order, not the last streaming total. */ +/** + * Settled Pi usage takes the context size from each turn's get_session_stats response and the + * input breakdown from the turn's last streamed message usage, since stats tokens are session totals. + */ export function assertPiSettledTokenUsage( result: OrchestratorV2ScenarioResult, transcript: ProviderReplayTranscript, ) { - const stats = transcript.entries.flatMap((entry) => - entry.type === "emit_inbound" && - field(entry.frame, "type") === "response" && - field(entry.frame, "command") === "get_session_stats" - ? [field(entry.frame, "data")] - : [], - ); - const turns = projectionFor(result, transcript.scenario).providerTurns; - assert.lengthOf(turns, stats.length); - for (const [index, turn] of turns.entries()) { - const contextUsage = field(stats[index], "contextUsage"); - const tokens = field(stats[index], "tokens"); - const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; - assert.deepEqual(tokenUsage, { - usedTokens: field(contextUsage, "tokens"), - maxTokens: field(contextUsage, "contextWindow"), - inputTokens: field(tokens, "input"), - cachedInputTokens: field(tokens, "cacheRead"), - outputTokens: field(tokens, "output"), - }); + const expected: Array> = []; + let messageUsage: unknown; + for (const entry of transcript.entries) { + if (entry.type !== "emit_inbound") continue; + const usage = field(entry.frame, "usage"); + if (field(entry.frame, "type") === "message_update" && field(usage, "totalTokens") !== 0) { + messageUsage = usage; + } + if ( + field(entry.frame, "type") === "response" && + field(entry.frame, "command") === "get_session_stats" + ) { + const contextUsage = field(field(entry.frame, "data"), "contextUsage"); + const count = (key: string) => Number(field(messageUsage, key)); + expected.push({ + usedTokens: field(contextUsage, "tokens"), + maxTokens: field(contextUsage, "contextWindow"), + inputTokens: count("input") + count("cacheRead") + count("cacheWrite"), + cachedInputTokens: count("cacheRead"), + outputTokens: count("output"), + }); + } } + const turns = projectionFor(result, transcript.scenario).providerTurns; + assert.deepEqual( + turns.map((turn) => { + const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; + return tokenUsage; + }), + expected, + ); } export function assertPiSimpleOutput( diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b3e54117f02ee 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("reports cached input as a share of input in live and completed token usage", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.queueState({ + sessionFile: FAKE_SESSION_FILE, + model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 }, + }); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + // Pi's message usage counts uncached input, cache reads and cache writes separately. + const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 }; + // Session stats total every message in the session, not this turn. + fake.queueStats({ + tokens: { + input: 1_206, + cacheRead: 90_202, + cacheWrite: 60_622, + output: 250, + total: 152_280, + }, + contextUsage: { tokens: 50_791, contextWindow: 1_000_000 }, + }); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + yield* fake.emit({ + type: "message_update", + usage: { ...usage, totalTokens: 50_791 }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" }, + }); + const live = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.deepInclude( + live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepInclude( + completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["turn window", "full tree"] as const)( "finishes a turn whose %s has a parentId cycle", (cycleIn) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index eae7f3eb6c2fa..e7803bbe9c5ee 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -359,6 +359,11 @@ function compactionTitle(status: PiCompactionStatus): string { } } +type PiMessageTokenUsage = Pick< + OrchestrationV2ProviderTurnTokenUsage, + "inputTokens" | "cachedInputTokens" | "outputTokens" +>; + interface ActivePiTurn { readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; readonly providerTurn: OrchestrationV2ProviderTurn; @@ -377,6 +382,7 @@ interface ActivePiTurn { promptMayBeCommandOnly: boolean; latestCompactionAfterTokens: number | null; lastLiveUsedTokens: number | null; + lastMessageUsage: PiMessageTokenUsage | undefined; settleProbeGeneration: number; /** An extension may start compaction immediately after Pi emits agent_settled. */ settleWhenIdle: boolean; @@ -904,6 +910,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return value === undefined ? undefined : Math.max(0, Math.trunc(value)); }; + // Pi counts uncached input, cache reads and cache writes separately; input includes all three. + const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => { + const uncachedInputTokens = nonNegativeInteger(usage, "input"); + const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); + const outputTokens = nonNegativeInteger(usage, "output"); + return { + ...(uncachedInputTokens === undefined + ? {} + : { + inputTokens: + uncachedInputTokens + + (cachedInputTokens ?? 0) + + (nonNegativeInteger(usage, "cacheWrite") ?? 0), + }), + ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), + ...(outputTokens === undefined ? {} : { outputTokens }), + }; + }; + const rememberModelContextWindow = (model: unknown): number | null => { const provider = recordString(model, "provider"); const id = recordString(model, "id"); @@ -994,6 +1019,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const tokenUsageFromStats = ( stats: unknown, fallbackUsedTokens: number | null, + messageUsage: PiMessageTokenUsage | undefined, updatedAt: DateTime.Utc, ): OrchestrationV2ProviderTurnTokenUsage | undefined => { const contextUsage = recordField(stats, "contextUsage"); @@ -1002,24 +1028,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined; if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0) return undefined; - - const totals = recordField(stats, "tokens"); - const inputTokens = nonNegativeInteger(totals, "input"); - const cachedInputTokens = nonNegativeInteger(totals, "cacheRead"); - const outputTokens = nonNegativeInteger(totals, "output"); - return { - usedTokens, - maxTokens, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), - updatedAt: DateTime.formatIso(updatedAt), - }; + // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message. + return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) }; }; - const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) => + const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) => request({ type: "get_session_stats" }, 2_000).pipe( - Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)), + Effect.map((stats) => + tokenUsageFromStats( + stats, + turn.latestCompactionAfterTokens, + turn.lastMessageUsage, + updatedAt, + ), + ), Effect.orElseSucceed(() => undefined), ); @@ -1030,6 +1052,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) { const usedTokens = nonNegativeInteger(usage, "totalTokens"); + if (usedTokens !== undefined && usedTokens > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } if ( usedTokens === undefined || usedTokens === 0 || @@ -1040,9 +1065,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } turn.lastLiveUsedTokens = usedTokens; - const inputTokens = nonNegativeInteger(usage, "input"); - const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); - const outputTokens = nonNegativeInteger(usage, "output"); const updatedAt = yield* DateTime.now; yield* emit({ type: "provider_turn.updated", @@ -1053,9 +1075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tokenUsage: { usedTokens, maxTokens: contextWindow, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), + ...turn.lastMessageUsage, updatedAt: DateTime.formatIso(updatedAt), }, }, @@ -2075,9 +2095,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } const treeRefs = turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs(); - const tokenUsage = readUsage - ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt) - : undefined; + const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined; const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure); yield* emit({ type: "provider_turn.updated", @@ -3474,6 +3492,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false), latestCompactionAfterTokens: null, lastLiveUsedTokens: null, + lastMessageUsage: undefined, settleProbeGeneration: 0, settleWhenIdle: false, compactionCancelled: false, From 4c3d83ff24c7437582cfd37ebe4565314250630b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:25:30 -0800 Subject: [PATCH 18/96] fix(mobile): usage account detail keeps even pace current while open (#40759) --- apps/mobile/src/features/usage/UsageLimitsPooled.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 96d8f922340f7..4c290d68ac338 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -20,6 +20,7 @@ import { import { msg, T, useGT, useMessages, Var } from "gt-react-native"; import { Fragment, type ReactNode, useId, useState } from "react"; import { Pressable, View } from "react-native"; +import { useNowMinuteMs } from "../../lib/clock"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { Defs, Path, Pattern, Rect, Svg } from "react-native-svg"; @@ -201,7 +202,6 @@ function PoolWindowCard({ windowId: pool.id, windowKind: pool.kind, environmentIds, - now, }); const summary = ( <> @@ -590,13 +590,13 @@ type AccountScreenProps = StaticScreenProps<{ windowId: string; windowKind: LimitPoolWindow["kind"]; environmentIds: readonly string[] | null; - now: number; }>; export function UsageLimitAccountScreen({ route }: AccountScreenProps) { const insets = useSafeAreaInsets(); const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); - const { accountKey, windowId, windowKind, environmentIds, now } = route.params; + const { accountKey, windowId, windowKind, environmentIds } = route.params; + const now = useNowMinuteMs(); const selectedIds = environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id))); const selected = From 7f125d83d18b2b4e9e65debf8e4d1ae71c45af94 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:27:45 -0800 Subject: [PATCH 19/96] fix(server): Resume sends pending context to providers without native resume (#40764) --- .../ProviderTurnStartService.test.ts | 21 +++++++ .../ProviderTurnStartService.ts | 61 +++++++++++++------ 2 files changed, 63 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 4bf6e71397fe5..89e5a6930bafc 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2289,6 +2289,27 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom }), ); +effectIt.effect.each([ + { contextRun: "current" }, + { contextRun: "failed", switchedProvider: true }, +] as const)( + "a resume that carries pending context asks a provider without native resume to continue: %j", + (sideChat) => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + nativeResumeUnsupported: true, + sideChat, + }); + yield* harness.start; + expect(harness.settledRuns).toEqual([]); + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ + withInlineContext("SIDE_CHAT_CONTEXT", "Continue where you left off."), + ]); + }), +); + effectIt.effect.each([ { contextRun: "current", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, { contextRun: "failed", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 8e35271ce5aa9..c3890cab5f71b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -408,12 +408,22 @@ export const layer: Layer.Layer< return { ...session, startTurn: (input: Parameters[0]) => start(input), - ...(session.resumeTurn === undefined - ? {} - : { - resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => - start(ProviderAdapter.resumeTurnInput(input)), - }), + // Pending context can prompt a resume, so even a session without native resume takes one. + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + session.resumeTurn === undefined && deliver === undefined + ? Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: session.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: input.providerThread.id, + }), + }), + ) + : start(ProviderAdapter.resumeTurnInput(input)), ...(session.compactThread === undefined ? {} : { @@ -1859,7 +1869,21 @@ export const layer: Layer.Layer< legacyInputRunIds, budget, } = handoffContext; - if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) { + const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); + const carriesPendingContext = + effectiveHandoffs.length > 0 || + retryHandoff.handoffs.length > 0 || + retryHandoff.attachments.length > 0 || + sideChatHandoff !== undefined || + restartNote !== "" || + noteContinuation; + // Pending context turns the resume into a prompted turn, which needs no native resume. + if ( + manualResume && + unsentResumeMessage === undefined && + session.resumeTurn === undefined && + !carriesPendingContext + ) { yield* settleStartFailure({ signal: "resume-unsupported", title: "Native resume is unavailable", @@ -1870,7 +1894,6 @@ export const layer: Layer.Layer< }); return; } - const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, @@ -2100,8 +2123,14 @@ export const layer: Layer.Layer< turnInput.resume && prompted && userText === "" ? RESUME_PROMPT : userText; const text = goalCommand ? userText : withInlineContext(context, requestText); const operation = - turnInput.resume && !prompted && session.resumeTurn !== undefined - ? session.resumeTurn({ ...resumeInput, messageId: resumeMessage.messageId }) + turnInput.resume && !prompted + ? (session.resumeTurn?.({ ...resumeInput, messageId: resumeMessage.messageId }) ?? + Effect.fail( + new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: providerThread.id, + }), + )) : start({ ...(prompted ? contextInput : startInput), message: { @@ -2176,15 +2205,9 @@ export const layer: Layer.Layer< }), ), ); - const deliverySession = - effectiveHandoffs.length === 0 && - retryHandoff.handoffs.length === 0 && - retryHandoff.attachments.length === 0 && - sideChatHandoff === undefined && - restartNote === "" && - !noteContinuation - ? session - : makeDeliverySession(session, startWithHandoffs); + const deliverySession = carriesPendingContext + ? makeDeliverySession(session, startWithHandoffs) + : session; return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, From 90a8ac086435ac3503810f64da2fc3c930ef8ce1 Mon Sep 17 00:00:00 2001 From: Aman Thanvi <22306104+amanthanvi@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:39:13 -0500 Subject: [PATCH 20/96] fix(server): a failed or cancelled clone no longer blocks re-cloning its destination (#40739) Co-authored-by: Julius Marminge --- .../src/project/ProjectCloneTracker.test.ts | 62 +++++++++++++++++++ .../server/src/project/ProjectCloneTracker.ts | 17 +++-- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index bdbb47b767c03..3b2e6f1179b86 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -312,6 +312,68 @@ describe("ProjectCloneTracker", () => { }).pipe(Effect.provide(harness.layer)); }); + it.effect("a fresh clone into a failed clone's destination supersedes it", () => { + let attempts = 0; + const harness = makeHarness({ + clone: (input) => + Effect.suspend(() => + ++attempts === 1 + ? Effect.fail( + new SourceControlRepositoryError({ + operation: "cloneRepository", + provider: SourceControlProviderKind.make("unknown"), + detail: "fatal: repository not found", + }), + ) + : Effect.succeed({ + cwd: input.destinationPath, + remoteUrl: input.remoteUrl ?? "", + repository: null, + }), + ), + }); + // The failed clone's project still owns the destination. + const conflictingHooks: ProjectCloneTracker.ProjectCloneHooks = { + ...harness.hooks, + createProject: (input) => + Effect.fail( + new ProjectConflictError({ + projectId: input.projectId, + workspaceRoot: input.workspaceRoot, + conflictingProjectId: projectId, + }), + ), + }; + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("failed"); + + const second = ProjectId.make("project-2"); + const result = yield* tracker.start({ ...startInput, projectId: second }, conflictingHooks); + expect(result.projectId).toBe(projectId); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("done"); + expect(yield* tracker.get(second)).toBeNull(); + expect(harness.cloned).toEqual([projectId]); + }).pipe(Effect.provide(harness.layer)); + }); + + it.effect("refuses a second clone into a destination that is still cloning", () => { + const harness = makeHarness({ clone: () => Effect.never }); + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + const error = yield* Effect.flip( + tracker.start({ ...startInput, projectId: ProjectId.make("project-2") }, harness.hooks), + ); + expect(error.message).toContain("already in progress"); + expect((yield* tracker.get(projectId))?.phase).toBe("running"); + }).pipe(Effect.provide(harness.layer)); + }); + it.effect("does not create a project when the clone cannot be prepared", () => { const harness = makeHarness(); const layer = ProjectCloneTracker.layer.pipe( diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index 0a24f11ffd89d..367b839cf2a6b 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -297,14 +297,19 @@ export const make = Effect.gen(function* () { endedAt: null, sequence: ++sequence, }; - const claimed = yield* Ref.modify(clones, (current) => { - const conflict = Array.from(current.values()).some( + const claim = yield* Ref.modify(clones, (current) => { + const overlapping = Array.from(current.values()).filter( (tracked) => tracked.snapshot.projectId === input.projectId || tracked.input.destinationPath === prepared.destinationPath, ); - if (conflict) return [false, current] as const; + // Only a running clone owns its destination; a failed or cancelled one + // left nothing behind, so a fresh start supersedes it. + if (overlapping.some((tracked) => tracked.snapshot.phase === "running")) { + return [null, current] as const; + } const next = new Map(current); + for (const stale of overlapping) next.delete(stale.snapshot.projectId); next.set(input.projectId, { snapshot, fiber: null, @@ -316,14 +321,16 @@ export const make = Effect.gen(function* () { protocol: input.protocol ?? "auto", }, }); - return [true, next] as const; + return [overlapping.map((stale) => stale.snapshot.projectId), next] as const; }); const alreadyInProgress = new SourceControlRepositoryError({ operation: "cloneRepository", provider: input.provider ?? SourceControlProviderKind.make("unknown"), detail: "A clone into this destination is already in progress.", }); - if (!claimed) return yield* alreadyInProgress; + if (claim === null) return yield* alreadyInProgress; + // A superseded done entry's pending removal would otherwise delete the new claim. + yield* Effect.forEach(claim, clearRetention, { discard: true }); // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried. const projectId = yield* Effect.uninterruptible( Effect.gen(function* () { From 70b5e489b91842243655cbc4307c614feb314ff0 Mon Sep 17 00:00:00 2001 From: Wu Shuwen Date: Sun, 22 Nov 2026 17:43:07 +0800 Subject: [PATCH 21/96] fix: retain pull request metadata in thread show (#40744) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 34 ++++++++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 3 ++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 49887ee0bb7cc..bb0906a9c6919 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -558,6 +558,40 @@ const timelineTools = (types: ReadonlyArray) => { const tail = (tools: number) => [...Array(tools).fill("tool_call"), "assistant_message"]; +it.effect("show retains pull request metadata when reading a later message window", () => + Effect.gen(function* () { + const link = { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + state: "open", + watching: false, + watchStartedAt: null, + } as const; + const call = ((_tool: string, input: unknown) => { + const args = input as { afterPosition?: number; limit: number }; + const first = args.afterPosition === undefined && args.limit === 1; + return Effect.succeed({ + thread: { + itemCount: 200, + status: first ? "running" : "completed", + pullRequestCount: 1, + ...(first ? { pullRequests: [link], openPullRequestCount: 1 } : {}), + }, + items: first ? [] : [{ position: 199, itemId: "message", type: "assistant_message" }], + nextPosition: 199, + hasMore: false, + }); + }) as ThreadTools["call"]; + const { thread } = yield* readLatestMessages({ call }, threadId, 1); + assert.strictEqual(thread.status, "completed"); + assert.deepStrictEqual(thread.pullRequests, [link]); + assert.strictEqual(thread.openPullRequestCount, 1); + }), +); + it.effect("show reads the end of a long thread, not its whole history", () => Effect.gen(function* () { const { tools, served, latest } = timelineTools([ diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index e63e762237e85..09ee65c32172b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -459,7 +459,8 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun ); afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY; } while (page.hasMore && afterPosition < (end ?? Number.POSITIVE_INFINITY) - 1); - thread = page.thread; + // Only the first read carries pull request previews; later pages omit them. + thread = Object.assign({}, thread, page.thread); // A window can hold the whole --messages count, too many to spread as arguments. messages = window.concat(messages); before = start; From c3a330d8342f0825293b56c0fd22b20c6ef3206c Mon Sep 17 00:00:00 2001 From: Jinhui Zheng Date: Sun, 22 Nov 2026 18:03:40 +0800 Subject: [PATCH 22/96] fix(web): show Queue for running sessions that cannot steer (#40767) Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 11 ++---- .../src/state/threadWorkflows.test.ts | 34 ++++++++++++++++- .../src/state/threadWorkflows.ts | 37 ++++++++++++++++--- 3 files changed, 68 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 254bbd4eb9e42..d17af4f620755 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -106,10 +106,9 @@ import { } from "@t3tools/client-runtime/state/subagentRuntime"; import { getUserQueuedThreadRuns, - threadSteersDuringCompaction, + threadCanSteer, threadSupportsProviderHandoff, } from "@t3tools/client-runtime/state/thread-workflows"; -import { compactionBlocksSteering } from "@t3tools/client-runtime/state/composer-dispatch"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { HandoffRow } from "./chat/V2LifecycleRow"; import { @@ -1545,12 +1544,10 @@ export default function ChatView(props: ChatViewProps) { const isCompacting = (isSendBusy || phase === "connecting" || phase === "running") && (compactionRunning || compactCommandIsActive); - const compactionBlocksSteer = compactionBlocksSteering({ + const canSteer = threadCanSteer(serverProjection, { compactCommandIsActive, compactionRunning, - steersDuringCompaction: threadSteersDuringCompaction(serverProjection), - run: serverProjection?.runs.find((run) => run.id === activeRuntime?.activeRunId), - messages: serverProjection?.messages, + activeRunId: activeRuntime?.activeRunId, }); const isWorking = deriveTimelineWorking({ phase, @@ -3822,7 +3819,7 @@ export default function ChatView(props: ChatViewProps) { isLocalDraftThread && activeProject === null } phase={phase} - canSteer={!compactionBlocksSteer} + canSteer={canSteer} canInterrupt={canInterruptRunningThread} isSendBusy={ (isSendBusy && !sendQueuesBehindSetup) || diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index a4049c7169163..fd8092a996a66 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -6,6 +6,7 @@ import { deriveThreadQueueWorkflowState, getUserQueuedThreadRuns, resolveLatestMergeBackRun, + threadCanSteer, threadSupportsProviderHandoff, } from "./threadWorkflows.ts"; @@ -13,6 +14,7 @@ const capabilities = (input?: { readonly queued?: boolean; readonly steer?: boolean; readonly restartSteer?: boolean; + readonly interrupt?: boolean; readonly nativeFork?: boolean; readonly portableFork?: boolean; }) => @@ -21,6 +23,7 @@ const capabilities = (input?: { supportsQueuedMessages: input?.queued ?? false, supportsActiveSteering: input?.steer ?? false, supportsSteeringByInterruptRestart: input?.restartSteer ?? false, + supportsInterrupt: input?.interrupt ?? false, }, threads: { canForkThread: input?.nativeFork ?? false, @@ -31,6 +34,35 @@ const capabilities = (input?: { }) as never; describe("thread workflows", () => { + it.each([ + ["queue only", { queued: true }, false, false], + ["session still attaching", undefined, false, true], + ["native steering", { steer: true }, false, true], + ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true], + ["restart without interrupt", { restartSteer: true }, false, false], + ["explicit compaction", { steer: true }, true, false], + ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => { + const projection = { + thread: { id: "thread", activeProviderThreadId: "provider-thread" }, + runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], + providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], + providerSessions: [ + ...(turns === undefined + ? [] + : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), + { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, + ], + messages: [], + } as unknown as OrchestrationV2ThreadProjection; + expect( + threadCanSteer(projection, { + compactCommandIsActive, + compactionRunning: false, + activeRunId: projection.runs[0]!.id, + }), + ).toBe(expected); + }); + it("skips message history classification when no runs are queued", () => { let metadataReads = 0; const message = { @@ -139,7 +171,7 @@ describe("thread workflows", () => { { id: "provider-session", status: "running", - capabilities: capabilities({ queued: true, restartSteer: true }), + capabilities: capabilities({ queued: true, interrupt: true, restartSteer: true }), }, ], } as never); diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 7dbbcf1e80c57..9e3d1eb4512b2 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -8,6 +8,7 @@ import { copySorted } from "@t3tools/shared/Array"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import { compactionBlocksSteering } from "./composerDispatch.ts"; import type { ThreadStructure } from "./models.ts"; type Projection = ThreadStructure; @@ -102,6 +103,33 @@ export function threadSteersDuringCompaction(projection: Projection | null | und ); } +function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): boolean { + return ( + turns.supportsActiveSteering || + (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) + ); +} + +export function threadCanSteer( + projection: Projection | null, + input: { + readonly compactCommandIsActive: boolean; + readonly compactionRunning: boolean; + readonly activeRunId: Run["id"] | null | undefined; + }, +): boolean { + const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns; + // A steer submitted before the session attaches can wait for its provider turn. + if (turns && !supportsSteering(turns)) return false; + return !compactionBlocksSteering({ + compactCommandIsActive: input.compactCommandIsActive, + compactionRunning: input.compactionRunning, + steersDuringCompaction: turns?.activeSteeringDuringCompaction === true, + run: projection?.runs.find((run) => run.id === input.activeRunId), + messages: projection?.messages, + }); +} + export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean { if (projection == null) return false; const session = resolveThreadProviderSession(projection); @@ -147,6 +175,7 @@ export function deriveThreadQueueWorkflowState( const activeRun = resolveActiveThreadRun(projection); const session = resolveThreadProviderSession(projection); const capabilities = session?.capabilities.turns; + const canSteer = capabilities !== undefined && supportsSteering(capabilities); const activeMessage = projection.messages.find( (message) => message.id === activeRun?.userMessageId, ); @@ -187,12 +216,8 @@ export function deriveThreadQueueWorkflowState( canPromoteToSteer: promoteSkipsCompaction || ((activeRun?.status === "preparing" || activeRun?.status === "starting") && - (capabilities === undefined || - capabilities.supportsActiveSteering || - capabilities.supportsSteeringByInterruptRestart)) || - (hasSteerableProviderTurn && - (capabilities?.supportsActiveSteering === true || - capabilities?.supportsSteeringByInterruptRestart === true)), + (capabilities === undefined || canSteer)) || + (hasSteerableProviderTurn && canSteer), promoteSkipsCompaction, }; } From c198f73b3766090e02cace1a8b14f439f9fc63b6 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Sun, 22 Nov 2026 15:54:47 +0530 Subject: [PATCH 23/96] fix(web): a click outside the project action editor no longer discards the draft (#40776) --- .../projectScriptEditor.browser.test.tsx | 14 ++++++++++++++ apps/web/src/components/projectScriptEditor.tsx | 2 ++ 2 files changed, 16 insertions(+) diff --git a/apps/web/src/components/projectScriptEditor.browser.test.tsx b/apps/web/src/components/projectScriptEditor.browser.test.tsx index a9ea6f03ad185..0f37c32b23a9e 100644 --- a/apps/web/src/components/projectScriptEditor.browser.test.tsx +++ b/apps/web/src/components/projectScriptEditor.browser.test.tsx @@ -3,6 +3,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { StrictMode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; vi.mock(import("~/state/session"), async (original) => ({ ...(await original()), @@ -86,3 +87,16 @@ describe("project action editor save lifecycle", () => { expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]); }); }); + +describe("project action editor dismissal", () => { + it("stays open when the user clicks outside the editor", async () => { + setup(); + await using screen = await render(null); + await open(screen, { scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT }); + await expect.element(page.getByRole("dialog")).toBeVisible(); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + expect(onClose).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsx index 504e0afc69ca0..ea9b5ca1f2245 100644 --- a/apps/web/src/components/projectScriptEditor.tsx +++ b/apps/web/src/components/projectScriptEditor.tsx @@ -188,6 +188,8 @@ export function ProjectScriptEditorDialog({ <> { if (!open) onClose(); }} From 379a98ac227d9c0b4185e133facfa6d3114c7427 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 02:55:08 -0800 Subject: [PATCH 24/96] fix(server): t3 pair skips Windows VirtualBox and VMware host-only adapters (#33441) --- apps/server/src/environment/DirectEndpoints.ts | 10 ++++++---- apps/server/src/startupAccess.test.ts | 14 ++++++++++++++ apps/server/src/startupAccess.ts | 7 ++++++- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index 4508d208e75e6..c39ca1d85484e 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -24,7 +24,12 @@ import { import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "./ServerEnvironment.ts"; -import { isLoopbackHost, isPrivateNetworkAddress, isVirtualInterface } from "../startupAccess.ts"; +import { + isLoopbackHost, + isPrivateNetworkAddress, + isVirtualInterface, + WINDOWS_HOST_ADAPTER_MAC, +} from "../startupAccess.ts"; type NetworkInterfacesMap = ReturnType; @@ -52,9 +57,6 @@ const isTailscaleInterface = ( /^tailscale/i.test(name) || entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address)); -// Windows adapter names are mutable; Linux bridges can inherit these MACs. -const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; - export function resolveBoundEndpoints(input: { readonly platform: NodeJS.Platform; readonly host: string | undefined; diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index 7290d6063db9b..c36c29e5f1278 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -71,6 +71,20 @@ it("prefers a LAN address over a tailnet one for a private-network pairing URL", ).toBe("http://192.168.1.42:3773"); }); +it("skips Windows VirtualBox and VMware host-only adapters for a private-network listener", () => { + expect( + resolveHeadlessConnectionString("0.0.0.0", 3773, { + interfaces: { + "VirtualBox Host-Only Network": [{ ...ipv4("192.168.56.1"), mac: "0a:00:27:00:00:0a" }], + "VMware Network Adapter VMnet8": [{ ...ipv4("192.168.159.1"), mac: "00:50:56:c0:00:08" }], + "Wi-Fi": [{ ...ipv4("192.168.1.20"), mac: "3c:22:fb:12:34:56" }], + }, + privateNetworkOnly: true, + platform: "win32", + }), + ).toBe("http://192.168.1.20:3773"); +}); + it("skips NixOS container and systemd-nspawn veths for a private-network pairing URL", () => { expect( resolveHeadlessConnectionString("0.0.0.0", 3773, { diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index b065a3fc88172..ce1b8be41938f 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -51,6 +51,9 @@ export const isLoopbackHost = (host: string | undefined): boolean => { const VIRTUAL_INTERFACE = /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/; +// VirtualBox and VMware host-only adapters on Windows. Their names are mutable; Linux bridges can inherit these MACs. +export const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; + /** * systemd-nspawn's `ve-*`/`vz-*` and NixOS containers' `vb-*` name host-side * veths after the machine. Windows aliases are user-renameable, so these @@ -155,7 +158,9 @@ const resolveHeadlessConnectionHost = ( (entry) => !entry.internal && isIpv4Family(entry.family) && - (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)), + (!privateNetworkOnly || + (isPrivateNetworkAddress(entry.address) && + !(platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)))), ); // A tailnet or other CGNAT address reaches fewer devices than the LAN one. const externalIpv4 = privateNetworkOnly From 418e1ace0fc6edeb729cb094efb939603b958049 Mon Sep 17 00:00:00 2001 From: Kyros Abas Date: Sun, 22 Nov 2026 18:57:28 +0800 Subject: [PATCH 25/96] fix(server): Word text boxes keep their paragraph breaks for agents (#40782) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 6 ++++-- apps/server/src/provider/userInputAttachments.test.ts | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 3dd649811f330..70f16961843d3 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -170,9 +170,11 @@ function* all(node: XmlNode, name: string | readonly string[]): Generator { +function* text(node: XmlNode): Generator { if (HIDDEN.has(node.name)) return; - if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; + // Word text boxes hold their own paragraphs inside the anchoring paragraph. + if (node.name === "txbxContent") yield* paragraphs(node); + else if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; else if (["br", "line-break", "cr"].includes(node.name)) yield "\n"; else if (node.name === "noBreakHyphen") yield "\u2011"; else if (node.spaceCount !== undefined) { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 72f7e52a3cd41..dd6c70cfcc00b 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -767,9 +767,9 @@ describe("question answer paths", () => { bounded: true, parts: { "word/document.xml": - 'BodyCallout boxCallout box', + 'BodyCallout boxSecond lineCallout boxSecond line', }, - expected: ["Body\nCallout box"], + expected: ["Body\nCallout box\nSecond line"], occurrences: { text: "Callout box", count: 1 }, }, { From 356dff3352f1014194c6c5861fead3bebc4c15ab Mon Sep 17 00:00:00 2001 From: TheGuyWithHAT Date: Sun, 22 Nov 2026 12:03:54 +0100 Subject: [PATCH 26/96] fix(web): RTF previews respect hidden character formatting (#40783) Co-authored-by: geezoria <25051260+geezoria@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 8 ++++++++ apps/web/src/components/files/extendedDocumentPreview.ts | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 4b736d8b6622e..c2b6aa0b306d7 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -158,6 +158,11 @@ describe("document preview contents", () => { "A\tB\u2003C\u2002D\u2005E\u200dF\u200cG\u200bH\u200eI\u200fJ", ], ["a Unicode fallback", String.raw`{\rtf1 Jean\u8209\_Luc}`, "Jean\u2011Luc"], + [ + "visible text around hidden character formatting", + String.raw`{\rtf1 A{\v hidden{\v0 B}hidden}C\v hidden\v0 D\v hidden\plain E}`, + "ABCDE", + ], ["a tracked replacement", String.raw`{\rtf1 aaa{\deleted bbb}{\revised BBB}ccc}`, "aaaBBBccc"], [ "text after a deletion reset", @@ -232,6 +237,9 @@ Third}`; expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected); const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`); expect(lineBreak).toEqual(["

First line
Second line

"]); + expect(html(String.raw`{\rtf1\ansi{\v\line\line\line}First line\line Second line}`)).toEqual( + lineBreak, + ); expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak); expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual( lineBreak, diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 7d6021de6f811..f107ea0266043 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -538,6 +538,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { let state = { skip: false, deleted: false, + hiddenText: false, bold: false, italic: false, underline: false, @@ -560,7 +561,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { }; let run = ""; let fallback = 0; - const hidden = () => state.skip || state.deleted; + const hidden = () => state.skip || state.deleted || state.hiddenText; const encoded = new Uint8Array(bytes.byteLength); let encodedLength = 0; const flush = () => { @@ -722,10 +723,12 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "ul") state.underline = arg !== 0; else if (word === "ulnone") state.underline = false; else if (word === "deleted") state.deleted = arg !== 0; + else if (word === "v") state.hiddenText = arg !== 0; else if (word === "plain") state = { ...state, deleted: false, + hiddenText: false, bold: false, italic: false, underline: false, From 5fc2eb2f4750230304c2a3c083f425854a16627a Mon Sep 17 00:00:00 2001 From: Arun Krishnamurthy Date: Sun, 22 Nov 2026 05:10:03 -0600 Subject: [PATCH 27/96] fix(mobile): the iOS composer keeps its keyboard and caret after dictation (#33916) Co-authored-by: Julius Marminge --- apps/mobile/src/features/issues/IssueCommentComposer.tsx | 6 +++++- apps/mobile/src/features/threads/ThreadComposer.tsx | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/issues/IssueCommentComposer.tsx b/apps/mobile/src/features/issues/IssueCommentComposer.tsx index 75ff1199595a3..901dee46152a4 100644 --- a/apps/mobile/src/features/issues/IssueCommentComposer.tsx +++ b/apps/mobile/src/features/issues/IssueCommentComposer.tsx @@ -170,7 +170,11 @@ export function IssueCommentComposer(props: { /> {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */} Date: Sun, 22 Nov 2026 11:16:00 +0000 Subject: [PATCH 28/96] fix(shared): find file links whose labels contain brackets (#40781) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- packages/shared/src/markdownLinks.test.ts | 3 ++ packages/shared/src/markdownLinks.ts | 49 ++++++++++------------- 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index a1f0af927636d..80204d903892b 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -174,6 +174,9 @@ describe("extractMarkdownLinkHrefs", () => { ["[".repeat(32_000), []], ["[a]( invalid [b](ok)", [" { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 50450a1e787de..e3458f04f3484 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -519,41 +519,36 @@ function markdownLinkDestinationScanner(markdown: string) { } } const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart); - if (hrefEnd === null || hrefEnd === hrefStart) return null; + if (hrefEnd === null) return null; const end = bareTail(hrefEnd); return end === null ? null : { hrefStart, hrefEnd, end }; }; } -// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one. -function unescapedLabelEnd(markdown: string, start: number): number { - let end = markdown.indexOf("]", start); - while (end !== -1) { - let backslashes = 0; - while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1; - if (backslashes % 2 === 0) return end; - end = markdown.indexOf("]", end + 1); - } - return -1; -} - +// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them +// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels. export function extractMarkdownLinkHrefs(markdown: string): string[] { const hrefs: string[] = []; const scanDestination = markdownLinkDestinationScanner(markdown); - let cursor = 0; - while (cursor < markdown.length) { - const labelStart = markdown.indexOf("[", cursor); - if (labelStart === -1) break; - const labelEnd = unescapedLabelEnd(markdown, labelStart + 1); - if (labelEnd === -1) break; - - // Skip a failed label once; nested openings share its closing bracket. - cursor = labelEnd + 1; - const destination = scanDestination(cursor); - if (!destination) continue; - cursor = destination.end; - const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); - if (href) hrefs.push(href); + const bracket = /[[\]\\]|\n[ \t\r]*\n/g; + let openBrackets = 0; + for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) { + if (match[0] === "\\") { + bracket.lastIndex = match.index + 2; + } else if (match[0].startsWith("\n")) { + openBrackets = 0; + } else if (match[0] === "[") { + openBrackets += 1; + } else if (openBrackets > 0) { + openBrackets -= 1; + const destination = scanDestination(match.index + 1); + if (!destination) continue; + // A link cannot contain a link, so the brackets still open around it become text. + openBrackets = 0; + bracket.lastIndex = destination.end; + const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); + if (href) hrefs.push(href); + } } return hrefs; } From 1acfd37c17ea49340705092d8ee3d41c210a0a99 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:19:46 -0800 Subject: [PATCH 29/96] fix(web): restore effort picker keyboard typeahead (#40798) Co-authored-by: shadowfeind --- .../chat/ComposerModelEffort.browser.test.tsx | 24 +++++++++++++++++++ .../components/chat/ComposerModelEffort.tsx | 23 ++++++++++++++---- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx index ab7d560d5c676..1678552dd0ab2 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx @@ -122,3 +122,27 @@ it("draws an agent's reasoning as bars and keeps its mode out of the levels", as .toBeInTheDocument(); await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); }); + +it("focuses a reasoning level by its first letter without selecting it", async () => { + await using screen = await render(, { router: false }); // no routes involved + await userEvent.tab(); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("l"); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + await expect + .element(screen.getByRole("radio", { name: "Medium" })) + .toHaveAttribute("aria-checked", "true"); + for (const key of ["{Control>}h{/Control}", "{Meta>}h{/Meta}", "{Alt>}h{/Alt}", "{Delete}"]) { + await userEvent.keyboard(key); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + } + await userEvent.keyboard("H"); + await expect.element(screen.getByRole("radio", { name: "High" })).toHaveFocus(); + // Wraps past the last level back to the first match. + await userEvent.keyboard("m"); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("h{Enter}"); + await expect + .element(screen.getByRole("radio", { name: "High" })) + .toHaveAttribute("aria-checked", "true"); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index 1d0227c0f6482..b5d5a519a3410 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -206,8 +206,8 @@ function ColumnRow(props: { "aria-checked": props.selected, disabled: props.disabled, "data-effort-row": true, - // Focus lands on a level after a model pick. - "data-effort-level": true, + // Focus lands on a level after a model pick, and a typed letter finds one by its label. + "data-effort-level": props.label, // Up and Down move between rows. tabIndex: props.tabStop ? 0 : -1, className: COLUMN_ROW, @@ -244,15 +244,28 @@ function ColumnRow(props: { } function moveBetweenRows(event: KeyboardEvent) { - if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; + const arrow = event.key === "ArrowDown" || event.key === "ArrowUp"; + if ( + !arrow && + (event.key.length !== 1 || + event.key.trim() === "" || + event.ctrlKey || + event.altKey || + event.metaKey || + event.nativeEvent.isComposing) + ) + return; // An option's side menu is a React child here, but it moves through its own items. if (!event.currentTarget.contains(event.target as Node)) return; const rows = Array.from( event.currentTarget.querySelectorAll("[data-effort-row]:not(:disabled)"), ); const index = rows.findIndex((row) => row === document.activeElement); - const next = - rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))]; + const next = arrow + ? rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))] + : [...rows.slice(index + 1), ...rows.slice(0, index + 1)].find((row) => + row.dataset.effortLevel?.toLowerCase().startsWith(event.key.toLowerCase()), + ); if (!next) return; event.preventDefault(); event.stopPropagation(); From 0ae3154695e5b6808a8fb9955f69d78d9c1274fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:19:58 -0800 Subject: [PATCH 30/96] fix(server): migration 75 no longer fails on an unreadable subagent payload (#30783) --- .../075_SubagentDeliveryState.test.ts | 48 +++++++++++++++++++ .../Migrations/075_SubagentDeliveryState.ts | 4 +- 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts new file mode 100644 index 0000000000000..c652d1f9bc851 --- /dev/null +++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts @@ -0,0 +1,48 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); +const updatedAt = "2026-09-01T00:00:00.000Z"; +const deliveredPayload = JSON.stringify({ completionDelivery: { state: "delivered" } }); + +layer("075_SubagentDeliveryState", (it) => { + it.effect("backfills delivery state without failing on an unreadable payload", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 74 }); + const payloads = [ + ["delivered", deliveredPayload], + ["unreadable", ""], + ]; + for (const [id, payload] of payloads) { + yield* sql` + INSERT INTO orchestration_v2_projection_subagents ( + subagent_id, thread_id, parent_node_id, provider, origin, status, updated_at, + payload_json + ) VALUES ( + ${id}, 'thread-1', 'node-1', 'codex', 'delegated', 'cancelled', ${updatedAt}, + ${payload} + ) + `; + } + + yield* runMigrations({ toMigrationInclusive: 75 }); + const rows = yield* sql` + SELECT subagent_id, completion_delivery_state, payload_json + FROM orchestration_v2_projection_subagents ORDER BY subagent_id + `; + assert.deepStrictEqual(rows, [ + { + subagent_id: "delivered", + completion_delivery_state: "delivered", + payload_json: deliveredPayload, + }, + { subagent_id: "unreadable", completion_delivery_state: null, payload_json: "" }, + ]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts index 4406911cc8a8c..0288c89ceed05 100644 --- a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts +++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts @@ -11,7 +11,9 @@ export default Effect.gen(function* () { yield* sql` UPDATE orchestration_v2_projection_subagents SET completion_delivery_state = json_extract(payload_json, '$.completionDelivery.state') - WHERE json_type(payload_json, '$.completionDelivery') IS NOT NULL + WHERE CASE WHEN json_valid(payload_json) + THEN json_type(payload_json, '$.completionDelivery') IS NOT NULL + ELSE 0 END `; yield* sql` CREATE INDEX orchestration_v2_projection_subagents_settled_idx From 671e05bc8cdd83c90673a0e254e43f6042263547 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:20:57 -0800 Subject: [PATCH 31/96] fix(issues): an Activity cross-reference opens the issue or pull request it came from (#40768) --- .../src/features/issues/IssueRouteScreen.tsx | 60 ++++++++++++++++- .../chat/RightPanelSurfaceContent.tsx | 19 +++++- .../src/components/issue/IssueDetailPanel.tsx | 65 ++++++++++++++++++- apps/web/src/components/issue/IssuesPage.tsx | 9 ++- packages/contracts/src/issue.ts | 10 +++ .../src/server/GitHubIssueTracker.test.ts | 9 +++ .../src/server/gitHubIssueJson.ts | 30 ++++++--- .../src/server/issues.graphql | 1 + .../src/server/issues.graphql.ts | 4 +- .../src/server/GitLabIssueTracker.test.ts | 14 ++++ .../src/server/GitLabIssueTracker.ts | 10 ++- .../src/server/gitLabIssueJson.ts | 35 ++++++++++ 12 files changed, 247 insertions(+), 19 deletions(-) diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 2e5354b23f50f..8312bb703894b 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -7,6 +7,7 @@ import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; import type { IssueComment, IssueEvent, + IssueEventReference, IssueLinkedPullRequest, IssueReaction, IssueState, @@ -404,9 +405,48 @@ function IssueCommentCard(props: { ); } -function IssueEventRow({ event }: { readonly event: IssueEvent }) { +function IssueEventRow({ + params, + event, +}: { + readonly params: IssueParams; + readonly event: IssueEvent; +}) { const gt = useGT(); const messages = useMessages(); + const navigation = useNavigation(); + const sentence = issueEventSentence(event, messages); + const source = event.reference; + const at = event.detail === null ? -1 : sentence.indexOf(event.detail); + // Only a git host's tracker shares its host with the change request it links. + const sameHost = sourceControlClients.find(params.tracker) !== undefined; + const openSource = (target: IssueEventReference) => { + const host = params.host ? { host: params.host } : {}; + if (target.kind === "issue") { + navigation.dispatch( + StackActions.push("Issue", { + environmentId: params.environmentId, + projectId: params.projectId, + tracker: params.tracker, + ...host, + scope: target.repository, + issueKey: String(target.number), + }), + ); + } else if (sameHost) { + navigation.dispatch( + StackActions.push("PullRequest", { + environmentId: params.environmentId, + projectId: params.projectId, + repository: target.repository, + number: target.number, + ...host, + }), + ); + } else { + void tryOpenExternalUrl(target.url); + } + }; return ( @@ -414,7 +454,21 @@ function IssueEventRow({ event }: { readonly event: IssueEvent }) { {event.actor?.login ?? gt("Someone", { $context: "an unknown person" })} {" "} - {issueEventSentence(event, messages)} + {source === undefined || event.detail === null || at < 0 ? ( + sentence + ) : ( + <> + {sentence.slice(0, at)} + openSource(source)} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + )} {relativeTime(event.createdAt, undefined, messages)} @@ -505,7 +559,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { ...detail.events.map((event) => ({ key: `e:${event.id}`, at: event.createdAt, - content: , + content: , })), ].sort((left, right) => Date.parse(left.at) - Date.parse(right.at)) : []; diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 076c78d88d468..8b4bb6232287b 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -141,9 +141,14 @@ export function RightPanelSurfaceContent(props: { getShortcutContext={props.getShortcutContext} shortcutsEnabled={visible && props.activeSurfaceId === surface.id} key={`${scopedThreadKey(threadRef)}:${surface.id}`} - environmentId={props.environmentId} + environmentId={ + (surface.environmentId as EnvironmentId | undefined) ?? props.environmentId + } onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, @@ -205,12 +210,24 @@ export function RightPanelSurfaceContent(props: { threadRef={threadRef} onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, ...(reference.host ? { host: reference.host } : {}), }); }} + onSelectIssue={({ host, ...reference }) => { + useRightPanelStore.getState().openIssue(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + ...reference, + ...(host ? { host } : {}), + }); + }} /> ); case "pull-requests": diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index bdee83563a330..30a55dd1d9e48 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -18,6 +18,7 @@ import type { IssueComment, IssueDetail, IssueEvent, + IssueEventReference, IssueLabelCandidate, IssueLinkedPullRequest, IssueListEntry, @@ -376,12 +377,44 @@ function LinkedPullRequestRow({ ); } +/** The sentence for an event, its source shown as a link where the tracker named one. */ +function IssueEventText({ + event, + sentence, + onOpen, +}: { + event: IssueEvent; + sentence: string; + /** Opens the source beside this issue, and says whether it did; if not, the link goes to the host. */ + onOpen: (source: IssueEventReference) => boolean; +}) { + const source = event.reference; + const at = event.detail === null ? -1 : sentence.indexOf(event.detail); + if (source === undefined || event.detail === null || at < 0) return {sentence}; + return ( + + {sentence.slice(0, at)} + } + onClick={(click) => { + if (!click.metaKey && !click.ctrlKey && onOpen(source)) click.preventDefault(); + }} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + ); +} + export function IssueDetailPanel({ environmentId, reference, threadRef = null, listEntry = null, onSelectPullRequest, + onSelectIssue, }: { environmentId: EnvironmentId; reference: IssueRef; @@ -390,6 +423,8 @@ export function IssueDetailPanel({ threadRef?: ScopedThreadRef | null; /** Opens a linked change request beside this one; absent, the link goes to the host. */ onSelectPullRequest?: ((reference: PullRequestRef) => void) | undefined; + /** Opens a referenced issue beside this one; absent, the link goes to the host. */ + onSelectIssue?: ((reference: IssueRef & { readonly url: string }) => void) | undefined; }) { const gt = useGT(); const messages = useMessages(); @@ -442,6 +477,30 @@ export function IssueDetailPanel({ const tracker = issueTrackerPresentation(detail.tracker); const currentState = issueStatePresentation(detail.state); + const host = reference.host === undefined ? {} : { host: reference.host }; + const openEventSource = (source: IssueEventReference) => { + if (source.kind === "pull-request") { + if (!onSelectPullRequest) return false; + onSelectPullRequest({ + projectId: reference.projectId, + ...host, + repository: source.repository, + number: source.number, + }); + return true; + } + if (!onSelectIssue) return false; + onSelectIssue({ + projectId: reference.projectId, + tracker: reference.tracker, + ...host, + scope: source.repository, + key: String(source.number), + url: source.url, + }); + return true; + }; + const loadOlder = async () => { const failure = await pager.loadOlder(registry, (cursor) => loadComments({ environmentId, input: { ...reference, cursor } }), @@ -869,7 +928,11 @@ export function IssueDetailPanel({ className="px-1 text-xs text-muted-foreground" > - {issueEventSentence(item.event, messages)} + {formatRelativeTimeLabel(item.event.createdAt, undefined, messages)} ), diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index e29e3aa3c8123..d1c9f77aa2917 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -419,7 +419,7 @@ export function IssuesPage() { : clearedSelection, ); - const selectEntry = (entry: IssueRowTarget) => { + const selectEntry = (entry: Omit & { readonly host?: string }) => { if (rightPanelRef === null) return; useRightPanelStore.getState().openIssue(rightPanelRef, entry); updateSearch({ @@ -864,6 +864,13 @@ export function IssuesPage() { environmentId: panelEnvironmentId, }); }} + onSelectIssue={({ host, ...reference }) => + selectEntry({ + ...reference, + ...(host === undefined ? {} : { host }), + environmentId: panelEnvironmentId, + }) + } /> ) : ( event.kind === "referenced")).toMatchObject({ + reference: { + repository: "acme/web", + number: 50, + kind: "pull-request", + url: "https://github.com/acme/web/pull/50", + }, + }); }), ); }); diff --git a/packages/source-control-github/src/server/gitHubIssueJson.ts b/packages/source-control-github/src/server/gitHubIssueJson.ts index e46ad7ec9e515..59e9b9efd118e 100644 --- a/packages/source-control-github/src/server/gitHubIssueJson.ts +++ b/packages/source-control-github/src/server/gitHubIssueJson.ts @@ -5,7 +5,6 @@ import type { IssueActor, IssueComment, IssueEvent, - IssueEventKind, IssueLabel, IssueLinkedPullRequest, IssueState, @@ -137,7 +136,7 @@ function toLinkedPullRequest( /** The change GitHub recorded, or null for a kind this page has no vocabulary for. */ function toEventFields( raw: TimelineItem, -): { readonly kind: IssueEventKind; readonly detail: string | null } | null { +): Pick | null { switch (raw.__typename) { case "ClosedEvent": return { kind: "closed", detail: null }; @@ -164,15 +163,28 @@ function toEventFields( case "RenamedTitleEvent": return { kind: "renamed", detail: trimmed(raw.currentTitle) }; case "CrossReferencedEvent": { - const repository = trimmed( - raw.source != null && "repository" in raw.source - ? raw.source.repository.nameWithOwner - : null, - ); - const number = raw.source != null && "number" in raw.source ? raw.source.number : 0; + const source = + raw.source.__typename === "PullRequest" || raw.source.__typename === "Issue" + ? raw.source + : null; + const repository = trimmed(source?.repository.nameWithOwner); + const url = trimmed(source?.url); + if (source === null || repository === null || source.number <= 0) { + return { kind: "referenced", detail: null }; + } return { kind: "referenced", - detail: repository === null || number <= 0 ? null : `${repository}#${number}`, + detail: `${repository}#${source.number}`, + ...(url === null + ? {} + : { + reference: { + repository, + number: source.number, + kind: source.__typename === "PullRequest" ? "pull-request" : "issue", + url, + }, + }), }; } default: diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 18c8cee3536a2..d8b28a08c7078 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -231,6 +231,7 @@ query IssueDetail($owner: String!, $name: String!, $number: Int!) { } ... on Issue { number + url repository { nameWithOwner } diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index 9d059396d26a0..fb393ef5ca4c6 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -487,6 +487,8 @@ export const SourceIssue = Schema.Struct({ __typename: Schema.Literal("Issue"), /** Identifies the issue number. */ number: Shared.Int, + /** The HTTP URL for this issue */ + url: Shared.URI, /** The repository associated with this node. */ repository: NodesRepositoryRepository }) @@ -584,7 +586,7 @@ export const IssueDetail = GraphQL.query("IssueDetail", { ], selections: [ { name: "viewer", body: ["{login}"] }, - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number repository{nameWithOwner}}}}}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number url repository{nameWithOwner}}}}}}}}"] } ], fragments: [ { name: "IssueRow", body: ["on Issue{number title url state stateReason createdAt updatedAt closedAt author{__typename login avatarUrl...on User{name}}}"] }, diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 7c794de8b456e..d3bd6e01366bd 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -59,6 +59,13 @@ function answer(path: string): string { created_at: "2026-07-03T00:00:00Z", system: true, }, + { + id: 10, + body: "mentioned in merge request api!51", + author: { username: "theo" }, + created_at: "2026-07-04T00:00:00Z", + system: true, + }, ]); } if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) { @@ -206,7 +213,14 @@ describe("GitLabIssueTracker", () => { expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ ["labeled", "bug"], ["closed", null], + ["referenced", "merge request api!51"], ]); + expect(issue.events.at(-1)?.reference).toEqual({ + repository: "acme/api", + number: 51, + kind: "pull-request", + url: "https://gitlab.com/acme/api/-/merge_requests/51", + }); // A closing merge request is not repeated as a related one. expect( issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index f8b1f80c18b0e..4f4aeb3135034 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -25,6 +25,7 @@ import { decodeIssueDetailListJson, decodeIssueListJson, decodeIssueNotesJson, + withMentionReference, decodeLabelEventsJson, decodeLinkedMergeRequestsJson, decodeProjectLabelsJson, @@ -576,9 +577,12 @@ export const make: Effect.Effect = reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [], })), commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null), - events: [...systemEvents, ...labelEvents].sort((left, right) => - left.createdAt.localeCompare(right.createdAt), - ), + events: [ + ...systemEvents.map((event) => + withMentionReference(event, issue.url, input.scope), + ), + ...labelEvents, + ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)), // A merge request that closes the issue outranks its sighting as a mere mention. linkedPullRequests: [ ...closing, diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts index 5458ed4f859ef..7a52667a4a425 100644 --- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts @@ -250,6 +250,41 @@ function toSystemEvent( return null; } +// The path class excludes the sigil, so matching is linear on any input. +const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/; + +/** + * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL + * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none. + */ +export function withMentionReference( + event: IssueEvent, + issueUrl: string, + scope: string, +): IssueEvent { + const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null; + const projectUrl = issueUrl.split("/-/")[0]!; + if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) { + return event; + } + const [, mergeRequestPath, issuePath, digits] = match; + const isMergeRequest = mergeRequestPath !== undefined; + const path = mergeRequestPath ?? issuePath ?? ""; + // A project in the same namespace is named by its path alone. + const repository = + path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`; + const base = projectUrl.slice(0, projectUrl.length - scope.length); + return { + ...event, + reference: { + repository, + number: Number(digits), + kind: isMergeRequest ? "pull-request" : "issue", + url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`, + }, + }; +} + interface GitLabIssueNotes { readonly comments: ReadonlyArray; readonly events: ReadonlyArray; From 8435a8cd418f6d46bbb00e812be1f53932c2aac8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:25:22 -0800 Subject: [PATCH 32/96] fix(server): tell a stopped parent which delegated tasks its Stop interrupted (#34499) --- .../DelegatedCompletionDelivery.test.ts | 133 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 17 ++- .../ProviderTurnStartService.ts | 56 ++++++-- .../RestartBackgroundNote.test.ts | 52 +++++++ .../orchestration-v2/RestartBackgroundNote.ts | 72 ++++++++++ 5 files changed, 315 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 441c9992e73cc..3d6575bd6a405 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -19,6 +19,7 @@ import { ProviderInstanceId, ProviderSessionId, ProviderThreadId, + ProviderTurnId, RunId, RuntimeRequestId, ThreadId, @@ -5063,6 +5064,138 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); + // regression: #34401 a parent's Stop killed a child's background build but its task read completed + it.effect("reports a child its parent's Stop reached as interrupted", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const stoppedAt = DateTime.add(now, { seconds: 10 }); + const threadId = ThreadId.make("thread:stop-background-parent"); + const projectId = ProjectId.make("project:stop-background-parent"); + const runId = RunId.make("run:stop-background-parent"); + const rootNodeId = NodeId.make("node:stop-background-parent-root"); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make("node:stop-background-parent-settled"), + deliveryState: "delivered", + now, + }); + // Background launches report their command finished at once; only the roster tracks the work. + const seedStoppedChild = (name: string, parentStopped: boolean, reachedTurn: boolean) => + Effect.gen(function* () { + const child = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name, + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + const item = { + threadId: child.childThreadId, + runId: child.childRunId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + }; + const scope = { + type: "turn-item.updated" as const, + threadId: child.childThreadId, + runId: child.childRunId, + providerInstanceId: modelSelection.instanceId, + }; + yield* eventSink.write({ + commandId: CommandId.make(`command:${name}:stop`), + events: [ + { + ...scope, + id: EventId.make(`event:${name}:command`), + occurredAt: now, + payload: { + ...item, + id: TurnItemId.make(`turn-item:${name}:command`), + type: "command_execution", + ordinal: 1, + status: "completed", + title: "Run build", + input: "./build.sh", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + { + ...scope, + id: EventId.make(`event:${name}:interrupt-request`), + occurredAt: stoppedAt, + payload: { + ...item, + id: TurnItemId.make(`turn-item:${name}:interrupt-request`), + // Stop interrupting background work names its provider turn; an idle run's marker does not. + providerTurnId: reachedTurn ? ProviderTurnId.make(`provider-turn:${name}`) : null, + type: "run_interrupt_request", + ordinal: 2, + status: "completed", + title: "Interrupt requested", + startedAt: stoppedAt, + completedAt: stoppedAt, + updatedAt: stoppedAt, + message: "Stopped by user", + }, + }, + ], + }); + if (parentStopped) { + const task = (yield* orchestrator.getThreadProjection(threadId)).subagents.find( + (row) => row.id === child.taskId, + )!; + yield* eventSink.write({ + commandId: CommandId.make(`command:${name}:parent-stop`), + events: [ + { + id: EventId.make(`event:${name}:disposed`), + type: "subagent.updated", + threadId, + runId, + nodeId: task.id, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: stoppedAt, + payload: { + ...task, + completionDelivery: { state: "disposed", observedByRunId: null }, + updatedAt: stoppedAt, + }, + }, + ], + }); + } + return child; + }); + const cut = yield* seedStoppedChild("stop-background-cut", true, true); + const idle = yield* seedStoppedChild("stop-background-idle", true, false); + const finished = yield* seedStoppedChild("stop-background-finished", false, true); + + yield* orchestrator.recoverDelegatedTasks; + + const settled = yield* orchestrator.getThreadProjection(threadId); + const statusOf = (taskId: NodeId) => + settled.subagents.find((row) => row.id === taskId)?.status; + assert.equal(statusOf(cut.taskId), "interrupted"); + assert.equal(statusOf(idle.taskId), "completed"); + assert.equal(statusOf(finished.taskId), "completed"); + }), + ); + it.effect("cancelling a task whose child already finished keeps its completed result", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 61f5027793569..5936f57ad5014 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15132,7 +15132,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, - turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES, + turnItemTypes: [...SUBAGENT_RESULT_TURN_ITEM_TYPES, "run_interrupt_request"], providerTurnAttemptIds: [childRun, ...reportRuns].flatMap( (run) => run.activeAttemptId ?? [], ), @@ -15177,9 +15177,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (task === undefined) { return; } - // A cancelled task's completed run ends it interrupted. + // A cancelled task's completed run ends it interrupted, as does one whose provider turn its + // parent's Stop interrupted to kill background work. Stop's marker on an idle run names no + // provider turn and interrupted nothing. const cancelled = task.cancelledRunId === childRun.id; - if (cancelled && terminalStatus === "completed") outcome = terminalStatus = "interrupted"; + const stopped = + task.completionDelivery?.state === "disposed" && + childResult.turnItems.some( + (item) => + item.runId === childRun.id && + item.type === "run_interrupt_request" && + item.providerTurnId !== null, + ); + if ((cancelled || stopped) && terminalStatus === "completed") + outcome = terminalStatus = "interrupted"; // Every result the child sent is among its own transfers, far fewer than the parent's. const childTransfers = yield* projectionStore.getThreadRecords(childThreadId, [ "contextTransfers", diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index c3890cab5f71b..752b13568a111 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -80,7 +80,9 @@ import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import { isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, + pendingStoppedDelegatedTasks, restartCancelledBackgroundWorkNote, + stoppedDelegatedTasksNote, } from "./RestartBackgroundNote.ts"; export class ProviderTurnStartError extends Schema.TaggedError()( @@ -1029,26 +1031,56 @@ export const layer: Layer.Layer< projection.providerTurns, projection.attempts, ); + let compactionMessageIdSet: ReadonlySet | undefined; + const compactionMessageIds = () => + (compactionMessageIdSet ??= new Set( + projection.messages + .filter( + (candidate) => + isCompactionCommandMessage(candidate) || + (goalDriver && parseGoalCommand(candidate) !== null), + ) + .map((candidate) => candidate.id), + )); const restartCancelledWork = pendingRestartCancelledBackgroundWork({ runs: projection.runs, providerTurns: projection.providerTurns, - compactionMessageIds: () => - new Set( - projection.messages - .filter( - (candidate) => - isCompactionCommandMessage(candidate) || - (goalDriver && parseGoalCommand(candidate) !== null), - ) - .map((candidate) => candidate.id), - ), + compactionMessageIds, run, attempts: projection.attempts, }); - const restartNote = + // The turn start context omits settled tasks, so read them only after a Stop disposed some. + // A failed read fails the start: a turn that ran without the note would count as telling it. + const stoppedRunIds = projection.runs + .filter( + (source) => + source.providerThreadId === run.providerThreadId && + source.delegatedCompletion?.disposition === "stopped", + ) + .map((source) => source.id); + const stoppedTasks = + stoppedRunIds.length === 0 || compactionMessageIds().has(run.userMessageId) + ? [] + : pendingStoppedDelegatedTasks({ + providerThreadId: run.providerThreadId, + runs: projection.runs, + providerTurns: projection.providerTurns, + attempts: projection.attempts, + compactionMessageIds: compactionMessageIds(), + subagents: (yield* projectionStore.getThreadRecords( + projection.thread.id, + ["subagents"], + { subagentRunIds: stoppedRunIds }, + )).subagents, + }); + const restartNote = [ restartCancelledWork.length === 0 ? "" - : restartCancelledBackgroundWorkNote(restartCancelledWork); + : restartCancelledBackgroundWorkNote(restartCancelledWork), + stoppedTasks.length === 0 ? "" : stoppedDelegatedTasksNote(stoppedTasks), + ] + .filter((part) => part !== "") + .join("\n\n"); const tokenCap = yield* handoffTokenCapConfig.pipe( Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP), ); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts index b5b3a033789dd..bd5b016fdc673 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts @@ -1,10 +1,12 @@ import { assert, it } from "@effect/vitest"; import { MessageId, + NodeId, ProviderThreadId, RunAttemptId, RunId, type OrchestrationV2Run, + type OrchestrationV2Subagent, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -14,7 +16,9 @@ import { isAwaitedWork, isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, + pendingStoppedDelegatedTasks, restartContinuationNote, + stoppedDelegatedTasksNote, mergeRestartCancelledBackgroundWork, } from "./RestartBackgroundNote.ts"; @@ -277,3 +281,51 @@ it("counts a prompted mid-turn or chained continuation as delivering the note", [], ); }); + +// regression: #34401 Stop interrupted a parent's delegated tasks without telling its agent +it("tells the next completed turn about delegated tasks its Stop interrupted, once", () => { + const at = (minute: number) => DateTime.makeUnsafe(`2026-10-03T10:0${minute}:00.000Z`); + const spawning = run(1, claudeThread, { + requestedAt: at(0), + delegatedCompletion: { disposition: "stopped", nextGeneration: 1, delivery: null }, + }); + const task = (id: string, extra: Partial = {}) => + ({ + id: NodeId.make(id), + runId: spawning.id, + origin: "app_owned", + prompt: `Run ${id}.`, + title: null, + status: "interrupted", + completionDelivery: { state: "disposed", observedByRunId: null }, + completedAt: at(1), + ...extra, + }) as OrchestrationV2Subagent; + const stopped = task("stopped", { title: "Build A" }); + const subagents = [ + stopped, + task("cancelled", { cancelledRunId: RunId.make("run:child") }), + task("finished", { status: "completed" }), + task("delivered", { completionDelivery: { state: "delivered", observedByRunId: null } }), + ]; + const pending = (runs: ReadonlyArray, providerThreadId = claudeThread) => + pendingStoppedDelegatedTasks({ + providerThreadId, + runs, + providerTurns: runs.map(turnFor), + attempts: runs.map((source) => ({ id: source.activeAttemptId!, runId: source.id })), + subagents, + compactionMessageIds: new Set(), + }); + + assert.deepEqual(pending([spawning]), [stopped]); + // A /clear turn starts a fresh provider thread that never saw the stopped tasks. + assert.deepEqual(pending([spawning], codexThread), []); + assert.equal(stoppedDelegatedTasksNote([stopped]).split("\n")[1], "- Build A (task stopped)"); + // Requested while the task was still settling, so its turn start could not see it. + const racing = run(2, claudeThread, { requestedAt: at(0), startedAt: at(2) }); + assert.deepEqual(pending([spawning, racing]), [stopped]); + assert.deepEqual(pending([spawning, racing, run(3, claudeThread, { requestedAt: at(2) })]), []); + // A fresh-context turn on another provider thread never carried the note. + assert.deepEqual(pending([spawning, run(3, codexThread, { requestedAt: at(2) })]), [stopped]); +}); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 58918bdef612d..878392b8377c6 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -13,6 +13,7 @@ import { } from "@t3tools/contracts"; import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import * as DateTime from "effect/DateTime"; import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; type Work = OrchestrationV2RestartCancelledBackgroundWork; @@ -150,6 +151,77 @@ export function restartCancelledBackgroundWorkNote( ].join("\n"); } +/** + * Delegated tasks a Stop on this provider thread interrupted, until a turn requested after they + * ended completes. A run's turn start reads tasks after its request, but can record startedAt + * later. A fresh context starts a new provider thread, so it never inherits the note. + */ +export function pendingStoppedDelegatedTasks(input: { + readonly providerThreadId: OrchestrationV2Run["providerThreadId"]; + readonly runs: ReadonlyArray; + readonly providerTurns: ReadonlyArray>; + readonly attempts: ReadonlyArray; + readonly subagents: ReadonlyArray; + readonly compactionMessageIds: ReadonlySet; +}): ReadonlyArray { + const stoppedRunIds = new Set( + input.runs + .filter( + (run) => + run.providerThreadId === input.providerThreadId && + run.delegatedCompletion?.disposition === "stopped", + ) + .map((run) => run.id), + ); + if (stoppedRunIds.size === 0) return []; + const completedAttemptIds = new Set( + input.providerTurns + .filter((turn) => turn.status === "completed") + .map((turn) => turn.runAttemptId), + ); + const toldRunRequests = input.runs + .filter( + (run) => + run.providerThreadId === input.providerThreadId && + !input.compactionMessageIds.has(run.userMessageId) && + input.attempts.some( + (attempt) => attempt.runId === run.id && completedAttemptIds.has(attempt.id), + ), + ) + .map((run) => DateTime.toEpochMillis(run.requestedAt)); + return input.subagents.filter( + (task) => + task.origin === "app_owned" && + task.runId !== null && + stoppedRunIds.has(task.runId) && + task.status === "interrupted" && + task.cancelledRunId === undefined && + task.completionDelivery?.state === "disposed" && + task.completedAt !== null && + !toldRunRequests.some( + (requestedAt) => requestedAt > DateTime.toEpochMillis(task.completedAt!), + ), + ); +} + +export function stoppedDelegatedTasksNote(tasks: ReadonlyArray): string { + const omitted = tasks.length - MAX_NOTE_ENTRIES; + return [ + "Note: Stop on this thread also stopped these delegated tasks before they finished. They will not report back on their own, so check them with task_status and start again what you still need:", + ...tasks + .slice(0, MAX_NOTE_ENTRIES) + .map( + (task) => + `- ${labelWithId( + compactLabel(task.title) === undefined ? task.prompt : task.title, + "delegated task", + ` (task ${task.id})`, + )}`, + ), + ...(omitted > 0 ? [`- and ${omitted} more`] : []), + ].join("\n"); +} + type ProviderTurnState = Pick< OrchestrationV2ProviderTurn, "runAttemptId" | "providerThreadId" | "status" | "promptDropped" From f931f03d6115bbe7f2dde6817c43620f6df20528 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:26:17 -0800 Subject: [PATCH 33/96] fix(server): worktree thread lookups match any spelling of the path (#36802) Co-authored-by: Alex Southwell <4596216+saphid@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .../orchestration-v2/ProjectionStore.test.ts | 41 ++++++++++++++----- .../src/orchestration-v2/ProjectionStore.ts | 22 ++++++++-- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/106_WorktreePathKeyIndex.ts | 16 ++++++++ .../reconcileV2PreviewMigration.test.ts | 2 + 5 files changed, 70 insertions(+), 13 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index b6539e46344f1..1667a176a54a0 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -3197,6 +3197,14 @@ it.effect("SQL shells read a subagent family and a worktree's threads", () => yield* createThread({ name: "archived-child", parent: "root", root: "root", archived: true }); yield* createThread({ name: "other", worktreePath: "/repo" }); yield* createThread({ name: "other-child", parent: "other", root: "other", worktreePath }); + yield* createThread({ + name: "aliased-child", + parent: "other", + root: "other", + worktreePath: `${worktreePath}/`, + }); + yield* createThread({ name: "cased", worktreePath: worktreePath.toUpperCase() }); + yield* createThread({ name: "windows", worktreePath: "C:\\Rรฉpo\\WT" }); const family = (threadId: ThreadId) => store @@ -3208,26 +3216,39 @@ it.effect("SQL shells read a subagent family and a worktree's threads", () => assert.sameMembers([...(yield* family(id("grandchild")))], tree); assert.deepEqual([...(yield* family(id("missing")))], []); - // Includes another root's idle child on the same path, which a shell may leave out. + // Includes another root's idle child on the same path, which a shell may leave out, under any + // spelling of that path. POSIX paths keep their case. const { statements, tracer } = traceSqlStatements(); const onWorktree = yield* store .getShellSnapshot({ location: "active", worktreePath }) .pipe(Effect.withTracer(tracer)); assert.sameMembers( onWorktree.threads.map((thread) => thread.id), - [id("root"), id("child"), id("other-child")], + [id("root"), id("child"), id("other-child"), id("aliased-child")], + ); + const onWindowsWorktree = yield* store + .getShellSnapshot({ location: "active", worktreePath: "c:/Rรฉpo/wt/" }) + .pipe(Effect.withTracer(tracer)); + assert.deepEqual( + onWindowsWorktree.threads.map((thread) => thread.id), + [id("windows")], ); - // A path names a few threads; scanning every thread parses every payload. + // A path, ASCII or not, names a few threads; scanning every thread parses every payload. const sql = yield* SqlClient.SqlClient; - const threadQuery = statements.find((statement) => + const threadQueries = statements.filter((statement) => statement.includes("AS latest_run_stop_requested"), ); - assert.isDefined(threadQuery); - const threadPlan = (yield* sql.unsafe<{ readonly detail: string }>( - `EXPLAIN QUERY PLAN ${threadQuery}`, - [], - )).map((row) => row.detail); - assert.notInclude(threadPlan, "SCAN t", threadPlan.join("\n")); + assert.lengthOf(threadQueries, 2); + for (const threadQuery of threadQueries) { + const threadPlan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${threadQuery}`, + [], + )).map((row) => row.detail); + assert.isFalse( + threadPlan.some((detail) => detail.startsWith("SCAN t ")), + threadPlan.join("\n"), + ); + } // A fork keeps its deleted source's root, so the deleted root still names the live tree. yield* store.apply({ id: EventId.make("event:family:root-deleted"), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a42679d304765..36cab7ab167c7 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -102,6 +102,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts"; import { @@ -1258,6 +1259,7 @@ type ShellThreadRow = { readonly thread_id: string; readonly payload_json: string; readonly forked_from_run_source_thread_id: string | null; + readonly worktree_path: string | null; readonly latest_run_id: string | null; readonly latest_run_status: string | null; readonly latest_run_requested_at: string | null; @@ -8397,6 +8399,7 @@ export const layer: Layer.Layer = THEN json_extract(t.payload_json, '$.forkedFrom.threadId') ELSE NULL END AS forked_from_run_source_thread_id, + json_extract(t.payload_json, '$.worktreePath') AS worktree_path, presented.run_id AS latest_run_id, presented.status AS latest_run_status, presented.requested_at AS latest_run_requested_at, @@ -8593,8 +8596,12 @@ export const layer: Layer.Layer = }${ worktreePath === undefined ? sql`` - : sql` AND CASE WHEN json_valid(t.payload_json) - THEN json_extract(t.payload_json, '$.worktreePath') END = ${worktreePath}` + : // Matches orchestration_v2_projection_threads_worktree_path_key_idx, so this never + // scans. SQLite lower() folds only ASCII: Windows paths differing only in the case + // of another letter are not found. readShellSnapshotRows keeps the exact comparison. + sql` AND CASE WHEN json_valid(t.payload_json) + THEN lower(rtrim(replace(trim(json_extract(t.payload_json, '$.worktreePath')), '\\', '/'), '/')) + END = lower(rtrim(replace(trim(${worktreePath}), '\\', '/'), '/'))` }${threadIds === undefined ? sql`` : sql` AND t.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)}))`} ORDER BY t.updated_at ASC, t.thread_id ASC `; @@ -9213,7 +9220,16 @@ export const layer: Layer.Layer = const readShellSnapshotRows = Effect.fn("ProjectionStore.readShellSnapshotRows")(function* ( options: ShellSnapshotOptions | undefined, ) { - const targetThreadRows = yield* selectShellThreadRows(undefined, options); + const worktreeKey = + options?.worktreePath === undefined + ? undefined + : normalizeProjectPathForComparison(options.worktreePath); + const targetThreadRows = (yield* selectShellThreadRows(undefined, options)).filter( + (row) => + worktreeKey === undefined || + (row.worktree_path !== null && + normalizeProjectPathForComparison(row.worktree_path) === worktreeKey), + ); const targetThreadIds = new Set(targetThreadRows.map((row) => ThreadId.make(row.thread_id))); const rowsByThreadId = new Map( targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const), diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 91b521fdb6036..1b4dd6cc66ccd 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -113,6 +113,7 @@ import Migration0102 from "./Migrations/102_ThreadItemCounts.ts"; import Migration0103 from "./Migrations/103_IssueTrackerAdditionalScopes.ts"; import Migration0104 from "./Migrations/104_ProjectionProjectsTrackedFolders.ts"; import Migration0105 from "./Migrations/105_TaskFolders.ts"; +import Migration0106 from "./Migrations/106_WorktreePathKeyIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -221,6 +222,7 @@ const migrationEntries = [ [103, "IssueTrackerAdditionalScopes", Migration0103], [104, "ProjectionProjectsTrackedFolders", Migration0104], [105, "TaskFolders", Migration0105], + [106, "WorktreePathKeyIndex", Migration0106], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts b/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts new file mode 100644 index 0000000000000..9b1b42647d60a --- /dev/null +++ b/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Keep this expression identical to ProjectionStore's loose worktree filter. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_threads_worktree_path_key_idx + ON orchestration_v2_projection_threads( + CASE WHEN json_valid(payload_json) + THEN lower(rtrim(replace(trim(json_extract(payload_json, '$.worktreePath')), '\\', '/'), '/')) + END + ) + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index d2b0dafab8731..42fbb26edaa82 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -85,6 +85,7 @@ describe("V2 preview upgrade", () => { [103, "IssueTrackerAdditionalScopes"], [104, "ProjectionProjectsTrackedFolders"], [105, "TaskFolders"], + [106, "WorktreePathKeyIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -213,6 +214,7 @@ describe("V2 preview upgrade", () => { [103, "IssueTrackerAdditionalScopes"], [104, "ProjectionProjectsTrackedFolders"], [105, "TaskFolders"], + [106, "WorktreePathKeyIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From c585a58598d594255e6e550702cc982925aa6e3f Mon Sep 17 00:00:00 2001 From: xiemin Date: Sun, 22 Nov 2026 19:28:33 +0800 Subject: [PATCH 34/96] fix(mobile): prevent clipped percentages in usage limit cards (#40778) Co-authored-by: Julius Marminge --- apps/mobile/src/features/usage/UsageLimitsPooled.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 4c290d68ac338..50a987787b4e4 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -211,7 +211,7 @@ function PoolWindowCard({ {label ?? pool.label} ) : null} - + {pool.remainingPercent}% From 989247488db978c1bf5fb519726a0677568e3c7f Mon Sep 17 00:00:00 2001 From: Rodrigo Brechard Date: Sun, 22 Nov 2026 12:33:02 +0100 Subject: [PATCH 35/96] test(web): browser tests no longer fail when a stale optimizer cache reloads them mid-run (#31999) Co-authored-by: Rodrigo Brechard Co-authored-by: Julius Marminge --- apps/web/vite.config.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 005e828202bda..e107c9a7e7491 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -111,6 +111,9 @@ const browserTestProject = { include: [ "vite-plus/test/browser", "@base-ui/react/autocomplete", + "@effect/vitest", + "@pierre/diffs/ssr", + "effect/testing", "saxes", "@betteroffice/docx/editor", "@betteroffice/docx/layout", From 62a7108904c37f225c09864f6f857f7b7474dbc1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:33:14 -0800 Subject: [PATCH 36/96] fix(github): superseded runs' cancelled checks no longer block PR watches (#30434) --- .../src/server/GitHubPullRequestApi.test.ts | 16 +- .../src/server/gitHubPullRequestJson.test.ts | 145 +++++++++++++++++- .../src/server/gitHubPullRequestJson.ts | 43 +++++- .../src/server/pullRequestReads.graphql | 3 + .../src/server/pullRequestReads.graphql.ts | 10 +- 5 files changed, 209 insertions(+), 8 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index c3cc15097dfd5..9d155cab2b794 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -3949,13 +3949,25 @@ layer("GitHubPullRequestApi.layer", (it) => { name: "build", status: "COMPLETED", conclusion: "SUCCESS", - checkSuite: { workflowRun: { workflow: { name: "linux" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_linux", name: "linux" }, + }, + }, }), checkRun({ name: "build", status: "COMPLETED", conclusion: "FAILURE", - checkSuite: { workflowRun: { workflow: { name: "windows" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_windows", name: "windows" }, + }, + }, }), ], pageInfo: { hasNextPage: false, endCursor: null }, diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 37db822d34386..e049943a3978f 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -359,10 +359,18 @@ describe("pull request detail decoding", () => { checkSuite: { workflowRun: null }, ...fields, }; - const inWorkflow = ({ workflowName, ...fields }: Record) => + const inWorkflow = ({ + workflowName, + workflowId = `W_kwDORLtfbc4${String(workflowName)}`, + event = "pull_request", + runNumber = 95380, + ...fields + }: Record) => check({ ...fields, - checkSuite: { workflowRun: { workflow: { name: workflowName } } }, + checkSuite: { + workflowRun: { event, runNumber, workflow: { id: workflowId, name: workflowName } }, + }, }); const coreJson = ( @@ -655,6 +663,139 @@ describe("pull request detail decoding", () => { } }); + it("drops a cancelled check whose workflow run was superseded by a newer run on the head", () => { + const superseded = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + status: "COMPLETED", + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:00:05Z", + }; + const replacement = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95380, + status: "COMPLETED", + conclusion: "SUCCESS", + startedAt: "2026-10-30T10:00:10Z", + completedAt: "2026-10-30T10:05:00Z", + }; + const rollup = [ + inWorkflow({ ...superseded, name: "check", conclusion: "CANCELLED" }), + inWorkflow({ + ...superseded, + name: "web browser tests (runner ${{ matrix.slice }} of 6)", + conclusion: "CANCELLED", + }), + inWorkflow({ ...replacement, name: "check" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 1 of 6)" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 2 of 6)" }), + ]; + const detail = detailOf(rollup); + + expect([detail.checks.map((check) => [check.name, check.status]), detail.checksState]).toEqual([ + [ + ["check", "success"], + ["web browser tests (runner 1 of 6)", "success"], + ["web browser tests (runner 2 of 6)", "success"], + ], + "passing", + ]); + }); + + it("keeps a cancelled check when the newer run is another workflow with the same name", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + conclusion: "CANCELLED", + }), + inWorkflow({ + name: "lint", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4ToKTh", + runNumber: 95380, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test", + "cancelled", + ]); + expect(detail.checksState).toBe("failing"); + }); + + it("drops a required cancelled check once a newer run reports it, whenever it finished", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 41, + conclusion: "CANCELLED", + isRequired: true, + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:09:00Z", + }), + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 42, + conclusion: "SUCCESS", + isRequired: true, + startedAt: "2026-10-30T10:01:00Z", + completedAt: "2026-10-30T10:05:00Z", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toEqual([["test", "success"]]); + expect(detail.checksState).toBe("passing"); + }); + + it.each([ + ["a push", "push", "push", "CANCELLED", false, "cancelled"], + ["another event", "pull_request", "pull_request_target", "CANCELLED", false, "cancelled"], + ["a pull request run", "pull_request", "pull_request", "FAILURE", false, "failure"], + [ + "a pull request run, if required", + "pull_request", + "pull_request", + "CANCELLED", + true, + "cancelled", + ], + ])( + "keeps an older run's check when the newer run is %s", + (_label, olderEvent, newerEvent, conclusion, isRequired, status) => { + const detail = detailOf([ + inWorkflow({ + name: "test (packages/shared)", + workflowName: "CI", + event: olderEvent, + runNumber: 41, + conclusion, + isRequired, + }), + inWorkflow({ + name: "test (apps/server)", + workflowName: "CI", + event: newerEvent, + runNumber: 42, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test (packages/shared)", + status, + ]); + expect(detail.checksState).toBe("failing"); + }, + ); + it("merges reviews with comments in time order and keeps a bodyless approval", () => { const detail = expectSuccess(activity(JSON.parse(detailJson) as Record)); expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 7fbe86839d495..9eed567a6a4da 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -131,6 +131,13 @@ interface LatestReviewFields { readonly isMinimized?: boolean | undefined; } +/** Run numbers count up per workflow file, whatever its name; database ids exceed int32. */ +interface WorkflowRunFields { + readonly event: string; + readonly runNumber: number; + readonly workflow: { readonly id: string }; +} + /** Check runs use status/conclusion; commit statuses use a single state. */ interface CheckFields { readonly name?: string | null | undefined; @@ -143,6 +150,8 @@ interface CheckFields { readonly targetUrl?: string | null | undefined; /** Empty for app-owned runs; absent for commit statuses. */ readonly workflowName?: string | null | undefined; + /** Absent for commit statuses and app-owned runs. */ + readonly workflowRun?: WorkflowRunFields | null | undefined; readonly startedAt?: string | null | undefined; readonly completedAt?: string | null | undefined; /** Branch protection requires this check; asked for on github.com only. */ @@ -617,16 +626,42 @@ function isNamelessCheck(raw: CheckFields): boolean { return trimmed(raw.name) === null && trimmed(raw.context) === null; } -/** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ +const PULL_REQUEST_EVENTS = new Set(["pull_request", "pull_request_target"]); + +/** + * Unfinished runs outrank finished runs of the same check across push/PR workflows. A newer pull + * request run of a workflow supersedes the older one's cancelled checks, whose names can differ + * (an unexpanded matrix). Other events can run one commit in different scopes (a branch and a + * tag, dispatch inputs), so their runs replace nothing. + */ function toCheckEntries(raw: ReadonlyArray | null | undefined): ReadonlyArray<{ readonly check: PullRequestCheck; readonly workflowName: string | null; readonly at: string | null; }> { + const lineageOf = (run: WorkflowRunFields) => `${run.workflow.id} ${run.event}`; + const newestRunNumber = new Map(); + const note = (key: string, runNumber: number) => { + if (runNumber > (newestRunNumber.get(key) ?? Number.NEGATIVE_INFINITY)) { + newestRunNumber.set(key, runNumber); + } + }; + for (const check of raw ?? []) { + const run = check.workflowRun; + if (run == null || !PULL_REQUEST_EVENTS.has(run.event)) continue; + note(lineageOf(run), run.runNumber); + note(`${lineageOf(run)} ${trimmed(check.name) ?? ""}`, run.runNumber); + } return (raw ?? []).flatMap((check) => { const name = trimmed(check.name) ?? trimmed(check.context); if (name === null) return []; const status = toCheckStatus(check); + const run = check.workflowRun; + if (status === "cancelled" && run != null) { + // Branch protection names required checks, so only a newer same-name check replaces one. + const replacedBy = check.isRequired === true ? `${lineageOf(run)} ${name}` : lineageOf(run); + if (run.runNumber < (newestRunNumber.get(replacedBy) ?? run.runNumber)) return []; + } return [ { check: { @@ -1246,7 +1281,11 @@ export type GitHubCheckContext = CheckFields; function toCheckContexts(nodes: ReadonlyArray): ReadonlyArray { return nodes.map((check) => check.__typename === "CheckRun" - ? { ...check, workflowName: check.checkSuite.workflowRun?.workflow.name ?? null } + ? { + ...check, + workflowName: check.checkSuite.workflowRun?.workflow.name ?? null, + workflowRun: check.checkSuite.workflowRun, + } : check, ); } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index 2799b67525a27..0b8c5350c1408 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -42,7 +42,10 @@ fragment CheckContext on StatusCheckRollupContext { isRequired(pullRequestNumber: $number) @include(if: $required) checkSuite { workflowRun { + event + runNumber workflow { + id name } } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index ab5e211a4dec2..d26912d6aee7b 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -23,6 +23,8 @@ export interface StatusContext extends Schema.Struct.Type {} /** A workflow run. */ export const WorkflowRun = Schema.Struct({ + /** The event that triggered the workflow run */ + event: Schema.String, + /** A number that uniquely identifies this workflow run in its parent workflow. */ + runNumber: Shared.Int, /** The workflow executed in this workflow run. */ workflow: Workflow }) @@ -565,7 +571,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt mergeCommit{oid}mergedBy{__typename login avatarUrl...on User{name}}closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}mergeQueueRemovals:timelineItems(last:1 itemTypes:[REMOVED_FROM_MERGE_QUEUE_EVENT])@include(if:$", "mergeQueue", "){nodes{__typename...on RemovedFromMergeQueueEvent{id createdAt reason}}}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { @@ -617,7 +623,7 @@ export const PullRequestCheckContexts = GraphQL.query("PullRequestCheckContexts" { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){headRefOid commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100 after:$", "after", "){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { From a8363dad7fa72f7f313dbcae5f7576a6383381c5 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Sun, 22 Nov 2026 17:12:14 +0530 Subject: [PATCH 37/96] fix(web): keybindings using '+' show a plus keycap instead of empty pills (#40808) Co-authored-by: Julius Marminge --- .../KeybindingsSettings.logic.test.ts | 10 ++++++ .../settings/KeybindingsSettings.logic.ts | 8 +++-- .../settings/KeybindingsSettings.tsx | 33 ++++++++++--------- 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 4468d0ee66a14..64984a238c251 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -14,6 +14,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, shortcutToKeybindingInput, + shortcutToKeybindingParts, unknownWhenVariables, whenAstToExpression, } from "./KeybindingsSettings.logic"; @@ -250,6 +251,15 @@ describe("KeybindingsSettings.logic", () => { ).toBe("mod+m"); }); + it("keeps a literal plus key as its own part", () => { + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod++")!)).toEqual(["mod", "+"]); + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod+shift++")!)).toEqual([ + "mod", + "shift", + "+", + ]); + }); + it("serializes shortcuts and when expressions for upserts", () => { expect( shortcutToKeybindingInput({ diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 99ff61182d626..55d4278b0fe16 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -88,7 +88,7 @@ export const DEFAULT_WHEN_VARIABLE = ) ?? "terminalFocus"; const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES); -export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { +export function shortcutToKeybindingParts(shortcut: KeybindingShortcut): ReadonlyArray { const parts: string[] = []; if (shortcut.modKey) parts.push("mod"); if (shortcut.metaKey) parts.push("meta"); @@ -96,7 +96,11 @@ export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string if (shortcut.altKey) parts.push("alt"); if (shortcut.shiftKey) parts.push("shift"); parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key); - return parts.join("+"); + return parts; +} + +export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { + return shortcutToKeybindingParts(shortcut).join("+"); } export function whenAstToExpression(node: KeybindingWhenNode | undefined): string { diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 6e78c7c1935a6..0b6cc7ed41f81 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -28,6 +28,7 @@ import { AuthOrchestrationOperateScope, AuthSettingsWriteScope, type KeybindingCommand, + type KeybindingShortcut, type KeybindingWhenNode, type ServerRemoveKeybindingInput, type ServerUpsertKeybindingInput, @@ -86,6 +87,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, groupKeybindingRows, + shortcutToKeybindingParts, type KeybindingCommandOption, type KeybindingGroup, type KeybindingRow, @@ -100,35 +102,34 @@ import { keybindingSearchAnchorId, useSearchableSetting } from "./settingsSearch import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useAtomCommand } from "../../state/use-atom-command"; -function KeybindingPill({ value }: { value: string }) { - // Keys dedupe repeated parts; a literal "+" in a shortcut splits into empty strings. - const seenParts = new Map(); - const parts = value.split("+").map((part) => { - const seen = seenParts.get(part) ?? 0; - seenParts.set(part, seen + 1); - return { part, key: seen === 0 ? part : `${part}-${seen}` }; - }); +function KeybindingPill({ shortcut }: { shortcut: KeybindingShortcut }) { + const isMac = navigator.platform.toLowerCase().includes("mac"); + const parts = shortcutToKeybindingParts(shortcut); + const modifierParts = parts.slice(0, -1); + const keyPart = parts.at(-1); + return ( - {parts.map(({ part, key }) => ( - + {modifierParts.map((part) => ( + {part === "mod" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "โŒ˜" : "Ctrl" : part === "shift" ? "โ‡ง" : part === "alt" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "โŒฅ" : "Alt" : part === "ctrl" ? "โŒƒ" - : part.length === 1 - ? part.toUpperCase() - : part} + : part} ))} + {keyPart !== undefined ? ( + {keyPart.length === 1 ? keyPart.toUpperCase() : keyPart} + ) : null} ); } @@ -915,7 +916,7 @@ function KeybindingKeyControl({ Unassigned ) : ( - + )} ) : ( From d27d29fe2d31fa260a7653f54401917940e1b578 Mon Sep 17 00:00:00 2001 From: Justin Jacob <159104807+justsrc@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:20:38 +0530 Subject: [PATCH 38/96] fix(web): lineage show-more no longer clips the last row or drops focus (#31295) Co-authored-by: Justin <159104807+Justin24506@users.noreply.github.com> Co-authored-by: Julius Marminge --- ...hreadRelationshipsControl.browser.test.tsx | 42 +++++++++++++++++++ .../chat/ThreadRelationshipsControl.tsx | 13 +++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 052a5742b7aab..666ce784b3afc 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -236,6 +236,48 @@ it("opens an idle child beside the thread, and in its place with the modifier", expect(panel().surfaces).toHaveLength(1); }); +it("keeps focus on the list when Show more pages reveal the last rows", async () => { + setup(); + const projection = makeThreadProjectionFixture(); + const environmentId = EnvironmentId.make("local"); + const { updatedAt } = projection.thread; + state.projection = { + ...projection, + subagents: Array.from({ length: 7 }, (_, index) => ({ + id: NodeId.make(`agent-${index}`), + threadId: projection.thread.id, + runId: null, + parentNodeId: NodeId.make("parent"), + origin: "app_owned", + createdBy: "agent", + driver: "codex", + providerInstanceId: projection.thread.providerInstanceId, + providerThreadId: null, + childThreadId: ThreadId.make(`omitted-child-${index}`), + nativeTaskRef: null, + prompt: `Inspect the change part ${index}`, + title: `Agent ${index}`, + model: null, + status: "completed", + result: null, + startedAt: null, + completedAt: updatedAt, + updatedAt, + })), + }; + await using screen = await render( + , + ); + await screen.getByRole("button", { name: /Previous agents/ }).click(); + await screen.getByRole("button", { name: "Show 1 more" }).click(); + await expect.element(screen.getByRole("list", { name: "Related threads" })).toHaveFocus(); +}); + it("shows a lineage thread's full title in its tooltip", async () => { setup(); const longTitle = "Compare the lineage tooltip against a title that the row truncates"; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 9675a21620d32..b005fa877b745 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -121,19 +121,28 @@ function ThreadLineageRowList(props: { readonly children: ReactNode; }) { const gt = useGT(); + const listRef = useRef(null); + const showMore = () => { + const exhausting = props.hiddenCount <= THREAD_LINEAGE_PAGE_COUNT; + props.onShowMore(); + // The button unmounts on the final page; focus the list so focus isn't dropped. + if (exhausting) listRef.current?.focus({ preventScroll: true }); + }; return ( <> {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
    {props.children}
{props.hiddenCount > 0 ? ( + } + />, + ); + const editor = editorIn(screen.container); + await userEvent.click(editor.view.dom, { position: { x: 12, y: 12 } }); + await vi.waitFor(() => expect(editor.view.hasFocus()).toBe(true)); + await userEvent.click(screen.getByRole("button", { name: "Tab" })); + expect(onClick).toHaveBeenCalledOnce(); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index c3fb7fad73ff8..402156b001286 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1975,7 +1975,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
From 1e78f37618f087f8606a0bc5a4e49f546c9e2781 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:06:56 -0800 Subject: [PATCH 61/96] fix(web): keep script-only drafts reachable in the sidebar (#25272) --- apps/web/src/components/Sidebar.tsx | 20 +++++- .../SidebarDraftBlock.browser.test.tsx | 53 +++++++++++++++- .../components/sidebar/SidebarDraftBlock.tsx | 62 ++++++++++++++++--- apps/web/src/lib/discardComposerDraft.test.ts | 17 +++++ apps/web/src/lib/discardComposerDraft.ts | 32 +++++----- apps/web/src/state/terminalSessions.ts | 48 +++++++++++++- 6 files changed, 202 insertions(+), 30 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 0c14aea9056b1..f8527d0d75a1f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -271,7 +271,12 @@ import { type SidebarProviderEntry, type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; -import { SidebarDraftBlock, useSidebarDrafts } from "./sidebar/SidebarDraftBlock"; +import { + draftTerminalLabel, + SidebarDraftBlock, + useDraftTerminalLabels, + useSidebarDrafts, +} from "./sidebar/SidebarDraftBlock"; import { SidebarProjectFolderHeader, sidebarFolderRowId, @@ -1199,13 +1204,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : { projectIds: scopedProjectRefs.map((projectRef) => projectRef.projectId) }, ); const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null; + const draftTerminalLabels = useDraftTerminalLabels(); const visibleDraftSessionCount = useComposerDraftStore((store) => { let count = 0; for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) { if (session.promotedTo != null) { continue; } - if (!composerDraftHasUserContent(store.draftsByThreadKey[draftKey])) { + if ( + draftTerminalLabel(session, draftTerminalLabels) === null && + !composerDraftHasUserContent(store.draftsByThreadKey[draftKey]) + ) { continue; } if ( @@ -1440,7 +1449,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); - const { draftIds, routeDraftComposer } = useSidebarDrafts(scopedProjectKeys, routeDraftIdForRows); + const { draftIds, routeDraftComposer } = useSidebarDrafts( + scopedProjectKeys, + routeDraftIdForRows, + draftTerminalLabels, + ); // Draft rows sit above the threads, so jumps and traversal reach them first. // Search hides them, so they drop out while it is open. const listedDraftIds = isSearchingThreads ? EMPTY_DRAFT_IDS : draftIds; @@ -3576,6 +3589,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve key="draft-sessions" draftIds={draftIds} routeDraftComposer={routeDraftComposer} + terminalLabels={draftTerminalLabels} jumpLabelByDraftId={draftJumpLabelById} projectByKey={projectByKey} projectDisplayNameByKey={projectDisplayNameByKey} diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx index 7b7adf7a31ea5..9e2e6a058f220 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx @@ -8,16 +8,24 @@ import { formatAssistantCitationForComposer } from "../../composer-logic"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { SidebarDraftBlock, useSidebarDrafts } from "./SidebarDraftBlock"; -function DraftBlock() { - const { draftIds, routeDraftComposer } = useSidebarDrafts(null, null); +const NO_TERMINAL_LABELS: ReadonlyMap = new Map(); + +function DraftBlock(props: { + routeDraftId?: string | null; + terminalLabels?: ReadonlyMap; +}) { + const routeDraftId = props.routeDraftId ?? null; + const terminalLabels = props.terminalLabels ?? NO_TERMINAL_LABELS; + const { draftIds, routeDraftComposer } = useSidebarDrafts(null, routeDraftId, terminalLabels); return ( @@ -91,3 +99,42 @@ it("keeps draft previews current through edits, promotion and removal", async () await act(() => initial.clearDraftThread(nextDraftId)); await expect.element(row).not.toBeInTheDocument(); }); + +it("lists empty drafts by terminal label while their terminal exists, active or not", async () => { + const initial = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => useComposerDraftStore.setState(initial, true), + }; + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); + const environmentId = EnvironmentId.make("draft-terminal-environment"); + const terminalDraftId = DraftId.make("draft-with-terminal"); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("terminal-project")), + terminalDraftId, + { threadId: ThreadId.make("terminal-thread") }, + ); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("idle-project")), + DraftId.make("draft-without-terminal"), + { threadId: ThreadId.make("idle-thread") }, + ); + + const terminalLabels = new Map([[`${environmentId}:terminal-thread`, "dev"]]); + const block = (routeDraftId: string | null) => ( +
    + +
+ ); + await using screen = await render(block(terminalDraftId)); + const rows = screen.getByTestId("sidebar-draft-row"); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); + + await screen.rerender(block(null)); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); +}); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 3a4a74bb64f18..4cb082a1f7ddd 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -12,8 +12,10 @@ import { type MouseEvent as ReactMouseEvent, } from "react"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId } from "@t3tools/contracts"; import { useShallow } from "zustand/react/shallow"; import { cn } from "~/lib/utils"; +import { useTerminalLabelsByThreadKey } from "~/state/terminalSessions"; import { resolveSidebarRowAccessibility } from "../Sidebar.logic"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -31,9 +33,41 @@ import { JumpHintBadge, } from "./SidebarThreadRow"; +const EMPTY_COMPOSER_PARTS = { + prompt: "", + images: [], + persistedAttachments: [], + files: [], + terminalContexts: [], + previewAnnotations: [], + reviewComments: [], +} as const; + +/** Terminal labels for draft threads; an unsent draft stays listed while it has a terminal. */ +export function useDraftTerminalLabels(): ReadonlyMap { + const environmentIds = useComposerDraftStore((store) => { + const ids = new Set(); + for (const session of Object.values(store.draftThreadsByThreadKey)) { + if (session.promotedTo == null) ids.add(session.environmentId); + } + return [...ids].toSorted().join("\n"); + }); + return useTerminalLabelsByThreadKey( + environmentIds === "" ? [] : (environmentIds.split("\n") as EnvironmentId[]), + ); +} + +export function draftTerminalLabel( + session: DraftSessionState, + terminalLabels: ReadonlyMap, +): string | null { + return terminalLabels.get(`${session.environmentId}:${session.threadId}`) ?? null; +} + const SidebarDraftRow = memo(function SidebarDraftRow(props: { draftId: DraftId; - composer: ComposerThreadDraftState; + composer: ComposerThreadDraftState | null; + terminalLabel: string | null; project: ProjectFaviconProject | null; projectDisplayName: string | null; isActive: boolean; @@ -46,7 +80,8 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { source: ContextMenuSource, ) => void; }) { - const { composer, draftId, onContextMenu, onDiscard, onNavigate } = props; + const { draftId, onContextMenu, onDiscard, onNavigate } = props; + const composer = props.composer ?? EMPTY_COMPOSER_PARTS; const gt = useGT(); const promptPreview = assistantCitationsToPlainText( @@ -65,9 +100,11 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const preview = promptPreview.length > 0 ? promptPreview - : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { - count: attachmentCount, - }); + : attachmentCount === 0 && props.terminalLabel !== null + ? props.terminalLabel + : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { + count: attachmentCount, + }); const accessibility = resolveSidebarRowAccessibility({ title: preview, statusLabel: gt("Unsent draft"), @@ -174,6 +211,7 @@ function listedDraftComposer(draftId: string | null): ComposerThreadDraftState | export function useSidebarDrafts( scopedProjectKeys: ReadonlySet | null, routeDraftId: string | null, + terminalLabels: ReadonlyMap, ): { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null } { const [frozenRoute, setFrozenRoute] = useState<{ routeDraftId: string | null; @@ -195,10 +233,12 @@ export function useSidebarDrafts( ) { continue; } + // Composer edits stay frozen while open; terminals come and go live. const isListed = - draftKey === routeDraftId + draftTerminalLabel(session, terminalLabels) !== null || + (draftKey === routeDraftId ? routeDraftComposer !== null - : composerDraftHasUserContent(store.draftsByThreadKey[draftKey]); + : composerDraftHasUserContent(store.draftsByThreadKey[draftKey])); if (isListed) listed.push([draftKey, session]); } listed.sort(([, left], [, right]) => right.createdAt.localeCompare(left.createdAt)); @@ -211,6 +251,7 @@ export function useSidebarDrafts( export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null; + terminalLabels: ReadonlyMap; jumpLabelByDraftId: ReadonlyMap | null; projectByKey: ReadonlyMap; projectDisplayNameByKey: ReadonlyMap; @@ -233,8 +274,10 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { const drafts = props.draftIds.flatMap((draftId) => { const session = draftThreadsByThreadKey[draftId]; const composer = - draftId === props.routeDraftId ? props.routeDraftComposer : draftsByThreadKey[draftId]; - return session && composer ? [{ draftId, session, composer }] : []; + (draftId === props.routeDraftId ? props.routeDraftComposer : null) ?? + draftsByThreadKey[draftId] ?? + null; + return session ? [{ draftId, session, composer }] : []; }); if (drafts.length === 0) { return null; @@ -248,6 +291,7 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { key={draftId} draftId={draftId} composer={composer} + terminalLabel={draftTerminalLabel(session, props.terminalLabels)} project={props.projectByKey.get(projectKey) ?? null} projectDisplayName={props.projectDisplayNameByKey.get(projectKey) ?? null} isActive={draftId === props.routeDraftId} diff --git a/apps/web/src/lib/discardComposerDraft.test.ts b/apps/web/src/lib/discardComposerDraft.test.ts index 6c63482dfe52b..340ed6b2606e3 100644 --- a/apps/web/src/lib/discardComposerDraft.test.ts +++ b/apps/web/src/lib/discardComposerDraft.test.ts @@ -80,6 +80,23 @@ describe("discardComposerDraft", () => { } }); + it("discards and restores a draft session that has no composer record", async () => { + useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId); + const before = useComposerDraftStore.getState(); + expect(before.draftsByThreadKey).toEqual({}); + + discardComposerDraft(draftId); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); + + await undoNotice().undo(); + const after = useComposerDraftStore.getState(); + expect(after.getDraftSession(draftId)).toEqual(before.getDraftSession(draftId)); + expect(after.draftsByThreadKey).toEqual({}); + expect(after.logicalProjectDraftThreadKeyByLogicalProjectKey).toEqual( + before.logicalProjectDraftThreadKeyByLogicalProjectKey, + ); + }); + it("releases a discarded existing-thread preview when Undo is committed", async () => { using preview = imagePreview(); useComposerDraftStore.getState().addImage(threadRef, preview.image); diff --git a/apps/web/src/lib/discardComposerDraft.ts b/apps/web/src/lib/discardComposerDraft.ts index bd52b0a02879f..f1847a737dc0a 100644 --- a/apps/web/src/lib/discardComposerDraft.ts +++ b/apps/web/src/lib/discardComposerDraft.ts @@ -19,8 +19,9 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { const store = useComposerDraftStore.getState(); const key = resolveComposerDraftKey(store, target); const draft = key === null ? undefined : store.draftsByThreadKey[key]; - if (key === null || !draft) return; + if (key === null) return; const session = store.draftThreadsByThreadKey[key]; + if (!draft && !session) return; const logicalProjectKeys = Object.entries(store.logicalProjectDraftThreadKeyByLogicalProjectKey) .filter(([, draftKey]) => draftKey === key) .map(([logicalProjectKey]) => logicalProjectKey); @@ -38,6 +39,7 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { } const releaseDiscardedDraft = () => { + if (!draft) return; releaseDraftAttachments([...draft.images, ...draft.files]); // Draft-session removal already revoked these previews. if (!discardsSession) { @@ -65,19 +67,21 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] ??= key; } return { - draftsByThreadKey: { - ...state.draftsByThreadKey, - [key]: discardsSession - ? { - ...draft, - images: draft.images.map((image) => - image.previewUrl.startsWith("blob:") - ? { ...image, previewUrl: URL.createObjectURL(image.file) } - : image, - ), - } - : draft, - }, + draftsByThreadKey: draft + ? { + ...state.draftsByThreadKey, + [key]: discardsSession + ? { + ...draft, + images: draft.images.map((image) => + image.previewUrl.startsWith("blob:") + ? { ...image, previewUrl: URL.createObjectURL(image.file) } + : image, + ), + } + : draft, + } + : state.draftsByThreadKey, draftThreadsByThreadKey: session ? { ...state.draftThreadsByThreadKey, [key]: session } : state.draftThreadsByThreadKey, diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 8eaca1b774c85..0915810b47fed 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -22,7 +22,13 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { formatEnvironmentQueryError } from "./query"; import { terminalEnvironment } from "./terminal"; -import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session"; +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList"; +import { + environmentSession, + sessionHasScope, + useEnvironmentScope, + useEnvironmentsWithScope, +} from "./session"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; @@ -274,3 +280,43 @@ export function useThreadRunningTerminalIds(input: { const sessions = useKnownTerminalSessions(input); return selectRunningSubprocessTerminalIds(sessions ?? []); } + +// A string so status updates that keep every label notify no one. +const terminalLabelsFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const metadata = get(terminalEnvironment.metadata({ environmentId, input: null })); + if (metadata._tag !== "Success") return "[]"; + return JSON.stringify( + Array.from(terminalMetadataIndex(metadata.value).byThreadId, ([threadId, summaries]) => [ + threadId, + summaries[0]!.label, + ]), + ); + }).pipe(Atom.withLabel(`web-terminal-labels:${environmentId}`)), +); +const terminalLabelsListAtom = environmentAtomList("web-terminal-labels", terminalLabelsFamily); +const terminalLabelsByResults = new WeakMap, ReadonlyMap>(); + +/** First terminal label of each thread that has one, keyed `${environmentId}:${threadId}`. */ +export function useTerminalLabelsByThreadKey( + environmentIds: ReadonlyArray, +): ReadonlyMap { + const readable = useEnvironmentsWithScope( + environmentIds.map((environmentId) => ({ environmentId })), + AuthTerminalReadScope, + ); + const readableIds = environmentIds.filter((environmentId) => readable.has(environmentId)); + const results = useAtomValue(terminalLabelsListAtom(environmentIdsKey(readableIds))); + let labels = terminalLabelsByResults.get(results); + if (!labels) { + const next = new Map(); + results.forEach((encoded, index) => { + for (const [threadId, label] of JSON.parse(encoded) as Array<[string, string]>) { + next.set(`${readableIds[index]}:${threadId}`, label); + } + }); + labels = next; + terminalLabelsByResults.set(results, labels); + } + return labels; +} From b23f1e8af9b13af2c4aa1ba8e0d6987550688645 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:21:55 -0800 Subject: [PATCH 62/96] fix(server): retire unresponsive shared Codex app-servers (#25123) --- .../Adapters/CodexAdapterV2.test.ts | 174 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 82 +++++++-- .../ProviderTurnStartService.test.ts | 34 ++++ .../ProviderTurnStartService.ts | 18 +- .../provider-core/src/server/failure.test.ts | 10 + packages/provider-core/src/server/failure.ts | 2 + 6 files changed, 299 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index cd5e51a32f616..ef4ffcf35c11b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1235,6 +1235,7 @@ describe("CodexAdapterV2 session initialize", () => { runtimePolicy: CODEX_TEST_RUNTIME_POLICY, }), initializeRequests: () => initializeRequests, + runtime, events: runtime.events, }; }); @@ -1531,6 +1532,179 @@ describe("CodexAdapterV2 session initialize", () => { ), ), ); + + // The no-op notification lands right after the request is written, so the + // test advances the clock only once the app-server is known to be silent. + const requestWritten: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: "request-written", + frame: { method: "t3/test/requestWritten", params: {} }, + }; + const awaitRequestWritten = + (written: Deferred.Deferred) => + ( + entry: Parameters< + NonNullable + >[0], + ) => + entry.label === "request-written" ? Deferred.succeed(written, undefined) : Effect.void; + const UNANSWERED_REQUEST_BUDGET = "5 minutes"; + // ProviderTurnStartService skips retries and fresh-thread fallback on this tag. + const failedOnDeadline = (exit: Exit.Exit): boolean => { + if (!Exit.isFailure(exit)) return false; + let error: unknown = Cause.squash(exit.cause); + while (Predicate.hasProperty(error, "cause")) { + if (Predicate.isTagged(error, "CodexAppServerUnresponsiveError")) return true; + error = error.cause; + } + return Predicate.isTagged(error, "CodexAppServerUnresponsiveError"); + }; + + // regression: #24300 a wedged shared app-server left thread/start pending and stayed ready + it.effect("fails and retires a shared app-server that never answers thread/start", () => + Effect.gen(function* () { + const written = yield* Deferred.make(); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "thread-start-unanswered", + entries: [...replayPreamble("thread-start-unanswered").slice(0, 4), requestWritten], + }), + awaitRequestWritten(written), + ); + const events = yield* session.runtime.events.pipe( + Stream.runDrain, + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + const ensured = yield* session + .ensureThread("thread-start-unanswered") + .pipe( + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(written); + yield* TestClock.adjust(UNANSWERED_REQUEST_BUDGET); + + const settled = yield* Fiber.join(ensured); + assert.isTrue( + Option.isSome(settled) && failedOnDeadline(settled.value), + `ensureThread did not fail on the deadline within ${UNANSWERED_REQUEST_BUDGET} of an unanswered thread/start`, + ); + const retired = yield* Fiber.join(events); + assert.isTrue( + Option.isSome(retired) && Exit.isFailure(retired.value), + "session events did not fail after thread/start passed its deadline", + ); + const refused = yield* Effect.exit(session.ensureThread("thread-start-after-retire")); + const refusal = Exit.isFailure(refused) ? Cause.squash(refused.cause) : undefined; + assert.isTrue( + Predicate.hasProperty(refusal, "cause") && + Predicate.isTagged(refusal.cause, "CodexAppServerRetiredError"), + "a retired app-server accepted a new thread", + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + const turnPreamble = codexReplayPreamble({ + nativeThreadId: "turn-start-unanswered", + nativeTurnId: "turn-unanswered", + prompt: "Hello", + }); + // regression: #24300 a stopped shared app-server left a loaded thread's next turn pending forever + it.effect.each([ + { + method: "config/read", + entries: [ + ...turnPreamble.slice(0, 5), + { + type: "expect_outbound", + label: "thread/name/set", + frame: { + id: 3, + method: "thread/name/set", + params: { threadId: "turn-start-unanswered", name: CODEX_TEST_THREAD_TITLE }, + }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + { + type: "emit_inbound", + label: "thread/name/set", + frame: { id: 3, result: {} }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + { + type: "expect_outbound", + label: "config/read", + frame: { + id: 4, + method: "config/read", + params: { cwd: "/workspace", includeLayers: false }, + }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + ], + }, + { method: "turn/start", entries: turnPreamble.slice(0, 6) }, + ])("fails a turn whose $method the shared app-server never answers", ({ entries }) => + Effect.gen(function* () { + const written = yield* Deferred.make(); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "turn-start-unanswered", + entries: [...entries, requestWritten], + }), + awaitRequestWritten(written), + ); + const threadId = ThreadId.make("thread-turn-start-unanswered"); + const providerThread = yield* session.ensureThread(threadId); + + const outcome = yield* session.runtime + .startTurn( + makeCodexTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("turn-start-unanswered-attempt"), + text: "Hello", + }), + ) + .pipe( + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(written); + yield* TestClock.adjust(UNANSWERED_REQUEST_BUDGET); + const settled = yield* Fiber.join(outcome); + + assert.isTrue( + Option.isSome(settled), + `startTurn was still waiting after ${UNANSWERED_REQUEST_BUDGET}`, + ); + if (Option.isSome(settled)) { + assert.isTrue(failedOnDeadline(settled.value), "startTurn did not fail on the deadline"); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); }); describe("CodexAdapterV2 post-settle continuation", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 09036b09e3f77..e5dfd83559292 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -541,6 +541,26 @@ function codexMcpToolOutput( // A hung MCP resource read must not hold run ingestion open. const MCP_APP_CAPTURE_TIMEOUT = "20 seconds"; +// Session setup and turn start requests answer promptly; silence this long means a wedged app-server. +const CODEX_APP_SERVER_REQUEST_DEADLINE = "2 minutes"; + +class CodexAppServerUnresponsiveError extends Schema.TaggedError()( + "CodexAppServerUnresponsiveError", + { method: Schema.String }, +) { + override get message() { + return `Codex app-server did not answer ${this.method} within ${CODEX_APP_SERVER_REQUEST_DEADLINE}.`; + } +} + +class CodexAppServerRetiredError extends Schema.TaggedError()( + "CodexAppServerRetiredError", + {}, +) { + override get message() { + return "Codex app-server was retired and accepts no new work."; + } +} function codexMcpAppResourceUri(item: CodexDynamicToolItem): string | undefined { if (item.type !== "mcpToolCall") return undefined; @@ -2140,6 +2160,39 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); // A failed open is discarded, so the next turn spawns the updated binary. if (adapterOptions.compatibility !== undefined) yield* ensureInitialized; + // Failing the event stream makes the session manager release this app-server. + // Queue.fail lets readers take items already buffered before they see the failure. + // Buffered events drain before the session manager drops this runtime; refuse work meanwhile. + let retired = false; + const retireAppServer = (cause: unknown) => + Effect.suspend(() => { + retired = true; + return Queue.fail( + events, + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: CODEX_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ); + }); + const rejectIfRetired = Effect.suspend(() => + retired ? Effect.fail(new CodexAppServerRetiredError()) : Effect.void, + ); + yield* client.awaitTermination.pipe(Effect.catch(retireAppServer), Effect.forkScoped); + // The outcome of an unanswered request is unknown, so it fails rather than retries. + const withAppServerDeadline = + (method: string) => + (effect: Effect.Effect) => + effect.pipe( + Effect.timeoutOrElse({ + duration: CODEX_APP_SERVER_REQUEST_DEADLINE, + orElse: () => { + const error = new CodexAppServerUnresponsiveError({ method }); + return retireAppServer(error).pipe(Effect.andThen(Effect.fail(error))); + }, + }), + ); // Read per thread: a workspace's project config can add its own servers. const readStdioMcpServers = (cwd: string | null | undefined) => ensureInitialized.pipe( @@ -2155,6 +2208,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.as>([]), ), ), + withAppServerDeadline("config/read"), ); const now = yield* DateTime.now; const session = providerSession({ @@ -2164,21 +2218,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( model: input.modelSelection.model, now, }); - // Drain final notifications before the session manager retires the dead process. - // Queue.fail lets readers take items already buffered before they see the failure. - yield* client.awaitTermination.pipe( - Effect.catch((cause) => - Queue.fail( - events, - new ProviderAdapter.ProviderAdapterEventStreamError({ - driver: CODEX_PROVIDER, - providerSessionId: input.providerSessionId, - cause, - }), - ), - ), - Effect.forkScoped, - ); const rateLimitSnapshot = yield* Ref.make(undefined); const limitedTurnItems = yield* Ref.make( new Map>(), @@ -7677,6 +7716,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined)), ), + withAppServerDeadline("config/read"), ); const turnStartParams = yield* buildCodexTurnStartParams({ cyberAccess: codexCyberAccess(models, turnInput.modelSelection.model), @@ -7708,7 +7748,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(yield* Ref.get(settledTurns)), ...(yield* Ref.get(activeTurns)), ]); - const started = yield* client.request("turn/start", turnStartParams); + const started = yield* client + .request("turn/start", turnStartParams) + .pipe(withAppServerDeadline("turn/start")); const previousTurn = previousTurns.get(started.turn.id) ?? (yield* Ref.get(activeTurns)).get(started.turn.id); @@ -7798,6 +7840,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, command: OrchestrationV2GoalCommand, ) { + yield* rejectIfRetired; if (command.type === "set") yield* validateCodexGoalObjective(command.objective); const threadId = yield* getNativeThreadId(turnInput.providerThread); rootProviderThreads.set(threadId, turnInput.providerThread); @@ -8075,7 +8118,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return false; }), ensureThread: (threadInput) => - ensureInitialized.pipe( + rejectIfRetired.pipe( + Effect.andThen(ensureInitialized), Effect.andThen( Effect.all([ mcpSessions.read(threadInput.threadId), @@ -8107,6 +8151,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( thread: response.thread, }), ), + withAppServerDeadline("thread/start"), Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterEnsureThreadError({ @@ -8118,6 +8163,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), resumeThread: Effect.fn("CodexAdapterV2.resumeThread")( function* (threadInput) { + yield* rejectIfRetired; const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread); const appThreadId = threadInput.threadId ?? threadInput.providerThread.appThreadId; const resume = resumeNativeThread(nativeThreadId, { @@ -8140,6 +8186,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( goalUpdatesHeld.add(nativeThreadId); const response = yield* ensureInitialized.pipe( Effect.andThen(resume), + withAppServerDeadline("thread/resume"), Effect.flatMap(decodeCodexResumeMetadata), // Stay registered: a lost or undecodable response may still have resumed the thread. Effect.onError(() => @@ -8252,6 +8299,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand); const nativeThreadId = turnInput.providerThread.nativeThreadRef?.nativeId; return Effect.gen(function* () { + yield* rejectIfRetired; if ( !continuation && nativeThreadId != null && diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 864d6f253ad41..ef9bd2bb32712 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -3163,6 +3163,40 @@ effectIt.effect("leaves the run starting when a session-open failure will be ret }), ); +effectIt.effect("fails rather than retries a provider thread request with an unknown outcome", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + ensureThreadFailure: { _tag: "CodexAppServerUnresponsiveError", method: "thread/start" }, + }); + + yield* harness.startWithRetry; + + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + +effectIt.effect("fails rather than starts a fresh thread when a resume outcome is unknown", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + resumeFailure: new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: ProviderDriverKind.make("codex"), + providerSessionId: ProviderSessionId.make("resume-provider-session"), + cause: { _tag: "CodexAppServerUnresponsiveError", method: "thread/resume" }, + }), + }); + + const exit = yield* Effect.exit(harness.startWithRetry); + + expect(exit._tag).toBe("Success"); + expect(harness.fallbackEnsureThread).not.toHaveBeenCalled(); + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + effectIt.effect("fails the run without a retry when the provider needs sign-in", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 317dff4b395b6..1cb77e387f950 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -165,6 +165,13 @@ const refusedBeforePrompt = (error: unknown): boolean => error.detail === CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL) || (Predicate.hasProperty(error, "cause") && refusedBeforePrompt(error.cause)); +// The provider may have acted on a request it never answered, so a retry could duplicate it. +const OUTCOME_UNKNOWN_TAGS = ["CodexAppServerUnresponsiveError"] as const; + +const outcomeUnknown = (error: unknown): boolean => + OUTCOME_UNKNOWN_TAGS.some((tag) => Predicate.isTagged(error, tag)) || + (Predicate.hasProperty(error, "cause") && outcomeUnknown(error.cause)); + /** * Whether a non-truncating provider's native session lost the conversation kept before `run`. * Rollback resets it: the newest accepted turn was rolled back (works without legacy-missing @@ -998,7 +1005,9 @@ export const layer: Layer.Layer< ) { const loaded = yield* Effect.result(load); if (loaded._tag === "Success") return loaded.success; - if (input.willRetry === true) return yield* loaded.failure; + if (input.willRetry === true && !outcomeUnknown(loaded.failure)) { + return yield* loaded.failure; + } yield* settleStartFailure({ signal: "provider-thread-load-failure", title: "Provider turn failed to start", @@ -1718,11 +1727,12 @@ export const layer: Layer.Layer< resumedHandoffContext = undefined; resumedRetryHandoff = undefined; if (!(yield* isCurrentAttemptInStatus("starting"))) return undefined; - // Another client is still writing to the native thread. A fresh - // session here would silently split the conversation from it. + // Another client is still writing to the native thread, or the provider may have + // resumed it without answering. A fresh session would split the conversation. if ( resumed._tag === "Failure" && - resumed.failure._tag === "ProviderAdapterThreadInUseError" + (resumed.failure._tag === "ProviderAdapterThreadInUseError" || + outcomeUnknown(resumed.failure)) ) { return yield* loadFromProvider(Effect.fail(resumed.failure)); } diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index a29b60d4d25ae..7f4b790927488 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -132,6 +132,16 @@ it("preserves actionable T3 errors wrapped by turn startup", () => { }); assert.equal(makeProviderFailure({ cause: Cause.fail(cause) }).message, error.message); } + const unanswered = { + _tag: "CodexAppServerUnresponsiveError", + message: "Codex app-server did not answer turn/start within 2 minutes.", + }; + assert.equal( + makeProviderFailure({ + cause: Cause.fail({ _tag: "ProviderAdapterEventStreamError", cause: unanswered }), + }).message, + unanswered.message, + ); }); it("names how the provider process exited and the stage it failed in, without its output", () => { diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index cfdb0eb3df9a6..e7d47cdb2175e 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -139,6 +139,8 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError": case "CodexGoalObjectiveTooLongError": + case "CodexAppServerUnresponsiveError": + case "CodexAppServerRetiredError": case "ProviderSetupError": case "ProviderAdapterThreadInUseError": case "ProviderCompactionUnsupportedError": From a985332c447173750394c0875fb961f88c306730 Mon Sep 17 00:00:00 2001 From: maria Date: Sun, 22 Nov 2026 10:28:38 -0300 Subject: [PATCH 63/96] fix(shared): Windows command discovery no longer blocks the event loop (#27391) Co-authored-by: Enmani <43571965+Enmani@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.testkit.ts | 4 +- .../provider/Drivers/ClaudeExecutable.test.ts | 2 +- .../src/provider/Drivers/ClaudeExecutable.ts | 4 +- apps/server/src/terminal/Manager.ts | 11 +-- .../src/server/AcpRegistrySupport.test.ts | 11 ++- .../src/server/AcpRegistrySupport.ts | 57 ++++++++----- .../src/server/clientTerminals.ts | 2 +- .../provider-muse/src/server/MuseUsageHome.ts | 6 +- packages/provider-muse/src/server/sdk.test.ts | 2 +- packages/provider-muse/src/server/sdk.ts | 3 +- .../provider-muse/src/server/usage.test.ts | 2 +- packages/shared/src/shell.test.ts | 85 +++++++++++++++++-- packages/shared/src/shell.ts | 77 +++++++++-------- .../src/server/AzureDevOpsCli.test.ts | 2 +- .../src/server/AzureDevOpsCli.ts | 3 +- .../src/server/discovery.ts | 3 +- 16 files changed, 190 insertions(+), 84 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index bed26e69ae008..5d08adab93042 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -1496,7 +1496,9 @@ const resolveClaudeRecordingExecutablePath = Effect.fn("resolveClaudeRecordingEx function* (environment: NodeJS.ProcessEnv) { const resolveExecutable = yield* SpawnExecutableResolution; const platform = yield* HostProcess.Platform; - const resolved = resolveExecutable("claude", platform, environment); + const resolved = yield* Effect.promise(async () => + resolveExecutable("claude", platform, environment), + ); if (resolved === undefined) { return undefined; } diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index b6dc61470e497..36d7e3f3313fc 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -21,7 +21,7 @@ function withWindowsResolution(input: { return (effect: Effect.Effect) => effect.pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => input.resolvedCommand), + Effect.provideService(SpawnExecutableResolution, async () => input.resolvedCommand), Effect.provideService(ClaudeExecutableFileCheck, (filePath) => existing.has(filePath)), ); } diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 5797066446b99..6f4e85812f0cc 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -50,7 +50,9 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta const resolveExecutable = yield* SpawnExecutableResolution; const isFile = yield* ClaudeExecutableFileCheck; - const resolved = resolveExecutable(binaryPath, platform, environment) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, platform, environment))) ?? + binaryPath; const extension = NodePath.win32.extname(resolved).toLowerCase(); if (!WINDOWS_SHIM_EXTENSIONS.has(extension)) { return resolved; diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index fb19b6c7ad1d6..e87ba67cf5837 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -2791,15 +2791,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func .join(":"), }; // POSIX node-pty can return a PTY before exec fails, so validate before accepting a candidate. + const shellCommand = candidate.shell.includes("/") + ? path.resolve(session.cwd, candidate.shell) + : candidate.shell; const executable = platform !== "win32" - ? resolveExecutable( - candidate.shell.includes("/") - ? path.resolve(session.cwd, candidate.shell) - : candidate.shell, - platform, - lookupEnv, - ) + ? yield* Effect.promise(async () => resolveExecutable(shellCommand, platform, lookupEnv)) : candidate.shell; if (executable === undefined) { return yield* trySpawn( diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 398c48be3f68c..75311d6598b7e 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -318,7 +318,7 @@ describe("AcpRegistrySupport", () => { registryUrl, }).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => `C:\\bin\\dsh${extension}`), + Effect.provideService(SpawnExecutableResolution, async () => `C:\\bin\\dsh${extension}`), ); const localSettings = decodeAcpRegistrySettings({ source: "local", commandPath: "dsh" }); for (const failure of [ @@ -1206,6 +1206,7 @@ describe("AcpRegistrySupport", () => { name: "Codex Darwin", } satisfies AcpRegistrySupport.AcpRegistryAgent; + const lookups: string[] = []; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ @@ -1215,9 +1216,15 @@ describe("AcpRegistrySupport", () => { cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, - }); + }).pipe( + Effect.provideService(SpawnExecutableResolution, async (command) => { + lookups.push(command); + return "/bin/npm"; + }), + ); const result = yield* resolver.search({ query: "codex" }); + expect(lookups).toEqual(["npm"]); expect(result.agents.map((agent) => agent.id)).toEqual(["codex-acp", "other-agent"]); expect(result.agents[0]).toMatchObject({ authors: ["OpenAI", "Zed Industries"], diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index d3ab397d7aaeb..26d58fb4ea9ad 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -673,7 +673,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const hostEnvironment = yield* HostProcess.Environment; - const resolveExecutable = yield* SpawnExecutableResolution; + const executableResolver = yield* SpawnExecutableResolution; + const resolveExecutable = Effect.fn("AcpRegistryCatalog.resolveExecutable")(function* ( + command: string, + environment: NodeJS.ProcessEnv, + ) { + return yield* Effect.promise(async () => executableResolver(command, platform, environment)); + }); const platformTarget = resolveAcpRegistryPlatformTarget(platform, architecture); const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL; const registryDirectory = path.join(input.cacheDir, "acp-registry"); @@ -1240,9 +1246,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const commandName = npmCommandName(agent, packageIdentity.name, manifest.value); if (commandName === undefined) return Option.none(); const binDirectory = platform === "win32" ? globalPrefix : path.join(globalPrefix, "bin"); - const executablePath = resolveExecutable( + const executablePath = yield* resolveExecutable( path.join(binDirectory, commandName), - platform, environment, ); return executablePath === undefined @@ -1289,9 +1294,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct truncatedOutputReason: "install_failed", }).pipe(Effect.flatMap((output) => parsePackageManagerPath(managerPath, output))); const managedBinEnvironment = { ...environment, PATH: binDirectory }; - const executablePath = packageCommandCandidates(agent, packageIdentity.name) - .map((candidate) => resolveExecutable(candidate, platform, managedBinEnvironment)) - .find((candidate): candidate is string => candidate !== undefined); + let executablePath: string | undefined; + for (const candidate of packageCommandCandidates(agent, packageIdentity.name)) { + executablePath = yield* resolveExecutable(candidate, managedBinEnvironment); + if (executablePath !== undefined) break; + } return executablePath === undefined ? Option.none() : Option.some({ @@ -1314,7 +1321,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct environment: NodeJS.ProcessEnv, ) { const managerName = packageManagerFor(distribution)!; - const managerPath = resolveExecutable(managerName, platform, environment); + const managerPath = yield* resolveExecutable(managerName, environment); if (managerPath === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", @@ -1740,22 +1747,27 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")( function* (input) { const registry = yield* recentRegistry(); - const ranked = registry.agents.flatMap((agent) => { + const ranked = []; + const managerAvailability = new Map(); + for (const agent of registry.agents) { const distribution = resolveAcpRegistryDistribution({ agent, preference: "auto", platformTarget, }); const rank = searchRank(agent, input.query); - const packageManager = - distribution === undefined ? undefined : packageManagerFor(distribution.kind); - const packageManagerAvailable = - packageManager === undefined || - resolveExecutable(packageManager, platform, hostEnvironment) !== undefined; - return distribution === undefined || rank === undefined || !packageManagerAvailable - ? [] - : [{ agent, distribution, rank }]; - }); + if (distribution === undefined || rank === undefined) continue; + const packageManager = packageManagerFor(distribution.kind); + if (packageManager !== undefined) { + let available = managerAvailability.get(packageManager); + if (available === undefined) { + available = (yield* resolveExecutable(packageManager, hostEnvironment)) !== undefined; + managerAvailability.set(packageManager, available); + } + if (!available) continue; + } + ranked.push({ agent, distribution, rank }); + } ranked.sort( (left, right) => left.rank - right.rank || @@ -1826,7 +1838,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (settings.source === "local") { const command = settings.commandPath.trim(); if (!command) return { status: "unconfigured" } as const; - const executable = resolveExecutable(command, platform, environment ?? hostEnvironment); + const executable = yield* resolveExecutable(command, environment ?? hostEnvironment); if (executable !== undefined) yield* validateLocalExecutable(executable); return executable === undefined ? ({ @@ -1854,8 +1866,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const commandOverride = settings.commandPath.trim(); if (commandOverride.length > 0) { const available = - resolveExecutable(commandOverride, platform, environment ?? hostEnvironment) !== - undefined; + (yield* resolveExecutable(commandOverride, environment ?? hostEnvironment)) !== undefined; return available ? ({ status: "ready", @@ -1919,7 +1930,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const runner = packageManagerFor(distribution.kind)!; const available = - resolveExecutable(runner, platform, environment ?? hostEnvironment) !== undefined; + (yield* resolveExecutable(runner, environment ?? hostEnvironment)) !== undefined; return available ? ({ status: "ready", @@ -1960,7 +1971,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const effectiveEnvironment = environment ?? hostEnvironment; const commandOverride = settings.commandPath.trim(); if (commandOverride.length > 0) { - const resolvedOverride = resolveExecutable(commandOverride, platform, effectiveEnvironment); + const resolvedOverride = yield* resolveExecutable(commandOverride, effectiveEnvironment); if (resolvedOverride === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", @@ -2028,7 +2039,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } const env = environment ?? hostEnvironment; - const command = resolveExecutable(executable, platform, env); + const command = yield* resolveExecutable(executable, env); if (command === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index c8371fb7020e8..592bf47553494 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -263,7 +263,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. const gitExecutable = isWindows && options.shellCommands === true - ? resolveExecutable("git", "win32", environment) + ? yield* Effect.promise(async () => resolveExecutable("git", "win32", environment)) : undefined; const posixShell = gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts index 1ced0d2578b01..329dce90c0e7b 100644 --- a/packages/provider-muse/src/server/MuseUsageHome.ts +++ b/packages/provider-muse/src/server/MuseUsageHome.ts @@ -66,7 +66,11 @@ const make = Effect.gen(function* () { if (Option.isSome(settled)) return settled; // Spawn failures surface asynchronously; without this a missing CLI would report as pending. const resolveExecutable = yield* SpawnExecutableResolution; - if (resolveExecutable(binaryPath, yield* HostProcess.Platform, environment) === undefined) { + const platform = yield* HostProcess.Platform; + const resolved = yield* Effect.promise(async () => + resolveExecutable(binaryPath, platform, environment), + ); + if (resolved === undefined) { return Option.some(undefined); } if (awaitRefresh) return Option.some(yield* Cache.get(cache, key)); diff --git a/packages/provider-muse/src/server/sdk.test.ts b/packages/provider-muse/src/server/sdk.test.ts index 45ef56cb63458..6607640751092 100644 --- a/packages/provider-muse/src/server/sdk.test.ts +++ b/packages/provider-muse/src/server/sdk.test.ts @@ -263,7 +263,7 @@ describe("Muse launch", () => { const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) => museLaunch("muse", env).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => resolved), + Effect.provideService(SpawnExecutableResolution, async () => resolved), ); it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () => diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts index 6d6b4d5d51050..aece589b1e188 100644 --- a/packages/provider-muse/src/server/sdk.ts +++ b/packages/provider-muse/src/server/sdk.ts @@ -117,7 +117,8 @@ export const museLaunch = Effect.fn("museLaunch")(function* ( if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] }; const env = environment ?? (yield* HostProcess.Environment); const resolveExecutable = yield* SpawnExecutableResolution; - const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, "win32", env))) ?? binaryPath; if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] }; const systemRoot = windowsEnvironmentValue(env, "SystemRoot"); return { diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index 3815cfce44321..d02271f44ff04 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -260,7 +260,7 @@ describe("Muse history discovery", () => { expect(create).not.toHaveBeenCalled(); }).pipe( Effect.provide([NodeServices.layer, MuseUsageHome.layer]), - Effect.provideService(SpawnExecutableResolution, () => undefined), + Effect.provideService(SpawnExecutableResolution, async () => undefined), ), ); diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 08731a41c19ef..8f81723486f55 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -577,7 +577,9 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ), ).toBe(path.join(directory, "audit-command")); const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); + expect( + yield* Effect.promise(async () => resolveExecutable("audit-command", "linux", env)), + ).toBe(executable); }), ); @@ -736,7 +738,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( - "relists a changed PATH directory in the synchronous spawn resolver", + "relists a changed PATH directory in the spawn resolver", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -746,11 +748,17 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { yield* fs.utimes(directory, 946_684_800, 946_684_800); const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("cursor", "win32", env)).toBe(path.join(directory, "cursor.CMD")); - expect(resolveExecutable("late", "win32", env)).toBeUndefined(); + expect(yield* Effect.promise(async () => resolveExecutable("cursor", "win32", env))).toBe( + path.join(directory, "cursor.CMD"), + ); + expect( + yield* Effect.promise(async () => resolveExecutable("late", "win32", env)), + ).toBeUndefined(); yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); yield* fs.utimes(directory, 946_684_830, 946_684_830); - expect(resolveExecutable("late", "win32", env)).toBe(path.join(directory, "late.EXE")); + expect(yield* Effect.promise(async () => resolveExecutable("late", "win32", env))).toBe( + path.join(directory, "late.EXE"), + ); }), ); }); @@ -975,6 +983,73 @@ describe("npmShimExecutable", () => { }); effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { + it.effect("yields while discovering a Windows executable", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const executable = path.join(directory, "tool.EXE"); + yield* fs.writeFileString(executable, ""); + let settled = false; + const pending = Promise.resolve( + SpawnExecutableResolution.defaultValue()(executable, "win32", { PATHEXT: ".EXE;.CMD" }), + ).then((value) => { + settled = true; + return value; + }); + try { + yield* Effect.promise(() => Promise.resolve()); + expect(settled).toBe(false); + } finally { + expect(yield* Effect.promise(() => pending)).toBe(executable); + } + }), + ), + ); + + it.effect("preserves PATH and PATHEXT order and discovers executables after a miss", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const fixture = NodePath.join(directory, "tool.EXE"); + yield* fs.writeFileString(fixture, ""); + const stat = yield* Effect.promise(() => NodeFS.promises.stat(fixture)); + const files = new Set(); + using _stat = vi.spyOn(NodeFS.promises, "stat").mockImplementation(async (candidate) => { + if (!files.has(String(candidate))) throw new Error("not found"); + return stat; + }); + const lookup = resolveSpawnCommand("tool", ["status"], { + env: { PATH: "C:\\first;C:\\later", PATHEXT: ".EXE;.CMD" }, + }); + expect((yield* lookup).command).toBe("tool"); + files.add("C:\\first\\tool.CMD"); + files.add("C:\\first\\tool.EXE"); + files.add("C:\\later\\tool.EXE"); + expect(yield* lookup).toEqual({ + command: "C:\\first\\tool.EXE", + args: ["status"], + shell: false, + }); + files.delete("C:\\first\\tool.EXE"); + expect((yield* lookup).command).toBe("C:\\first\\tool.EXE"); + expect( + yield* Effect.promise(async () => + SpawnExecutableResolution.defaultValue()("tool", "win32", { + PATH: "C:\\first;C:\\later", + PATHEXT: ".EXE;.CMD", + }), + ), + ).toBe("C:\\first\\tool.CMD"); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + ), + ), + ); + it.effect("runs Windows executables directly without a shell", () => Effect.gen(function* () { const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index ffcc1110fe381..0ba42dc3078d6 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -75,13 +75,13 @@ export type SpawnExecutableResolver = ( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -) => string | undefined; +) => string | undefined | Promise; -function resolveSpawnExecutableWithNode( +async function resolveSpawnExecutableWithNode( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): string | undefined { +): Promise { const path = platform === "win32" ? NodePath.win32 : NodePath.posix; const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; const candidates = resolveCommandCandidates( @@ -90,20 +90,24 @@ function resolveSpawnExecutableWithNode( windowsPathExtensions, path.extname, ); - const isExecutable = (candidate: string) => { + const isExecutable = async (candidate: string) => { try { - if (!NodeFS.statSync(candidate).isFile()) return false; + if (!(await NodeFS.promises.stat(candidate)).isFile()) return false; if (platform === "win32") { return windowsPathExtensions.includes(path.extname(candidate).toUpperCase()); } - return canExecuteFile(candidate); + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return true; } catch { return false; } }; if (command.includes("/") || command.includes("\\")) { - return candidates.find(isExecutable); + for (const candidate of candidates) { + if (await isExecutable(candidate)) return candidate; + } + return undefined; } for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { @@ -111,12 +115,12 @@ function resolveSpawnExecutableWithNode( if (normalizedPathEntry.length === 0) continue; const names = platform === "win32" - ? listPathDirectorySync(normalizedPathEntry, path.isAbsolute) + ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute) : undefined; for (const candidate of candidates) { if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); - if (isExecutable(candidatePath)) return candidatePath; + if (await isExecutable(candidatePath)) return candidatePath; } } return undefined; @@ -661,42 +665,42 @@ export const PathDirectoryListings = Context.Reference( { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, ); -const syncPathDirectoryListings = new Map< +const resolverPathDirectoryListings = new Map< string, { readonly modified: number; readonly names: ReadonlySet } >(); -// The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. -function listPathDirectorySync( +// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules. +async function listResolverPathDirectory( directory: string, isAbsolute: (path: string) => boolean, -): ReadonlySet | undefined { +): Promise | undefined> { let modified: number; try { - const stats = NodeFS.statSync(directory); + const stats = await NodeFS.promises.stat(directory); if (!stats.isDirectory()) return undefined; modified = stats.mtimeMs; } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; } - const cached = syncPathDirectoryListings.get(directory); + const cached = resolverPathDirectoryListings.get(directory); if (cached?.modified === modified) return cached.names; - syncPathDirectoryListings.delete(directory); + resolverPathDirectoryListings.delete(directory); // This resolver runs outside Effect, so it has no Clock to read. // @effect-diagnostics-next-line globalDate:off const listedAtMs = Date.now(); let names: ReadonlySet; try { - names = new Set(NodeFS.readdirSync(directory).map((entry) => entry.toLowerCase())); + names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase())); } catch { return undefined; } if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { - if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { - const oldest = syncPathDirectoryListings.keys().next().value; - if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); + if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = resolverPathDirectoryListings.keys().next().value; + if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest); } - syncPathDirectoryListings.set(directory, { modified, names }); + resolverPathDirectoryListings.set(directory, { modified, names }); } return names; } @@ -1002,18 +1006,21 @@ const resolveMacosGit = Effect.fnUntraced(function* ( const nowNanos = yield* Clock.currentTimeNanos; const cached = cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. - if ( - cached !== undefined && - cached.expiresAtNanos > nowNanos && - (cached.resolvedPath === null || - resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined) - ) { - return cached.resolvedPath ?? "git"; + if (cached !== undefined && cached.expiresAtNanos > nowNanos) { + const cachedPath = cached.resolvedPath; + if ( + cachedPath === null || + (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== + undefined + ) { + return cachedPath ?? "git"; + } } - const located = - resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = - located !== undefined && resolveExecutable(located, "darwin", env) !== undefined + located !== undefined && + (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located : null; cacheCommandResolution(cache, cacheKey, realGit, nowNanos); @@ -1093,10 +1100,8 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( shell: false, }; } - // The scan is synchronous and runs before every child process, so it shares - // the PATH scan cache above. Explicit paths stay uncached for the same reason, - // and so do misses: a failed spawn is how providers report "not installed", - // and that has to clear the moment the binary appears. + // Cache successful PATH lookups. Explicit paths and misses stay uncached so + // newly installed executables are discoverable immediately. const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ @@ -1114,7 +1119,7 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( if (cached !== undefined && cached.expiresAtNanos > nowNanos) { resolvedExecutable = cached.resolvedPath; } else { - const found = resolveExecutable(command, platform, env); + const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env)); resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env); if (!explicitPath && resolvedExecutable !== null) { cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts index 6e4600fe5a338..c71f1f36df2fb 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts @@ -414,7 +414,7 @@ describe("azureCliInvocation", () => { AzureDevOpsCli.azureCliInvocation().pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }), - Effect.provideService(SpawnExecutableResolution, () => launcher), + Effect.provideService(SpawnExecutableResolution, async () => launcher), Effect.provideService(AzureCliInstallLocation, () => install), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts index 6cffe9ab0b3ab..f289e7406950f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -495,7 +495,8 @@ export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(functio return { command: "az", args: [] } satisfies AzureCliInvocation; } const resolveExecutable = yield* SpawnExecutableResolution; - const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const launcher = yield* Effect.promise(async () => resolveExecutable("az", "win32", env)); const installFor = yield* AzureCliInstallLocation; const install = launcher === undefined ? undefined : installFor(launcher); // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode. diff --git a/packages/source-control-core/src/server/discovery.ts b/packages/source-control-core/src/server/discovery.ts index 62ec94d7d67fe..0cc6654adf021 100644 --- a/packages/source-control-core/src/server/discovery.ts +++ b/packages/source-control-core/src/server/discovery.ts @@ -357,7 +357,8 @@ const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(fun return installHint; } const resolveExecutable = yield* SpawnExecutableResolution; - const path = resolveExecutable(executable, platform, yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const path = yield* Effect.promise(async () => resolveExecutable(executable, platform, env)); const architecture = yield* HostProcess.Architecture; return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`; }); From b479ce21edae40ed1bcd02d117e54bb7243e5897 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:34:59 -0800 Subject: [PATCH 64/96] fix(client-runtime): stop sessions on incompatible server configuration (#21667) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/i18n/translations/de.json | 3 + apps/mobile/src/i18n/translations/en.json | 3 + apps/mobile/src/i18n/translations/es.json | 3 + apps/mobile/src/i18n/translations/fr.json | 3 + apps/mobile/src/i18n/translations/ja.json | 3 + apps/mobile/src/i18n/translations/ko.json | 3 + apps/mobile/src/i18n/translations/pt-BR.json | 3 + apps/mobile/src/i18n/translations/ru.json | 3 + apps/mobile/src/i18n/translations/sv.json | 3 + apps/mobile/src/i18n/translations/zh.json | 3 + apps/web/src/i18n/translations/de.json | 3 + apps/web/src/i18n/translations/en.json | 3 + apps/web/src/i18n/translations/es.json | 3 + apps/web/src/i18n/translations/fr.json | 3 + apps/web/src/i18n/translations/ja.json | 3 + apps/web/src/i18n/translations/ko.json | 3 + apps/web/src/i18n/translations/pt-BR.json | 3 + apps/web/src/i18n/translations/ru.json | 3 + apps/web/src/i18n/translations/sv.json | 3 + apps/web/src/i18n/translations/zh.json | 3 + .../client-runtime/src/rpc/session.test.ts | 80 +++++++++ packages/client-runtime/src/rpc/session.ts | 154 ++++++++++++------ 22 files changed, 241 insertions(+), 53 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 039e1ddadd0bf..f4d80a116eece 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 91170171c1621..62b182b1a30c9 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 398c20ce17f1f..55d4e81456cc5 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexiรณn WebSocket.", "d9ce6c142a485959": "{host} dejรณ de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectรณ.", + "8450a95e5214d199": "{host} enviรณ una actualizaciรณn de la configuraciรณn del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} enviรณ una configuraciรณn del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 1734d91934a04..245547981f3dc 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} nโ€™a pas pu รฉtablir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne rรฉpond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est dรฉconnectรฉ.", + "8450a95e5214d199": "{host} a envoyรฉ une mise ร  jour de la configuration du serveur que ce client nโ€™a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyรฉ une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez ร  jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "ร‰chec de lโ€™envoi. Touchez pour rรฉessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 113ada551f17d..a62452cddc89d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} ใฏ WebSocket ๆŽฅ็ถšใ‚’็ขบ็ซ‹ใงใใพใ›ใ‚“ใงใ—ใŸใ€‚", "d9ce6c142a485959": "{host} ใฏ {seconds} ็ง’้–“ๅฟœ็ญ”ใ—ใฆใ„ใพใ›ใ‚“ใ€‚", "d6bdce8f4e6101a4": "{host} ใฎๆŽฅ็ถšใŒๅˆ‡ๆ–ญใ•ใ‚Œใพใ—ใŸใ€‚", + "8450a95e5214d199": "{host} ใ‹ใ‚‰ใ€ใ“ใฎใ‚ฏใƒฉใ‚คใ‚ขใƒณใƒˆใง่ชญใฟๅ–ใ‚Œใชใ„ใ‚ตใƒผใƒใƒผ่จญๅฎšใฎๆ›ดๆ–ฐใŒ้€ไฟกใ•ใ‚Œใพใ—ใŸใ€‚", + "56b4ff3993c93eca": "{host} ใ‹ใ‚‰ไบ’ๆ›ๆ€งใฎใชใ„ใ‚ตใƒผใƒใƒผ่จญๅฎšใŒ้€ไฟกใ•ใ‚Œใพใ—ใŸใ€‚", + "368c4d4f99c66bfb": "ใ‚ฏใƒฉใ‚คใ‚ขใƒณใƒˆใจใ‚ตใƒผใƒใƒผใ‚’ไบ’ๆ›ๆ€งใฎใ‚ใ‚‹ใƒใƒผใ‚ธใƒงใƒณใซๆ›ดๆ–ฐใ—ใฆใใ ใ•ใ„ใ€‚", "e5fd422e445391fc": "ใ‚ขใƒƒใƒ—ใƒญใƒผใƒ‰ใซๅคฑๆ•—ใ—ใพใ—ใŸใ€‚ใ‚ฟใƒƒใƒ—ใ—ใฆๅ†่ฉฆ่กŒใ—ใฆใใ ใ•ใ„ใ€‚", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 7768bd410d434..87195d1e59336 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host}์—์„œ WebSocket ์—ฐ๊ฒฐ์„ ์„ค์ •ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", "d9ce6c142a485959": "{host}์ด(๊ฐ€) {seconds}์ดˆ ๋™์•ˆ ์‘๋‹ตํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.", "d6bdce8f4e6101a4": "{host} ์—ฐ๊ฒฐ์ด ๋Š์–ด์กŒ์Šต๋‹ˆ๋‹ค.", + "8450a95e5214d199": "{host}์—์„œ ์ด ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ฝ์„ ์ˆ˜ ์—†๋Š” ์„œ๋ฒ„ ๊ตฌ์„ฑ ์—…๋ฐ์ดํŠธ๋ฅผ ๋ณด๋ƒˆ์Šต๋‹ˆ๋‹ค.", + "56b4ff3993c93eca": "{host}์—์„œ ํ˜ธํ™˜๋˜์ง€ ์•Š๋Š” ์„œ๋ฒ„ ๊ตฌ์„ฑ์„ ๋ณด๋ƒˆ์Šต๋‹ˆ๋‹ค.", + "368c4d4f99c66bfb": "ํด๋ผ์ด์–ธํŠธ์™€ ์„œ๋ฒ„๋ฅผ ํ˜ธํ™˜๋˜๋Š” ๋ฒ„์ „์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜์„ธ์š”.", "e5fd422e445391fc": "์—…๋กœ๋“œ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค. ํƒญํ•˜์—ฌ ๋‹ค์‹œ ์‹œ๋„ํ•˜์„ธ์š”.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 88dbb8da5cd87..fb5d60acdbd89 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} nรฃo conseguiu estabelecer uma conexรฃo WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualizaรงรฃo da configuraรงรฃo do servidor que este cliente nรฃo conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuraรงรฃo de servidor incompatรญvel.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versรตes compatรญveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 2d0fb55302031..b5beca32c6869 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} ะฝะต ัƒะดะฐะปะพััŒ ัƒัั‚ะฐะฝะพะฒะธั‚ัŒ WebSocket-ัะพะตะดะธะฝะตะฝะธะต.", "d9ce6c142a485959": "{host} ะฝะต ะพั‚ะฒะตั‡ะฐะตั‚ ัƒะถะต {seconds} ั.", "d6bdce8f4e6101a4": "{host} ะพั‚ะบะปัŽั‡ั‘ะฝ.", + "8450a95e5214d199": "{host} ะพั‚ะฟั€ะฐะฒะธะป ะพะฑะฝะพะฒะปะตะฝะธะต ะบะพะฝั„ะธะณัƒั€ะฐั†ะธะธ ัะตั€ะฒะตั€ะฐ, ะบะพั‚ะพั€ะพะต ัั‚ะพั‚ ะบะปะธะตะฝั‚ ะฝะต ัะผะพะณ ะฟั€ะพั‡ะธั‚ะฐั‚ัŒ.", + "56b4ff3993c93eca": "{host} ะพั‚ะฟั€ะฐะฒะธะป ะฝะตัะพะฒะผะตัั‚ะธะผัƒัŽ ะบะพะฝั„ะธะณัƒั€ะฐั†ะธัŽ ัะตั€ะฒะตั€ะฐ.", + "368c4d4f99c66bfb": "ะžะฑะฝะพะฒะธั‚ะต ะบะปะธะตะฝั‚ ะธ ัะตั€ะฒะตั€ ะดะพ ัะพะฒะผะตัั‚ะธะผั‹ั… ะฒะตั€ัะธะน.", "e5fd422e445391fc": "ะžัˆะธะฑะบะฐ ะทะฐะณั€ัƒะทะบะธ. ะะฐะถะผะธั‚ะต, ั‡ั‚ะพะฑั‹ ะฟะพะฒั‚ะพั€ะธั‚ัŒ.", "b2bc6bd92ea24e5c": "{size} ะœะ‘", "88f84178edbb7f57": "{size} ะšะ‘", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 70617afd183ca..28ed7e557146a 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprรคtta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades frรฅn.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den hรคr klienten inte kunde lรคsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck fรถr att fรถrsรถka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 485d4206bf054..52857eda6cc8a 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} ๆ— ๆณ•ๅปบ็ซ‹ WebSocket ่ฟžๆŽฅใ€‚", "d9ce6c142a485959": "{host} ๅทฒ {seconds} ็ง’ๆ— ๅ“ๅบ”ใ€‚", "d6bdce8f4e6101a4": "{host} ๅทฒๆ–ญๅผ€่ฟžๆŽฅใ€‚", + "8450a95e5214d199": "{host} ๅ‘้€ไบ†ๆญคๅฎขๆˆท็ซฏๆ— ๆณ•่ฏปๅ–็š„ๆœๅŠกๅ™จ้…็ฝฎๆ›ดๆ–ฐใ€‚", + "56b4ff3993c93eca": "{host} ๅ‘้€ไบ†ไธๅ…ผๅฎน็š„ๆœๅŠกๅ™จ้…็ฝฎใ€‚", + "368c4d4f99c66bfb": "่ฏทๅฐ†ๅฎขๆˆท็ซฏๅ’ŒๆœๅŠกๅ™จๆ›ดๆ–ฐๅˆฐๅ…ผๅฎน็š„็‰ˆๆœฌใ€‚", "e5fd422e445391fc": "ไธŠไผ ๅคฑ่ดฅใ€‚็‚นๆŒ‰ไปฅ้‡่ฏ•ใ€‚", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 3a71e92063446..0db2fb8989ce2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 65ed2a4db1b89..3aa61a18f6b2b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index dae05eda74dd9..60ddca69b570f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexiรณn WebSocket.", "d9ce6c142a485959": "{host} dejรณ de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectรณ.", + "8450a95e5214d199": "{host} enviรณ una actualizaciรณn de la configuraciรณn del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} enviรณ una configuraciรณn del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 6054810c0c23d..fdcba31a1032f 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} nโ€™a pas pu รฉtablir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne rรฉpond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est dรฉconnectรฉ.", + "8450a95e5214d199": "{host} a envoyรฉ une mise ร  jour de la configuration du serveur que ce client nโ€™a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyรฉ une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez ร  jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "ร‰chec de lโ€™envoi. Touchez pour rรฉessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 188d63866545c..13379225ecf26 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} ใฏ WebSocket ๆŽฅ็ถšใ‚’็ขบ็ซ‹ใงใใพใ›ใ‚“ใงใ—ใŸใ€‚", "d9ce6c142a485959": "{host} ใฏ {seconds} ็ง’้–“ๅฟœ็ญ”ใ—ใฆใ„ใพใ›ใ‚“ใ€‚", "d6bdce8f4e6101a4": "{host} ใฎๆŽฅ็ถšใŒๅˆ‡ๆ–ญใ•ใ‚Œใพใ—ใŸใ€‚", + "8450a95e5214d199": "{host} ใ‹ใ‚‰ใ€ใ“ใฎใ‚ฏใƒฉใ‚คใ‚ขใƒณใƒˆใง่ชญใฟๅ–ใ‚Œใชใ„ใ‚ตใƒผใƒใƒผ่จญๅฎšใฎๆ›ดๆ–ฐใŒ้€ไฟกใ•ใ‚Œใพใ—ใŸใ€‚", + "56b4ff3993c93eca": "{host} ใ‹ใ‚‰ไบ’ๆ›ๆ€งใฎใชใ„ใ‚ตใƒผใƒใƒผ่จญๅฎšใŒ้€ไฟกใ•ใ‚Œใพใ—ใŸใ€‚", + "368c4d4f99c66bfb": "ใ‚ฏใƒฉใ‚คใ‚ขใƒณใƒˆใจใ‚ตใƒผใƒใƒผใ‚’ไบ’ๆ›ๆ€งใฎใ‚ใ‚‹ใƒใƒผใ‚ธใƒงใƒณใซๆ›ดๆ–ฐใ—ใฆใใ ใ•ใ„ใ€‚", "e5fd422e445391fc": "ใ‚ขใƒƒใƒ—ใƒญใƒผใƒ‰ใซๅคฑๆ•—ใ—ใพใ—ใŸใ€‚ใ‚ฟใƒƒใƒ—ใ—ใฆๅ†่ฉฆ่กŒใ—ใฆใใ ใ•ใ„ใ€‚", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fd4f1a5af2fc8..cc8261d7681ff 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host}์—์„œ WebSocket ์—ฐ๊ฒฐ์„ ์„ค์ •ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", "d9ce6c142a485959": "{host}์ด(๊ฐ€) {seconds}์ดˆ ๋™์•ˆ ์‘๋‹ตํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.", "d6bdce8f4e6101a4": "{host} ์—ฐ๊ฒฐ์ด ๋Š์–ด์กŒ์Šต๋‹ˆ๋‹ค.", + "8450a95e5214d199": "{host}์—์„œ ์ด ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ฝ์„ ์ˆ˜ ์—†๋Š” ์„œ๋ฒ„ ๊ตฌ์„ฑ ์—…๋ฐ์ดํŠธ๋ฅผ ๋ณด๋ƒˆ์Šต๋‹ˆ๋‹ค.", + "56b4ff3993c93eca": "{host}์—์„œ ํ˜ธํ™˜๋˜์ง€ ์•Š๋Š” ์„œ๋ฒ„ ๊ตฌ์„ฑ์„ ๋ณด๋ƒˆ์Šต๋‹ˆ๋‹ค.", + "368c4d4f99c66bfb": "ํด๋ผ์ด์–ธํŠธ์™€ ์„œ๋ฒ„๋ฅผ ํ˜ธํ™˜๋˜๋Š” ๋ฒ„์ „์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜์„ธ์š”.", "e5fd422e445391fc": "์—…๋กœ๋“œ์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค. ํƒญํ•˜์—ฌ ๋‹ค์‹œ ์‹œ๋„ํ•˜์„ธ์š”.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f8450e8032e5f..a9ce3832a0b9f 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} nรฃo conseguiu estabelecer uma conexรฃo WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualizaรงรฃo da configuraรงรฃo do servidor que este cliente nรฃo conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuraรงรฃo de servidor incompatรญvel.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versรตes compatรญveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 75b7db757cf04..ee0fe30aa4f39 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} ะฝะต ัƒะดะฐะปะพััŒ ัƒัั‚ะฐะฝะพะฒะธั‚ัŒ WebSocket-ัะพะตะดะธะฝะตะฝะธะต.", "d9ce6c142a485959": "{host} ะฝะต ะพั‚ะฒะตั‡ะฐะตั‚ ัƒะถะต {seconds} ั.", "d6bdce8f4e6101a4": "{host} ะพั‚ะบะปัŽั‡ั‘ะฝ.", + "8450a95e5214d199": "{host} ะพั‚ะฟั€ะฐะฒะธะป ะพะฑะฝะพะฒะปะตะฝะธะต ะบะพะฝั„ะธะณัƒั€ะฐั†ะธะธ ัะตั€ะฒะตั€ะฐ, ะบะพั‚ะพั€ะพะต ัั‚ะพั‚ ะบะปะธะตะฝั‚ ะฝะต ัะผะพะณ ะฟั€ะพั‡ะธั‚ะฐั‚ัŒ.", + "56b4ff3993c93eca": "{host} ะพั‚ะฟั€ะฐะฒะธะป ะฝะตัะพะฒะผะตัั‚ะธะผัƒัŽ ะบะพะฝั„ะธะณัƒั€ะฐั†ะธัŽ ัะตั€ะฒะตั€ะฐ.", + "368c4d4f99c66bfb": "ะžะฑะฝะพะฒะธั‚ะต ะบะปะธะตะฝั‚ ะธ ัะตั€ะฒะตั€ ะดะพ ัะพะฒะผะตัั‚ะธะผั‹ั… ะฒะตั€ัะธะน.", "e5fd422e445391fc": "ะžัˆะธะฑะบะฐ ะทะฐะณั€ัƒะทะบะธ. ะะฐะถะผะธั‚ะต, ั‡ั‚ะพะฑั‹ ะฟะพะฒั‚ะพั€ะธั‚ัŒ.", "b2bc6bd92ea24e5c": "{size} ะœะ‘", "88f84178edbb7f57": "{size} ะšะ‘", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6a3525acc8636..fb02753220b14 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprรคtta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades frรฅn.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den hรคr klienten inte kunde lรคsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck fรถr att fรถrsรถka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index af1ca50a064b3..04044302284b7 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} ๆ— ๆณ•ๅปบ็ซ‹ WebSocket ่ฟžๆŽฅใ€‚", "d9ce6c142a485959": "{host} ๅทฒ {seconds} ็ง’ๆ— ๅ“ๅบ”ใ€‚", "d6bdce8f4e6101a4": "{host} ๅทฒๆ–ญๅผ€่ฟžๆŽฅใ€‚", + "8450a95e5214d199": "{host} ๅ‘้€ไบ†ๆญคๅฎขๆˆท็ซฏๆ— ๆณ•่ฏปๅ–็š„ๆœๅŠกๅ™จ้…็ฝฎๆ›ดๆ–ฐใ€‚", + "56b4ff3993c93eca": "{host} ๅ‘้€ไบ†ไธๅ…ผๅฎน็š„ๆœๅŠกๅ™จ้…็ฝฎใ€‚", + "368c4d4f99c66bfb": "่ฏทๅฐ†ๅฎขๆˆท็ซฏๅ’ŒๆœๅŠกๅ™จๆ›ดๆ–ฐๅˆฐๅ…ผๅฎน็š„็‰ˆๆœฌใ€‚", "e5fd422e445391fc": "ไธŠไผ ๅคฑ่ดฅใ€‚็‚นๆŒ‰ไปฅ้‡่ฏ•ใ€‚", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 5882638af0c0c..ebd4780ba5064 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -291,6 +291,59 @@ const publishConfigEvents = Effect.fn("TestRpcSessionFactory.publishConfigEvents }); describe("RpcSessionFactory", () => { + it.effect.each([ + { established: false, closedWith: { _tag: "ConnectionBlockedError", reason: "unsupported" } }, + { + established: true, + closedWith: { _tag: "ConnectionTransientError", reason: "remote-unavailable" }, + }, + ])( + "ends the session when config fails to decode, after readiness=$established", + ({ established, closedWith }) => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* session.ready.pipe(Effect.exit, Effect.forkChild); + const socket = yield* awaitSocket(sockets); + socket.open(); + if (established) { + yield* completeInitialConfig(socket); + yield* Fiber.join(ready); + yield* completeInitialConfig(socket, { ...ENCODED_SERVER_CONFIG, cwd: 42 }); + } else { + yield* completeInitialConfig(socket, { ...ENCODED_SERVER_CONFIG, cwd: 42 }); + expect(yield* Fiber.join(ready)).toMatchObject({ + _tag: "Failure", + cause: { reasons: [{ _tag: "Fail", error: { reason: "unsupported" } }] }, + }); + } + + expect(yield* Effect.flip(session.closed)).toMatchObject({ ...closedWith, hop: "server" }); + }).pipe(Effect.scoped), + ); + + it.effect( + "fails readiness with the disconnect when the socket closes before its first config", + () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* Effect.forkChild(Effect.flip(session.ready)); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* awaitRequest(socket); + socket.close(1012, "service restart"); + + for (const error of [yield* Fiber.join(ready), yield* Effect.flip(session.closed)]) { + expect(error).toMatchObject({ + _tag: "ConnectionTransientError", + reason: "transport", + detail: "Test environment disconnected.", + }); + } + }).pipe(Effect.scoped), + ); + it.effect("connects while a large config snapshot downloads at 4000 bytes per second", () => Effect.gen(function* () { const { factory, sockets } = yield* makeFactory(); @@ -822,6 +875,33 @@ describe("RpcSessionFactory", () => { }), ); + it.effect("closes the session when the server interrupts the config stream", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + + const closedFiber = yield* Effect.forkChild(Effect.flip(session.closed)); + const request = yield* awaitRequest(socket); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: request.id, + exit: { _tag: "Failure", cause: [{ _tag: "Interrupt", fiberId: null }] }, + }), + ); + + expect(yield* Fiber.join(closedFiber)).toMatchObject({ + reason: "remote-unavailable", + detail: "Test environment config subscription ended.", + }); + }), + ); + it.effect.each([{ failure: "defect" as const }, { failure: "typed" as const }])( "keeps durable config state alive after an owned $failure failure", ({ failure }) => diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 409169ff1e345..91160a60941db 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -139,11 +139,14 @@ const isSocketErrorReason = Schema.is(Socket.SocketErrorReason); const PING_TIMEOUT_SECONDS = Duration.toSeconds(PING_TIMEOUT); function mapSessionRpcError( - error: InitialConfigError | ProbeError | ServerConfigSubscriptionError, - networkHint: string, + error: InitialConfigError | ProbeError | ServerConfigSubscriptionError | ConnectionAttemptError, via: "relay" | "direct", + socketFailure: () => ConnectionTransientError, ): ConnectionAttemptError { switch (error._tag) { + case "ConnectionBlockedError": + case "ConnectionTransientError": + return error; case "EnvironmentAuthorizationError": return new ConnectionBlockedError({ reason: "permission", @@ -160,11 +163,13 @@ function mapSessionRpcError( via, }); case "RpcClientError": - return new ConnectionTransientErrorClass({ - reason: "transport", - detail: `${error.message}${isSocketErrorReason(error.reason) ? networkHint : ""}`, - ...socketFailureLocation(via), - }); + return isSocketErrorReason(error.reason) + ? socketFailure() + : new ConnectionTransientErrorClass({ + reason: "transport", + detail: error.message, + ...socketFailureLocation(via), + }); } } @@ -194,47 +199,42 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( const connect = Effect.fnUntraced(function* (connection: PreparedConnection) { const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct"; - const networkHint = via === "relay" ? ` ${NETWORK_BLOCKING_HINT}` : ""; - const mapRpcError = (error: Parameters[0]) => - mapSessionRpcError(error, networkHint, via); yield* Effect.annotateCurrentSpan({ "connection.environment.id": connection.environmentId, }); const connected = yield* Deferred.make(); const disconnected = yield* Deferred.make(); - const pingTimedOut = yield* Ref.make(false); + let pingTimedOut = false; + const socketFailure = () => + new ConnectionTransientErrorClass({ + reason: "transport", + // The network hint only fits a socket that never opened. Once it + // opened, the path worked, and a host that goes quiet is more + // often overloaded or asleep than blocked. + ...(!Deferred.isDoneUnsafe(connected) + ? translatableDetail( + msg("{host} could not establish a WebSocket connection.", { + host: connection.label, + }), + ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []), + ) + : pingTimedOut + ? translatableDetail( + msg("{host} stopped responding for {seconds}s.", { + host: connection.label, + seconds: String(PING_TIMEOUT_SECONDS), + }), + UNRESPONSIVE_HOST_HINT, + ) + : translatableDetail(msg("{host} disconnected.", { host: connection.label }))), + ...socketFailureLocation(via), + }); + const mapRpcError = (error: Parameters[0]) => + mapSessionRpcError(error, via, socketFailure); const hooks = RpcClient.ConnectionHooks.of({ onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid), - onDisconnect: Effect.all([Deferred.isDone(connected), Ref.get(pingTimedOut)]).pipe( - Effect.flatMap(([wasConnected, timedOut]) => - Deferred.fail( - disconnected, - new ConnectionTransientErrorClass({ - reason: "transport", - // The network hint only fits a socket that never opened. Once it - // opened, the path worked, and a host that goes quiet is more - // often overloaded or asleep than blocked. - ...(!wasConnected - ? translatableDetail( - msg("{host} could not establish a WebSocket connection.", { - host: connection.label, - }), - ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []), - ) - : timedOut - ? translatableDetail( - msg("{host} stopped responding for {seconds}s.", { - host: connection.label, - seconds: String(PING_TIMEOUT_SECONDS), - }), - UNRESPONSIVE_HOST_HINT, - ) - : translatableDetail(msg("{host} disconnected.", { host: connection.label }))), - ...socketFailureLocation(via), - }), - ), - ), + onDisconnect: Effect.suspend(() => Deferred.fail(disconnected, socketFailure())).pipe( Effect.asVoid, ), }); @@ -267,7 +267,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( pingTimeout: PING_TIMEOUT, retryTransientErrors: false, retryPolicy: Schedule.recurs(0), - onPingTimeout: Ref.set(pingTimedOut, true), + // RpcClient runs this before it fails the open requests. + onPingTimeout: Effect.sync(() => { + pingTimedOut = true; + }), }).pipe( // Teardown sends an interrupt per open stream, and a write to a closed // socket waits out the client's 1s interrupt timeout before reconnecting. @@ -302,7 +305,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ); const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); const initialConfigDeferred = yield* Deferred.make(); - const serverConfigExit = yield* Deferred.make(); + const serverConfigExit = yield* Deferred.make< + void, + ServerConfigSubscriptionError | ConnectionAttemptError + >(); const configSubscriptionClosed = yield* Deferred.make(); const serverConfigState = yield* Ref.make(Option.none()); const serverConfigUpdates = yield* PubSub.sliding(64); @@ -310,6 +316,8 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( reason: "remote-unavailable", detail: `${connection.label} config subscription ended.`, }); + // An interrupt while the session is not closing came from the server; it ends the subscription. + let closingSession = false; const configRequestedAtMs = yield* Clock.currentTimeMillis; const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig]( onDemandSnapshots(serverConfigInput), @@ -362,8 +370,46 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( } }), ), + // An unreadable first snapshot means the versions are incompatible. A later + // unreadable update ends the session, and the reconnect's snapshot decides. + Effect.catchDefect((defect) => + Schema.isSchemaError(defect) + ? Effect.logWarning("Server configuration failed to decode.", { + environmentId: connection.environmentId, + issue: defect.message, + }).pipe( + Effect.andThen( + Effect.fail( + Deferred.isDoneUnsafe(initialConfigDeferred) + ? new ConnectionTransientErrorClass({ + reason: "remote-unavailable", + ...translatableDetail( + msg( + "{host} sent a server configuration update this client could not read.", + { host: connection.label }, + ), + ), + hop: "server", + via, + }) + : new ConnectionBlockedError({ + reason: "unsupported", + ...translatableDetail( + msg("{host} sent an incompatible server configuration.", { + host: connection.label, + }), + msg("Update the client and server to compatible versions."), + ), + hop: "server", + via, + }), + ), + ), + ) + : Effect.die(defect), + ), Effect.onExit((exit) => { - if (Exit.isSuccess(exit)) { + if (Exit.isSuccess(exit) || (Cause.hasInterruptsOnly(exit.cause) && !closingSession)) { return Effect.all([ Deferred.succeed(serverConfigExit, undefined), Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError), @@ -379,6 +425,12 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( }), ); yield* serverConfigSource.pipe(Effect.forkScoped); + // Finalizers run in reverse, so this is set before the fork above is interrupted. + yield* Effect.addFinalizer(() => + Effect.sync(() => { + closingSession = true; + }), + ); const initialConfig = Effect.raceFirst( Deferred.await(initialConfigDeferred), Deferred.await(serverConfigExit).pipe( @@ -424,7 +476,9 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ).pipe( Stream.catchCause((cause) => { if (Cause.hasInterruptsOnly(cause)) { - return Stream.failCause(cause); + return Stream.failCause( + Cause.fromReasons(cause.reasons.filter(Cause.isInterruptReason)), + ); } // The supervisor keeps the original cause. Shared durable consumers // need a transport-shaped failure so they wait for its replacement. @@ -471,17 +525,11 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( client: protocolClient, initialConfig, subscribeServerConfig, - ready: Deferred.await(connected).pipe( - Effect.andThen(initialConfig), - Effect.asVoid, - Effect.raceFirst(Deferred.await(disconnected)), - ), + ready: initialConfig.pipe(Effect.asVoid), probe, inboundFrames: Effect.sync(() => inboundFrames), - closed: Effect.raceFirst( - Deferred.await(disconnected), - Deferred.await(configSubscriptionClosed), - ), + // The config stream also fails on disconnect, and only it can report a decode failure. + closed: Deferred.await(configSubscriptionClosed), } satisfies RpcSession; }); From 620cf4770d992d642f822a13dc2539c2605a3500 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:38:38 -0800 Subject: [PATCH 65/96] fix(web): browser page translation no longer crashes the app when a turn updates (#40856) --- apps/web/src/appInit.tsx | 2 + .../lib/pageTranslationGuard.browser.test.tsx | 42 +++++++++++++++++++ apps/web/src/lib/pageTranslationGuard.ts | 20 +++++++++ 3 files changed, 64 insertions(+) create mode 100644 apps/web/src/lib/pageTranslationGuard.browser.test.tsx create mode 100644 apps/web/src/lib/pageTranslationGuard.ts diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index ae8e685c5c9ec..cce59f08f6d12 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -62,6 +62,7 @@ import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; import { m } from "./i18n/messages"; import { startI18n, subscribeI18n } from "./i18n/runtime"; +import { guardDomAgainstPageTranslation } from "./lib/pageTranslationGuard"; import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands"; import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut"; import { environmentThreadShells, threadEnvironment } from "./state/threads"; @@ -267,6 +268,7 @@ export function startAppServices(): AppRouter { } installDesktopPasteAsText(window.desktopBridge, window); + guardDomAgainstPageTranslation(); startClientAppearance(); startI18n(); diff --git a/apps/web/src/lib/pageTranslationGuard.browser.test.tsx b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx new file mode 100644 index 0000000000000..40d7e7597ccf8 --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { guardDomAgainstPageTranslation } from "./pageTranslationGuard"; + +// What Chrome's page translator does: swap each text node for translation. +function translatePage(root: Element) { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const textNodes: Text[] = []; + while (walker.nextNode()) textNodes.push(walker.currentNode as Text); + for (const text of textNodes) { + if (!text.nodeValue?.trim()) continue; + const outer = document.createElement("font"); + const inner = document.createElement("font"); + inner.textContent = `่ฏ‘:${text.nodeValue}`; + outer.append(inner); + text.replaceWith(outer); + } +} + +function Status({ running }: { running: boolean }) { + return ( +
+ {running ? "Working" : } + {"for 2s"} +
+ ); +} + +describe("guardDomAgainstPageTranslation", () => { + it("keeps React committing after page translation replaced its text nodes", async () => { + guardDomAgainstPageTranslation(); + await using screen = await render(, { router: false }); + translatePage(screen.container); + + // Removing "Working" hits removeChild; placing the icon before "for 2s" hits insertBefore. + await screen.rerender(); + await expect.element(screen.getByTestId("done")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByTestId("done")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/lib/pageTranslationGuard.ts b/apps/web/src/lib/pageTranslationGuard.ts new file mode 100644 index 0000000000000..de8dbceb8e2bf --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.ts @@ -0,0 +1,20 @@ +// Browser page translation (Chrome, Edge) swaps text nodes for wrappers React does not +// know about, so a later removeChild or insertBefore on the original node throws NotFoundError +// and takes down the whole tree. See facebook/react#11538. +export function guardDomAgainstPageTranslation(): void { + const proto = Node.prototype; + const removeChild = proto.removeChild; + const insertBefore = proto.insertBefore; + + proto.removeChild = function (this: Node, child: T): T { + // Already detached by the translator: nothing left to remove. + if (child.parentNode !== this) return child; + return removeChild.call(this, child) as T; + }; + + proto.insertBefore = function (this: Node, node: T, reference: Node | null): T { + // The anchor was replaced; append so the new node still shows. + const anchor = reference && reference.parentNode !== this ? null : reference; + return insertBefore.call(this, node, anchor) as T; + }; +} From 30372d0fade8903b4cd6c544768333fc7588fd37 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 22 Nov 2026 06:13:03 -0800 Subject: [PATCH 66/96] perf(mobile): keep image bytes outside draft JSON (#9727) Co-authored-by: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../review/ReviewCommentComposerSheet.tsx | 70 +++++++--- .../sharing/incoming-share-model.test.ts | 118 ++++++++++++++++- .../features/sharing/incoming-share-model.ts | 55 +++++--- apps/mobile/src/lib/composerFiles.test.ts | 81 +++++++----- apps/mobile/src/lib/composerImages.test.ts | 24 ++-- apps/mobile/src/lib/composerImages.ts | 122 +++++++++++------- apps/mobile/src/state/thread-outbox-model.ts | 6 +- .../src/state/use-composer-drafts.test.ts | 22 +++- apps/mobile/src/state/use-composer-drafts.ts | 4 +- 9 files changed, 368 insertions(+), 134 deletions(-) diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index db2e7169d4930..881f67e86648f 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -2,7 +2,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native" import { TextInputWrapper } from "expo-paste-input"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { T, useGT } from "gt-react-native"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { ScrollView, View, useWindowDimensions } from "react-native"; import * as Dialog from "../../components/ui/Dialog"; import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal"; @@ -16,6 +16,7 @@ import { cn } from "../../lib/cn"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages"; import { useNativePaste } from "../../lib/useNativePaste"; +import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts"; import { setPendingConnectionError } from "../../state/use-remote-environment-registry"; import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state"; import { @@ -49,6 +50,31 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp const { environmentId, threadId } = props.route.params; const [commentText, setCommentText] = useState(""); const [attachments, setAttachments] = useState>([]); + const attachmentsRef = useRef(attachments); + const isMountedRef = useRef(true); + // Store file references before React commits, so closing the sheet can release them. + const replaceAttachments = (next: ReadonlyArray) => { + attachmentsRef.current = next; + setAttachments(next); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases owned image files when the sheet unmounts + useEffect(() => { + isMountedRef.current = true; + return () => { + isMountedRef.current = false; + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + }; + }, []); + + function appendImages(images: ReadonlyArray): void { + if (!isMountedRef.current) { + scheduleUnusedComposerAttachmentCleanup(images); + return; + } + if (images.length > 0) { + replaceAttachments([...attachmentsRef.current, ...images]); + } + } const [previewFile, setPreviewFile] = useState(null); const { selectedLines, highlightedLinesById } = useMemo(() => { @@ -90,27 +116,25 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp }; const handleNativePaste = useNativePaste((uris) => { void (async () => { - try { - const result = await convertPastedImagesToAttachments({ - uris, - existingCount: attachments.length, - }); - if (result.attachments.length > 0) { - setAttachments((current) => [...current, ...result.attachments]); - } - if (result.error) Dialog.alert(gt("Could not paste image"), result.error); - } catch (error) { + const result = await convertPastedImagesToAttachments({ + uris, + existingCount: attachmentsRef.current.length, + }).catch((error: unknown) => { console.error("[review comment] error converting pasted images", error); + return null; + }); + if (result === null) return; + appendImages(result.attachments); + if (result.error && isMountedRef.current) { + Dialog.alert(gt("Could not paste image"), result.error); } })(); }); async function handlePickImages(): Promise { - const result = await pickComposerImages({ existingCount: attachments.length }); - if (result.images.length > 0) { - setAttachments((current) => [...current, ...result.images]); - } - if (result.error) { + const result = await pickComposerImages({ existingCount: attachmentsRef.current.length }); + appendImages(result.images); + if (result.error && isMountedRef.current) { setPendingConnectionError(result.error); } } @@ -124,9 +148,10 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp environmentId, threadId, text: formatReviewCommentContext(target, commentText), - attachments, + attachments: attachmentsRef.current, }); - setAttachments([]); + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + replaceAttachments([]); dismissComposer(); }; @@ -255,9 +280,12 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp onPressPreview={setPreviewFile} removeButtonPlacement="gutter" onRemove={(imageId) => { - setAttachments((current) => - current.filter((image) => image.id !== imageId), - ); + const current = attachmentsRef.current; + const removed = current.find((image) => image.id === imageId); + replaceAttachments(current.filter((image) => image.id !== imageId)); + if (removed) { + scheduleUnusedComposerAttachmentCleanup([removed]); + } }} /> diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 1dea547de53b4..7ca92b23c3208 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "@effect/vitest"; +import { describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, @@ -13,6 +13,32 @@ import { selectIncomingShareAttachmentsForServer, } from "./incoming-share-model"; +const nativeImage = vi.hoisted(() => ({ + resize: vi.fn(), +})); + +vi.mock("expo-image-manipulator", () => ({ + SaveFormat: { PNG: "png", JPEG: "jpeg" }, + ImageManipulator: { + manipulate: (source: string | { width: number; height: number }) => { + let size = typeof source === "string" ? { width: 3000, height: 1500 } : source; + const context = { + resize: (next: { width: number; height: number }) => { + nativeImage.resize(next); + size = next; + return context; + }, + renderAsync: async () => ({ + ...size, + release: () => {}, + saveAsync: async () => ({ uri: "file:///cache/resized.png", base64: "YWJj" }), + }), + }; + return context; + }, + }, +})); + describe("incoming native shares", () => { it("converts shared text, URLs, and images into a durable composer draft", async () => { const image: SharePayload = { @@ -35,6 +61,9 @@ describe("incoming native shares", () => { originalName: "Screenshot.png", }; const removeOwnedFile = vi.fn(() => Promise.resolve()); + const readBase64 = vi.fn(async () => "YWJj"); + const persistedUri = "file:///documents/t3-composer-attachments/Screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); const result = await buildIncomingShareDraft({ id: "share-1", @@ -42,7 +71,9 @@ describe("incoming native shares", () => { payloads, resolvedPayloads: [resolvedImage], fileReader: { - readBase64: async () => "YWJj", + readBase64, + persistFile, + readSize: async (uri) => (uri === persistedUri ? 3 : null), removeOwnedFile, }, }); @@ -59,16 +90,95 @@ describe("incoming native shares", () => { name: "Screenshot.png", mimeType: "image/png", sizeBytes: 3, - dataUrl: "data:image/png;base64,YWJj", - previewUri: "data:image/png;base64,YWJj", + fileUri: persistedUri, + previewUri: persistedUri, }, ], warnings: [], }); expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); expect(hasIncomingShareContent(result)).toBe(true); }); + it("persists the resized PNG for a shared image over 2000px", async () => { + const header = Buffer.alloc(24); + header.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + header.set([0x49, 0x48, 0x44, 0x52], 12); + header.writeUInt32BE(3000, 16); + header.writeUInt32BE(1500, 20); + const persistedUri = "file:///documents/t3-composer-attachments/screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + + const draft = await buildIncomingShareDraft({ + id: "share-resize", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [ + { shareType: "image", value: "content://shared/screenshot", mimeType: "image/png" }, + ], + resolvedPayloads: [], + fileReader: { + readBase64: async () => header.toString("base64"), + persistFile, + readSize: async () => 3, + removeOwnedFile, + }, + }); + + expect(nativeImage.resize).toHaveBeenCalledWith({ width: 2000, height: 1000 }); + expect(persistFile).toHaveBeenCalledWith("file:///cache/resized.png", "screenshot"); + expect(draft.attachments).toEqual([ + { + id: "share-resize-image-0", + type: "image", + name: "screenshot", + mimeType: "image/png", + sizeBytes: 3, + fileUri: persistedUri, + previewUri: persistedUri, + }, + ]); + expect(draft.warnings).toEqual([]); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); + }); + + it("releases a shared image when its stored size cannot be measured", async () => { + const image: SharePayload = { + shareType: "image", + value: "file:///shared/photo.png", + mimeType: "image/png", + }; + const persistedUri = "file:///documents/t3-composer-attachments/photo.png"; + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + const result = await buildIncomingShareDraft({ + id: "share-unmeasured", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [image], + resolvedPayloads: [ + { + ...image, + contentUri: image.value, + contentType: "image", + contentMimeType: "image/png", + contentSize: 3, + originalName: "photo.png", + }, + ], + fileReader: { + readBase64: async () => "unused", + persistFile: async () => persistedUri, + readSize: async () => null, + removeOwnedFile, + }, + }); + + expect(result.attachments).toEqual([]); + expect(result.warnings).toEqual(["'photo.png' is empty or could not be read."]); + expect(removeOwnedFile).toHaveBeenCalledWith(persistedUri); + expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + }); + it("skips oversized images and releases the temporary native file", async () => { const image: SharePayload = { shareType: "image", diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 9bfc2dcca1b29..86c17c6059e0e 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -412,6 +412,9 @@ export async function buildIncomingShareDraft(input: { continue; } + const name = resolved?.originalName ?? fallbackName(uri, index, mimeType); + let persistedImageUri: string | undefined; + let retainedImageUri: string | undefined; try { const sharedBase64 = await input.fileReader.readBase64(uri); // Use already-read bytes because native image loaders may not read the provider's file. @@ -421,36 +424,54 @@ export async function buildIncomingShareDraft(input: { base64: sharedBase64, }); const base64 = fitted?.base64 ?? sharedBase64; - const sizeBytes = fitted - ? estimateBase64ByteSize(base64) - : (resolved?.contentSize ?? estimateBase64ByteSize(base64)); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - warnings.push( - m( - msg("''{name}'' exceeds the 10 MB attachment limit.", { - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), - }), - ), - ); + const decodedSize = estimateBase64ByteSize(base64); + if (decodedSize <= 0 || decodedSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + continue; + } + if (input.fileReader.persistFile) { + persistedImageUri = await input.fileReader.persistFile(fitted?.uri ?? uri, name); + const sizeBytes = (await input.fileReader.readSize?.(persistedImageUri)) ?? null; + if (sizeBytes === null || sizeBytes <= 0) { + warnings.push(m(msg("''{name}'' is empty or could not be read.", { name }))); + continue; + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m)); + continue; + } + attachments.push({ + id: `${input.id}-image-${index}`, + type: "image", + name, + mimeType, + sizeBytes, + fileUri: persistedImageUri, + previewUri: persistedImageUri, + }); + retainedImageUri = persistedImageUri; continue; } const dataUrl = `data:${mimeType};base64,${base64}`; attachments.push({ id: `${input.id}-image-${index}`, type: "image", - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), + name, mimeType, - sizeBytes, + sizeBytes: decodedSize, dataUrl, // Data-backed previews outlive temporary share files and App Group entries. previewUri: dataUrl, }); } catch { - warnings.push( - m(msg("Could not read ''{name}''.", { name: fallbackName(uri, index, mimeType) })), - ); + warnings.push(m(msg("Could not read ''{name}''.", { name }))); } finally { - await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + await releaseOwnedFiles( + input.fileReader, + [uri, payload.value, persistedImageUri].filter( + (candidate) => candidate !== retainedImageUri, + ), + ); } } diff --git a/apps/mobile/src/lib/composerFiles.test.ts b/apps/mobile/src/lib/composerFiles.test.ts index bdcd35c36ff75..73f0af20fcc00 100644 --- a/apps/mobile/src/lib/composerFiles.test.ts +++ b/apps/mobile/src/lib/composerFiles.test.ts @@ -2,6 +2,9 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts"; import type { ImagePickerAsset } from "expo-image-picker"; +// Bytes of image files the tests create, so stored attachments can be read back and measured. +const imageFiles = new Map(); + const mocks = vi.hoisted(() => ({ documentUri: "file:///documents", pickFile: vi.fn(), @@ -57,6 +60,8 @@ vi.mock("expo-file-system", () => { async copy(destination: File): Promise { mocks.copy(this.uri, destination.uri); + const bytes = imageFiles.get(this.uri); + if (bytes !== undefined) imageFiles.set(destination.uri, bytes); } async base64(): Promise { @@ -99,6 +104,16 @@ import { import { isForegroundHandoffActive } from "./foreground-handoff"; import { retainComposerAttachmentFile } from "./composerAttachmentFiles"; +const STORED = "file:///documents/t3-composer-attachments/attachment-id"; + +function sizeOtherFilesAs(bytes: number): void { + mocks.size.mockImplementation((uri: string) => { + if (uri.startsWith("content:")) return null; + const stored = imageFiles.get(uri); + return stored === undefined ? bytes : Buffer.from(stored, "base64").byteLength; + }); +} + describe("composer file attachments", () => { beforeEach(() => { mocks.documentUri = "file:///documents"; @@ -110,7 +125,8 @@ describe("composer file attachments", () => { mocks.size.mockReset(); mocks.readBase64.mockReset(); mocks.manipulate.mockReset(); - mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42)); + imageFiles.clear(); + sizeOtherFilesAs(42); }); describe("photo library image conversion", () => { @@ -151,8 +167,11 @@ describe("composer file attachments", () => { width: size.width, height: size.height, release: mocks.release, - saveAsync: async (options: { format: string }) => - native.encode?.(size, options.format) ?? native.saved, + saveAsync: async (options: { format: string }) => { + const saved = native.encode?.(size, options.format) ?? native.saved; + if (saved.base64 !== undefined) imageFiles.set(saved.uri, saved.base64); + return saved; + }, }), }; return context; @@ -160,7 +179,7 @@ describe("composer file attachments", () => { }); it.each(["image/heic", "image/heif", undefined])( - "renders a %s photo to JPEG natively and previews the rendered file", + "renders a %s photo to JPEG natively and stores it in an owned file", async (mimeType) => { mocks.pickMedia.mockResolvedValue({ canceled: false, @@ -180,8 +199,8 @@ describe("composer file attachments", () => { name: "photo.jpg", mimeType: "image/jpeg", sizeBytes: 4, - dataUrl: `data:image/jpeg;base64,${rendered.base64}`, - previewUri: rendered.uri, + fileUri: `${STORED}-photo.jpg`, + previewUri: `${STORED}-photo.jpg`, }, ], error: null, @@ -200,6 +219,7 @@ describe("composer file attachments", () => { assets: [{ ...photo, fileName: name, mimeType: original.mimeType }], }); mocks.readBase64.mockResolvedValue(original.base64); + imageFiles.set(photo.uri, original.base64); const result = await pickComposerImages({ existingCount: 0 }); @@ -210,11 +230,12 @@ describe("composer file attachments", () => { expect.objectContaining({ name, mimeType: original.mimeType, - dataUrl: `data:${original.mimeType};base64,${original.base64}`, + fileUri: `${STORED}-${name}`, sizeBytes: Buffer.from(original.base64, "base64").byteLength, - previewUri: photo.uri, }), ]); + expect(result.images[0]).not.toHaveProperty("dataUrl"); + expect(imageFiles.get(`${STORED}-${name}`)).toBe(original.base64); }); it("shrinks a fitted PNG further when re-encoding it exceeds the image limit", async () => { @@ -229,7 +250,7 @@ describe("composer file attachments", () => { uri: `file:///cache/fitted-${size.width}x${size.height}.${format}`, base64: Buffer.alloc(size.width * size.height * 4).toString("base64"), }); - mocks.size.mockReturnValue(7 * 1024 * 1024); + sizeOtherFilesAs(7 * 1024 * 1024); mocks.readBase64.mockResolvedValue(header.toString("base64")); mocks.pickMedia.mockResolvedValue({ canceled: false, @@ -248,12 +269,14 @@ describe("composer file attachments", () => { name: "IMG_9280.png", mimeType: "image/png", sizeBytes: last.width * last.height * 4, - previewUri: `file:///cache/fitted-${last.width}x${last.height}.png`, + fileUri: `${STORED}-IMG_9280.png`, }), ); expect(image!.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES); expect(mocks.delete).toHaveBeenCalledWith("file:///cache/fitted-1397x2000.png"); - expect(mocks.delete).not.toHaveBeenCalledWith(image!.previewUri); + expect(imageFiles.get(image!.previewUri)).toBe( + Buffer.alloc(last.width * last.height * 4).toString("base64"), + ); }); it("measures the picker file instead of trusting the reported size", async () => { @@ -261,7 +284,7 @@ describe("composer file attachments", () => { canceled: false, assets: [{ ...photo, fileName: "photo.png", mimeType: "image/png", fileSize: 42 }], }); - mocks.size.mockReturnValue(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); + sizeOtherFilesAs(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); const result = await pickComposerImages({ existingCount: 0 }); @@ -372,7 +395,7 @@ describe("composer file attachments", () => { ); expect(result).toEqual({ attachments: [ - expect.objectContaining({ type: "image", dataUrl: "data:image/png;base64,YWJj" }), + expect.objectContaining({ type: "image", fileUri: `${STORED}-photo.png` }), { id: "attachment-id", type: "file", @@ -398,7 +421,7 @@ describe("composer file attachments", () => { expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]); expect(result.error).toBe("Video attachments are unavailable here."); - expect(mocks.copy).not.toHaveBeenCalled(); + expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything()); }); it("uses local video metadata when the picker omits its name, MIME type, or size", async () => { @@ -476,7 +499,7 @@ describe("composer file attachments", () => { expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]); expect(result.error).toBe("You can attach up to 100 attachments per message."); expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ selectionLimit: 1 })); - expect(mocks.copy).not.toHaveBeenCalled(); + expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything()); }); it("reports a native video retrieval error and ends the foreground handoff", async () => { @@ -506,7 +529,7 @@ describe("composer file attachments", () => { canceled: false, assets: [{ uri: `file:///picker/${name}`, name, mimeType, size: 3 }], }); - mocks.size.mockReturnValue(3); + sizeOtherFilesAs(3); mocks.readBase64.mockResolvedValue("YWJj"); const result = await pickComposerFiles({ existingCount: 0 }); @@ -519,16 +542,14 @@ describe("composer file attachments", () => { name, mimeType: expected, sizeBytes: 3, - dataUrl: `data:${expected};base64,YWJj`, - previewUri: `data:${expected};base64,YWJj`, + fileUri: `${STORED}-${name}`, + previewUri: `${STORED}-${name}`, }, ], error: null, }); expect(mocks.manipulate).not.toHaveBeenCalled(); - expect(mocks.delete).toHaveBeenCalledWith( - `file:///documents/t3-composer-attachments/attachment-id-${name}`, - ); + expect(mocks.delete).not.toHaveBeenCalled(); }); it.each([ @@ -590,17 +611,19 @@ describe("composer file attachments", () => { header.writeUInt32BE(3000, 20); const original = header.toString("base64"); mocks.readBase64.mockResolvedValue(original); + imageFiles.set("file:///picker/photo.png", original); const resize = vi.fn(); const renderAsync = vi.fn(async () => ({ width: 4000, height: 3000, release: vi.fn(), - saveAsync: vi.fn(async () => ({ - uri: "file:///cache/fitted.png", - base64: oversized + saveAsync: vi.fn(async () => { + const base64 = oversized ? Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1).toString("base64") - : "YWJj", - })), + : "YWJj"; + imageFiles.set("file:///cache/fitted.png", base64); + return { uri: "file:///cache/fitted.png", base64 }; + }), })); mocks.manipulate.mockImplementation(() => { const context = { @@ -626,14 +649,12 @@ describe("composer file attachments", () => { type: "image", mimeType: "image/png", sizeBytes: oversized ? header.length : 3, - dataUrl: `data:image/png;base64,${oversized ? original : "YWJj"}`, - previewUri: oversized - ? `data:image/png;base64,${original}` - : "file:///cache/fitted.png", + fileUri: `${STORED}-photo.png`, }), ], error: null, }); + expect(imageFiles.get(`${STORED}-photo.png`)).toBe(oversized ? original : "YWJj"); }); it("releases the owned copy when reading an image fails", async () => { diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index d7830b8ed3466..de05411a8f327 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -122,6 +122,8 @@ vi.mock("./uuid", () => ({ import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages"; +const STORED = "file:///documents/t3-composer-attachments/attachment-id"; + function oversizedPng(): string { const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png); @@ -150,10 +152,12 @@ describe("native pasted image cleanup", () => { expect.objectContaining({ name: "pasted-image.jpeg", mimeType: "image/jpeg", - dataUrl: "data:image/jpeg;base64,aGVsbG8=", - previewUri: "data:image/jpeg;base64,aGVsbG8=", + fileUri: `${STORED}-pasted-image.jpeg`, + previewUri: `${STORED}-pasted-image.jpeg`, }), ]); + expect(attachments[0]).not.toHaveProperty("dataUrl"); + expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("aGVsbG8="); expect(files.get(uri)?.deleted).toBe(false); }); @@ -171,10 +175,10 @@ describe("native pasted image cleanup", () => { expect.objectContaining({ name: "pasted-image.jpeg", mimeType: "image/jpeg", - dataUrl: "data:image/jpeg;base64,cmVuZGVyZWQ=", - previewUri: "data:image/jpeg;base64,cmVuZGVyZWQ=", + fileUri: `${STORED}-pasted-image.jpeg`, }), ]); + expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("cmVuZGVyZWQ="); expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true); expect(files.get(uri)?.deleted).toBe(false); }); @@ -197,7 +201,7 @@ describe("native pasted image cleanup", () => { expect(files.get(uri)?.deleted).toBe(false); }); - it("converts owned files to data-backed previews and deletes the source", async () => { + it("stores owned pastes in an attachment file and deletes the source", async () => { const uri = "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png"; const gif = @@ -212,11 +216,13 @@ describe("native pasted image cleanup", () => { expect(attachments).toEqual([ expect.objectContaining({ - dataUrl: "data:image/png;base64,aGVsbG8=", - previewUri: "data:image/png;base64,aGVsbG8=", + fileUri: `${STORED}-pasted-image.png`, + previewUri: `${STORED}-pasted-image.png`, }), - expect.objectContaining({ mimeType: "image/gif", dataUrl: "data:image/gif;base64,R0lGODlh" }), + expect.objectContaining({ mimeType: "image/gif", fileUri: `${STORED}-pasted-image.gif` }), ]); + expect(files.get(`${STORED}-pasted-image.png`)?.base64).toBe("aGVsbG8="); + expect(files.get(`${STORED}-pasted-image.gif`)?.base64).toBe("R0lGODlh"); expect(files.get(uri)?.deleted).toBe(true); expect(files.get(gif)?.deleted).toBe(true); }); @@ -267,7 +273,7 @@ describe("native pasted image cleanup", () => { const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 }); expect(result.attachments).toEqual([ - expect.objectContaining({ dataUrl: "data:image/png;base64,aGVsbG8=" }), + expect.objectContaining({ fileUri: `${STORED}-pasted-image.png` }), ]); expect(result.error).toBe("Could not read a pasted image."); }); diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index 69f26103134b9..4c81024c1d403 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -124,7 +124,7 @@ export function isFileBackedComposerAttachment( return attachment.fileUri !== undefined; } -/** Inline library/clipboard images own no file; local ids cannot resolve server assets. */ +/** Legacy inline images have only a local draft id, so a remote asset lookup cannot load them. */ export function composerAttachmentInlineUri( attachment: DraftComposerAttachment | undefined, ): string | undefined { @@ -135,6 +135,11 @@ export function composerAttachmentInlineUri( const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste"; const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024; +// Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. +function safeComposerAttachmentName(name: string): string { + return name.replace(/[^\w. -]/g, "-") || "file"; +} + export async function persistComposerAttachmentFile( uri: string, name: string, @@ -143,9 +148,7 @@ export async function persistComposerAttachmentFile( const { Directory, File, FileMode, Paths } = await import("expo-file-system"); const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY); directory.create({ idempotent: true, intermediates: true }); - // Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. - const safeName = name.replace(/[^\w. -]/g, "-") || "file"; - const destination = new File(directory, `${uuidv4()}-${safeName}`); + const destination = new File(directory, `${uuidv4()}-${safeComposerAttachmentName(name)}`); const source = new File(uri); const sourceSize = source.size; if ( @@ -218,6 +221,35 @@ export async function persistComposerAttachmentFile( return destination.uri; } +async function ownedComposerImageAttachment(input: { + readonly fileUri: string; + readonly name: string; + readonly mimeType: string; +}): Promise { + try { + const { File } = await import("expo-file-system"); + const sizeBytes = new File(input.fileUri).size; + if (sizeBytes === null || sizeBytes <= 0) { + throw new Error(m(msg("''{name}'' is empty or could not be read.", { name: input.name }))); + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + throw new Error( + fileAttachmentTooLargeMessage(input.name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m), + ); + } + return { + ...input, + id: uuidv4(), + type: "image", + sizeBytes, + previewUri: input.fileUri, + }; + } catch (error) { + await removePersistedComposerAttachmentFile(input.fileUri); + throw error; + } +} + export async function removePersistedComposerAttachmentFile(uri: string): Promise { try { const { File, Paths } = await import("expo-file-system"); @@ -333,37 +365,29 @@ export async function pickComposerFiles(input: { attachments.push(attachment); continue; } + const { File } = await import("expo-file-system"); + let fileUri = attachment.fileUri; try { - const { File } = await import("expo-file-system"); - const original = await new File(attachment.fileUri).base64(); - const candidate = await fitComposerImage({ - uri: attachment.fileUri, - mimeType, - base64: original, - }); + const original = await new File(fileUri).base64(); + const candidate = await fitComposerImage({ uri: fileUri, mimeType, base64: original }); const fitted = candidate !== null && estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? candidate : null; - const base64 = fitted?.base64 ?? original; - const sizeBytes = estimateBase64ByteSize(base64); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - throw new Error(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + if (fitted !== null) { + fileUri = await persistComposerAttachmentFile( + fitted.uri, + name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + await removePersistedComposerAttachmentFile(attachment.fileUri); } - const dataUrl = `data:${mimeType};base64,${base64}`; - attachments.push({ - id: attachment.id, - type: "image", - name, - mimeType, - sizeBytes, - dataUrl, - previewUri: fitted?.uri ?? dataUrl, - }); - } finally { + } catch (cause) { await removePersistedComposerAttachmentFile(attachment.fileUri); + throw cause; } + attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); } catch (cause) { error = errorDisplayMessage(cause, m) ?? m(msg("Could not read ''{name}''.", { name })); } @@ -517,7 +541,7 @@ export async function pickComposerMedia(input: { ? mimeType : null; - let image: { base64: string; mimeType: string; name: string; previewUri: string }; + let image: { base64: string; mimeType: string; name: string; uri: string }; try { if (originalMimeType !== null) { const { File } = await import("expo-file-system"); @@ -531,7 +555,7 @@ export async function pickComposerMedia(input: { base64: fitted?.base64 ?? base64, mimeType: originalMimeType, name, - previewUri: fitted?.uri ?? asset.uri, + uri: fitted?.uri ?? asset.uri, }; } else { const rendered = await renderPhoto(asset.uri); @@ -539,7 +563,7 @@ export async function pickComposerMedia(input: { base64: rendered.base64, mimeType: "image/jpeg", name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`, - previewUri: rendered.uri, + uri: rendered.uri, }; } } catch { @@ -553,15 +577,18 @@ export async function pickComposerMedia(input: { continue; } - attachments.push({ - id: uuidv4(), - type: "image", - name: image.name, - mimeType: image.mimeType, - sizeBytes, - dataUrl: `data:${image.mimeType};base64,${image.base64}`, - previewUri: image.previewUri, - }); + try { + const fileUri = await persistComposerAttachmentFile( + image.uri, + image.name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + attachments.push( + await ownedComposerImageAttachment({ fileUri, name: image.name, mimeType: image.mimeType }), + ); + } catch (cause) { + error = errorDisplayMessage(cause, m) ?? m(msg("Failed to read ''{name}''.", { name })); + } } return { @@ -639,6 +666,7 @@ export async function convertPastedImagesToAttachments(input: { temporaryUris.push(fitted.uri); } let base64 = fitted?.base64 ?? pastedBase64; + let sourceUri = fitted?.uri ?? uri; if ( rendered === null && estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES @@ -647,6 +675,7 @@ export async function convertPastedImagesToAttachments(input: { temporaryUris.push(jpeg.uri); mimeType = "image/jpeg"; base64 = jpeg.base64; + sourceUri = jpeg.uri; } const sizeBytes = estimateBase64ByteSize(base64); if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { @@ -656,16 +685,13 @@ export async function convertPastedImagesToAttachments(input: { : m(msg("Could not read a pasted image.")); continue; } - const dataUrl = `data:${mimeType};base64,${base64}`; - attachments.push({ - id: uuidv4(), - type: "image", - name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`, - mimeType, - sizeBytes, - dataUrl, - previewUri: dataUrl, - }); + const name = `pasted-image.${mimeType.split("/")[1] ?? "png"}`; + const fileUri = await persistComposerAttachmentFile( + sourceUri, + name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); } catch (cause) { console.warn("Failed to read pasted image", uri, cause); error = m(msg("Could not read a pasted image.")); diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts index d85340a8556d2..e7e9fe9a302a0 100644 --- a/apps/mobile/src/state/thread-outbox-model.ts +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -34,8 +34,8 @@ import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/compose import type { DraftComposerAttachment } from "../lib/composerImages"; import { scopedThreadKey } from "../lib/scopedEntities"; -// Keep current writes until a compatible native baseline includes the v4 reader. -const THREAD_OUTBOX_SCHEMA_VERSION = 3; +// v4 file-backed writes require native baselines with embedded readers and storage guards. +const THREAD_OUTBOX_SCHEMA_VERSION = 4; const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000; const QueuedThreadCreationSchema = Schema.Struct({ @@ -52,7 +52,7 @@ const QueuedThreadCreationSchema = Schema.Struct({ }); export const QueuedThreadMessageSchema = Schema.Struct({ - schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION, 4]), + schemaVersion: Schema.Literals([1, 2, 3, THREAD_OUTBOX_SCHEMA_VERSION]), environmentId: EnvironmentId, threadId: ThreadId, messageId: MessageId, diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index fd1c248f5de9b..8c1870f76836b 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -91,9 +91,12 @@ const composerDraftFileMocks = vi.hoisted(() => { exists = true; size = 3; parentDirectory = null; + uri = "file:///documents/attachment.png"; create() {} + async copy() {} + moveSync() {} async text() { @@ -144,6 +147,7 @@ const incomingShareStorageMocks = vi.hoisted(() => ({ vi.mock("expo-file-system", () => ({ Directory: composerDraftFileMocks.Directory, File: composerDraftFileMocks.File, + FileMode: {}, Paths: { document: { uri: "file:///documents" } }, })); @@ -297,7 +301,7 @@ it.each(["picker open", "reading image"] as const)( expect.objectContaining({ type: "image", name: "screenshot.png", - dataUrl: "data:image/png;base64,YWJj", + fileUri: "file:///documents/attachment.png", }), ], ); @@ -1217,6 +1221,22 @@ describe("mobile composer drafts", () => { expect( appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id), ).toEqual(["red", "blue"]); + + const makeStoredPaste = (id: string) => ({ + id, + type: "image" as const, + name: "pasted-image.png", + mimeType: "image/png", + sizeBytes: 3, + fileUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + previewUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + }); + const storedKey = "new-task:environment-1:project-stored-pastes"; + appendComposerDraftAttachments(storedKey, [makeStoredPaste("red")]); + appendComposerDraftAttachments(storedKey, [makeStoredPaste("green")]); + expect( + appAtomRegistry.get(composerDraftsAtom)[storedKey]?.attachments.map(({ id }) => id), + ).toEqual(["red", "green"]); }); it("keeps shared attachment files until every draft releases them", async () => { diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 0020defdc5915..10d8fd7a4f271 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1431,7 +1431,9 @@ function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment a.mimeType === b.mimeType && a.sizeBytes === b.sizeBytes && a.name === b.name && - (a.type !== "image" || b.type !== "image" || a.dataUrl === b.dataUrl) + (a.type !== "image" || + b.type !== "image" || + (a.dataUrl === b.dataUrl && a.fileUri === b.fileUri)) ); } From ad2bdc76a5bf22cd63b84e2cdee610c1a1b4bd18 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 06:14:38 -0800 Subject: [PATCH 67/96] fix(server): watch_pull_request says when checks already passed (#40866) --- apps/server/src/mcp/toolkits/pullRequests/handlers.ts | 9 ++++++--- apps/server/src/mcp/toolkits/pullRequests/tools.ts | 4 ++++ .../src/pullRequest/PullRequestWatchService.test.ts | 10 ++++++++++ apps/server/src/pullRequest/PullRequestWatchService.ts | 6 ++++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index e422a799f3d9a..ddb3f2a025d43 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -66,6 +66,7 @@ import { PullRequestsToolkit, type ThreadPullRequestEntry, alreadyEndedWatchNext, + CHECKS_ALREADY_PASSED_WATCH_NEXT, CHILD_PULL_REQUEST_REPORT_NEXT, } from "./tools.ts"; @@ -333,9 +334,11 @@ const make = Effect.gen(function* () { .setWatching({ threadId, target: input, watching, until: input.until }) .pipe( Effect.map((result) => - result.state === undefined - ? result - : { ...result, next: alreadyEndedWatchNext(result.state) }, + result.state !== undefined + ? { ...result, next: alreadyEndedWatchNext(result.state) } + : result.checksState === "passing" + ? { ...result, next: CHECKS_ALREADY_PASSED_WATCH_NEXT } + : result, ), Effect.catchTags({ PullRequestWatchThreadNotFoundError: (error) => diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 847ae4ef19e7d..1e75c5bbaa19f 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -263,6 +263,7 @@ export const WatchPullRequestResult = Schema.Struct({ description: "The PR already ended, so nothing was watched.", }), ), + checksState: Schema.optional(PullRequestChecksState), next: Schema.optional(Schema.String), }); export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; @@ -270,6 +271,9 @@ export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; export const alreadyEndedWatchNext = (state: "merged" | "closed") => `This PR is already ${state}, so there is nothing to watch. Report that and end your turn.`; +export const CHECKS_ALREADY_PASSED_WATCH_NEXT = + "Checks already pass on this head, so no wake will come for them. Act on that now; the watch still wakes you on later changes."; + export const ThreadPullRequestEntry = Schema.Struct({ ...PullRequestIdentity, source: ThreadPullRequestLinkSource, diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts index edf4fee9c5c56..8982e795e2615 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.test.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -205,6 +205,16 @@ describe("PullRequestWatchService", () => { }), ); + it.effect("tells the caller when the checks already passed, since no wake will report it", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ readChecksState: "passing" }); + const result = yield* harness.setWatching(true, { + url: "https://github.com/t3tools/t3code/pull/9", + }); + expect(result).toMatchObject({ wasWatching: false, checksState: "passing" }); + }), + ); + it.effect("reports a missing hosting CLI before saving a watch and still allows unwatch", () => Effect.gen(function* () { const missing = new PullRequestUnavailableError({ diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 5e64ac4206896..32f51f540bf9f 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -2,6 +2,7 @@ import { CommandId, ThreadId, type OrchestrationV2ThreadShell, + type PullRequestChecksState, type PullRequestUnavailableError, type PullRequestWatchUntil, } from "@t3tools/contracts"; @@ -68,6 +69,8 @@ export class PullRequestWatchService extends Context.Service< readonly wasWatching: boolean; /** Set when the PR already ended, so no watch was registered. */ readonly state?: "merged" | "closed"; + /** CI as the start read saw it. Checks that already passed never wake the watch. */ + readonly checksState?: PullRequestChecksState; }, | PullRequestWatchFailedError | PullRequestWatchFromSubagentError @@ -130,6 +133,7 @@ const make = Effect.gen(function* () { if (watching && before?.snapshot?.state === "merged") return alreadyEnded("merged"); // A pending rollup has no failure yet, so any failure the first read finds is news. let checksPendingAtStart: boolean | undefined; + let checksStateAtStart: PullRequestChecksState | undefined; if (watching && !wasWatching) { const read = yield* pullRequests .summary( @@ -151,6 +155,7 @@ const make = Effect.gen(function* () { ); if (read?.state === "merged" || read?.state === "closed") return alreadyEnded(read.state); checksPendingAtStart = read === undefined ? undefined : read.checksState === "pending"; + checksStateAtStart = read?.checksState ?? undefined; } const uuid = yield* random.uuidV4().pipe(Effect.orDie); yield* engine @@ -180,6 +185,7 @@ const make = Effect.gen(function* () { ...target, watching: watchedLink(after)?.watch !== undefined, wasWatching, + ...(checksStateAtStart !== undefined && { checksState: checksStateAtStart }), }; }); From a445025645680d8c282011df5edc774f4551e6d8 Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 14:38:36 +0000 Subject: [PATCH 68/96] fix(codex): Open diff shows every file of a multi-file patch (#40874) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Adapters/CodexAdapterV2.test.ts | 22 +++++++++++++ .../Adapters/CodexAdapterV2.ts | 32 ++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index ef4ffcf35c11b..d30748a0df77c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -12809,6 +12809,28 @@ describe("CodexAdapterV2 post-settle continuation", () => { { operation: "delete", path: "/w/e.ts" }, { operation: "add", path: "/w/a.ts" }, ]); + assert.equal( + fileChanges[0]?.diffStr, + [ + 'diff --git "a//w/c.ts" "b//w/d.ts"', + '--- "a//w/c.ts"', + '+++ "b//w/d.ts"', + "@@", + 'diff --git "a//w/e.ts" "b//w/e.ts"', + '--- "a//w/e.ts"', + "+++ /dev/null", + "@@ -1,1 +0,0 @@", + "-gone", + "\\ No newline at end of file", + 'diff --git "a//w/a.ts" "b//w/a.ts"', + "--- /dev/null", + '+++ "b//w/a.ts"', + "@@ -0,0 +1,1 @@", + "+export {};", + "\\ No newline at end of file", + "", + ].join("\n"), + ); }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index e5dfd83559292..181ed17fd5c16 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -178,6 +178,35 @@ type CodexFileChangeKinds = Readonly< Record >; +// Diff parsers split at Git headers once one exists, so each file of a multi-file patch needs its own. +function codexMultiFilePatch( + changes: ReadonlyArray, +): string { + return changes + .map(({ path, kind, diff }) => { + const oldPath = path; + const newPath = (kind.type === "update" && kind.move_path) || path; + const git = `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n`; + if (kind.type === "update" && diff.startsWith("diff --git ")) return diff; + if (kind.type === "update" && diff.startsWith("--- ")) return `${git}${diff}`; + let hunks = diff; + // Codex records added and deleted files as their raw contents. + if (kind.type !== "update") { + const lines = diff.split("\n"); + const hasFinalNewline = diff.endsWith("\n"); + if (hasFinalNewline) lines.pop(); + const added = kind.type === "add"; + const range = `1,${lines.length}`; + hunks = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`; + } + const before = kind.type === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = kind.type === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`); + return `${git}--- ${before}\n+++ ${after}\n${hunks}`; + }) + .map((section) => (section.endsWith("\n") ? section : `${section}\n`)) + .join(""); +} + function codexFileChangeApprovalPrompt(input: { readonly reason?: string | null; readonly grantRoot?: string | null; @@ -4285,7 +4314,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updatedAt, type: "file_change", fileName: firstChange.path, - diffStr: firstChange.diff, + diffStr: + item.changes.length > 1 ? codexMultiFilePatch(item.changes) : firstChange.diff, changes: item.changes.map((change) => { const movePath = change.kind.type === "update" ? change.kind.move_path : undefined; return movePath From 2f19cec07933f9f5fe1fe380d98b0841f83b90be Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 06:41:15 -0800 Subject: [PATCH 69/96] fix(server): ACP startup gives up when the agent never answers the handshake (#40864) --- .../provider/acp/AcpJsonRpcConnection.test.ts | 20 ++++++++++++++ .../src/server/AcpSessionRuntime.ts | 27 ++++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index 796bc854d28d6..a000e05471bc6 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -1621,6 +1621,26 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("fails startup when the agent never answers initialize", () => + Effect.gen(function* () { + const initializeSent = yield* Deferred.make(); + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + // A live child that reads stdin and never replies, like one stuck in disk sleep. + spawn: { command: "node", args: ["-e", "process.stdin.resume()"] }, + requestLogger: (event) => + event.method === "initialize" && event.status === "started" + ? Deferred.succeed(initializeSent, undefined) + : Effect.void, + }); + const startup = yield* runtime.start().pipe(Effect.forkChild); + yield* Deferred.await(initializeSent); + yield* TestClock.adjust("30 minutes"); + const exit = yield* Fiber.await(startup); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("sends a cancel after the cancel timeout when its prompt never goes out", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.make({ diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 2c488b6bdd83c..b08eef243fc3e 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -85,6 +85,8 @@ export type AcpSessionRuntimeEvent = }; const defaultSessionLoadTimeout = Duration.seconds(90); +// A live child that never answers the handshake would otherwise hold the start open forever. +const startupRequestTimeout = Duration.seconds(90); const defaultSessionLoadReplayIdleGap = Duration.seconds(2); const defaultCancelTimeout = Duration.seconds(15); const maxStartupMetadataUpdates = 32; @@ -1399,6 +1401,25 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( Effect.andThen(runLoggedRequest(method, payload, effect)), ); + const withStartupTimeout = ( + method: string, + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.timeoutOrElse({ + duration: startupRequestTimeout, + orElse: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + operation: "call-rpc", + method, + detail: `${method} timed out waiting for RPC response`, + cause: undefined, + }), + ), + }), + ); + const runLoggedRequest = ( method: string, payload: unknown, @@ -2297,7 +2318,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const initializeResult = yield* runLoggedRequest( "initialize", initializePayload, - acp.agent.initialize(initializePayload), + withStartupTimeout("initialize", acp.agent.initialize(initializePayload)), ); yield* options.onInitialized?.(initializeResult) ?? Effect.void; return initializeResult; @@ -2445,7 +2466,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult = yield* runLoggedRequest( "session/resume", resumePayload, - acp.agent.resumeSession(resumePayload), + withStartupTimeout("session/resume", acp.agent.resumeSession(resumePayload)), ); } else { return yield* new EffectAcpErrors.AcpRequestError({ @@ -2462,7 +2483,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const created = yield* runLoggedRequest( "session/new", createPayload, - acp.agent.createSession(createPayload), + withStartupTimeout("session/new", acp.agent.createSession(createPayload)), ); sessionId = created.sessionId; sessionSetupResult = created; From 1d028248683f90f405b2d8e7b71682e3b67317ed Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 14:43:54 +0000 Subject: [PATCH 70/96] fix(server): a branch prefixed with another remote's name publishes under its full name (#40877) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 29 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 21 ++++++-------- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d9a661c7b1237..b3ad640db4c7a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -10325,6 +10325,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "publishes a new branch prefixed with another remote's name under its full name", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const origin = yield* makeTmpDir("git-remote-"); + const fork = yield* makeTmpDir("git-fork-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(origin, ["init", "--bare"]); + yield* git(fork, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", origin]); + // e.g. the remote T3 adds when checking out a pull request from alice's fork. + yield* git(cwd, ["remote", "add", "alice", fork]); + yield* git(cwd, ["checkout", "-b", "alice/fix"]); + yield* writeTextFile(cwd, "fix.txt", "fix\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add fix", ""); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { status: "pushed", upstreamBranch: "origin/alice/fix" }); + assert.equal( + yield* git(origin, ["--git-dir=.", "rev-parse", "refs/heads/alice/fix"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + }), + ); + it.effect("still pushes a git-mangled tracking alias to its upstream head", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 8f3e3e16ca12b..f863f01bdb40a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2147,14 +2147,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map(parseRemoteNamesInGitOrder), ); - const resolvePublishBranchName = Effect.fn("resolvePublishBranchName")(function* ( - cwd: string, - branchName: string, - ) { - const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => [])); - const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames); - return parsedRemoteRef?.branchName ?? branchName; - }); + // Only the destination remote's prefix is dropped; `alice/fix` pushed to origin keeps its full name. + const resolvePublishBranchName = (branchName: string, remoteName: string) => + parseRemoteRefWithRemoteNames(branchName, [remoteName])?.branchName ?? branchName; const hasAnyRemote = (cwd: string) => resolveRepositoryPaths(cwd).pipe( @@ -3680,7 +3675,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // A gone local upstream still gets the full local name, as below. const branchName = goneUpstream?.branchName ?? - (configuredRemoteName === "." ? branch : yield* resolvePublishBranchName(cwd, branch)); + (configuredRemoteName === "." ? branch : resolvePublishBranchName(branch, remoteName)); return { remoteName, branchName, @@ -3731,10 +3726,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( Effect.orElseSucceed(() => null), ); - const branchName = yield* resolvePublishBranchName(cwd, branch); + const remoteName = publishRemoteName ?? upstream.remoteName; return { - remoteName: publishRemoteName ?? upstream.remoteName, - branchName, + remoteName, + branchName: resolvePublishBranchName(branch, remoteName), publishes: true, upstream, pushRemote: null, @@ -3774,7 +3769,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const requestedRemoteName = options?.remoteName?.trim() || null; if (requestedRemoteName) { - const publishBranch = yield* resolvePublishBranchName(cwd, branch); + const publishBranch = resolvePublishBranchName(branch, requestedRemoteName); yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, From f10e1eb3825a773cf702569d2258edfdbc8b77dc Mon Sep 17 00:00:00 2001 From: project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:55:27 -0600 Subject: [PATCH 71/96] fix(server): list open delegated tasks when task_status or task_cancel finds no match (#40886) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 8 ++++ apps/server/src/mcp/OrchestratorMcpService.ts | 38 +++++++++++++++---- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index ccd41144a5ea8..551a84109cfa2 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -106,6 +106,7 @@ describe("OrchestratorMcpService", () => { threadId: parentThreadId, origin: "app_owned", childThreadId, + title: "Merge", driver: "codex", model: "gpt-5.6-terra", result: "terminal result", @@ -252,6 +253,13 @@ describe("OrchestratorMcpService", () => { const commandIds = yield* Ref.get(acknowledgementCommandIds); assert.equal(commandIds.length, 2); assert.notEqual(commandIds[0], commandIds[1]); + + const missing = yield* service + .taskStatus(scope, NodeId.make("node:mcp-ack-missing")) + .pipe(Effect.flip); + assert.equal(missing.code, "task_not_found"); + assert.include(missing.message, "No delegated task with id node:mcp-ack-missing"); + assert.include(missing.message, `${taskId} (Merge)`); }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); }), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 4062c509812c4..f9ad32a6e1d3e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -154,6 +154,7 @@ const TASK_WAKE_EVENTS = [ { thread: "child", eventType: "runtime-request.updated" }, ] as const; const SECRET_REQUEST_POLL_INTERVAL_MS = 500; +const MAX_LISTED_TASKS = 10; const DEFAULT_THREAD_LIST_LIMIT = 10; const DEFAULT_THREAD_READ_LIMIT = 10; const DEFAULT_THREAD_RUN_LIMIT = 10; @@ -1805,6 +1806,33 @@ const make = Effect.gen(function* () { const requestKey = (clientRequestId: string | undefined): Effect.Effect => clientRequestId === undefined ? random.uuidV4() : Effect.succeed(clientRequestId); + const taskNotFound = Effect.fn("OrchestratorMcpService.taskNotFound")(function* ( + scope: McpThreadInvocationScope, + taskId: NodeId, + ): Effect.fn.Return { + const { subagents } = yield* loadThreadRecords(scope.thread.threadId, ["subagents"], { + omitSettledSubagents: true, + }); + const open = subagents.filter( + (task) => + task.origin === "app_owned" && + (task.childThreadId !== null || task.remoteChild !== undefined), + ); + const listed = open + .slice(0, MAX_LISTED_TASKS) + .map((task) => (task.title ? `${task.id} (${task.title})` : task.id)) + .join(", "); + const more = + open.length > MAX_LISTED_TASKS ? `, and ${open.length - MAX_LISTED_TASKS} more` : ""; + return yield* failure( + "task_not_found", + `No delegated task with id ${taskId} exists on thread ${scope.thread.threadId}. ` + + (open.length === 0 + ? "This thread has no open delegated tasks." + : `Open delegated tasks on this thread: ${listed}${more}.`), + ); + }); + const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* ( scope: McpThreadInvocationScope, taskId: NodeId, @@ -1820,10 +1848,7 @@ const make = Effect.gen(function* () { candidate.threadId === scope.thread.threadId, ); if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) { - return yield* failure( - "task_not_found", - `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, taskId); } if (task.childThreadId === null) { return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal); @@ -3006,10 +3031,7 @@ const make = Effect.gen(function* () { task.remoteChild !== undefined, ); if (remoteTask === undefined) { - return yield* failure( - "task_not_found", - `Delegated task ${input.taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, input.taskId); } return yield* remoteDelegation.cancel(scope, remoteTask, input); } From 2251de4d2e61f921b90fb7bfdabef8b1a34d8803 Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 15:23:05 +0000 Subject: [PATCH 72/96] fix(gitlab): find merge requests opened from a fork (#40894) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/GitLabCli.ts | 46 +++++++++- .../GitLabSourceControlProvider.git.test.ts | 91 +++++++++++++++++++ .../GitLabSourceControlProvider.test.ts | 7 ++ .../src/server/GitLabSourceControlProvider.ts | 16 +++- .../src/server/gitLabMergeRequests.ts | 20 ++++ 5 files changed, 173 insertions(+), 7 deletions(-) diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index b528c1ced5a8a..04a633bba7096 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { decodeGitLabMergeRequestJson, decodeGitLabMergeRequestListJson, + type NormalizedGitLabMergeRequestRecord, + withSourceProjectPath, } from "./gitLabMergeRequests.ts"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })), ); +const decodeGitLabProjectPath = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })), +); + const RawGitLabNamespaceSchema = Schema.Struct({ id: Schema.Number, }); @@ -559,6 +565,35 @@ export const make = Effect.gen(function* () { ), ); + // glab's MR JSON names a fork's source project only by `source_project_id`. + const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* ( + cwd: string, + records: ReadonlyArray, + paths: Map, + ) { + const ids = new Set(); + for (const record of records) { + const id = record.unresolvedSourceProjectId; + if (id !== undefined && !paths.has(id)) ids.add(id); + } + yield* Effect.forEach( + ids, + (id) => + execute({ cwd, args: ["api", `projects/${id}`] }).pipe( + Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())), + Effect.map((project) => project.path_with_namespace), + Effect.orElseSucceed(() => null), + Effect.map((path) => void paths.set(id, path)), + ), + { concurrency: 8, discard: true }, + ); + return records.map((record) => + record.unresolvedSourceProjectId === undefined + ? record + : withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null), + ); + }); + return GitLabCli.of({ execute, listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) { @@ -566,6 +601,7 @@ export const make = Effect.gen(function* () { let pageSize = limit; let page = 1; const items: GitLabMergeRequestSummary[] = []; + const sourceProjectPaths = input.source?.owner ? new Map() : null; while (items.length < limit) { const result = yield* execute({ cwd: input.cwd, @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () { cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated", }); } - items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt)); + // Only a fork head can match a fork's merge request, so other lookups skip the API calls. + const records = sourceProjectPaths + ? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths) + : decoded.success; + items.push(...records.map(toSummaryWithOptionalUpdatedAt)); // Count raw entries: the decoder drops invalid ones, which would end paging early. const entries = decodeJsonArray(raw); if ( @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () { ); } - return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success)); + return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe( + Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)), + ); }), ), ), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index 7038e6a82d630..abd2f7b82f218 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }), ); +// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its +// source project only by `source_project_id`, never by a `source_project` path. +it.effect("names a fork merge request's source project from real glab list output", () => + Effect.gen(function* () { + const branch = "feature/fork-work"; + const mergeRequest = (iid: number, sourceProjectId: number) => ({ + id: 9000 + iid, + iid, + project_id: 100, + title: `Work ${iid}`, + state: "opened", + target_branch: "main", + source_branch: branch, + source_project_id: sourceProjectId, + target_project_id: 100, + draft: false, + sha: "0123456789abcdef0123456789abcdef01234567", + updated_at: "2026-04-07T15:00:00.000Z", + references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` }, + web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`, + }); + const output = JSON.stringify([ + mergeRequest(1, 101), + mergeRequest(2, 101), + mergeRequest(3, 100), + mergeRequest(4, 102), + ]); + const apiCalls: ReadonlyArray[] = []; + const provider = yield* GitLabSourceControlProvider.make.pipe( + Effect.provide( + GitLabCli.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => + Effect.sync(() => { + if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output); + apiCalls.push(input.args); + return TestSourceControlHost.processOutput( + input.args[1] === "projects/101" + ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" }) + : "not json", + ); + }), + }, + }), + ), + Layer.provide(FileSystem.layerNoop({})), + ), + ), + ); + + const upstreamHead = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: branch, + state: "open", + limit: 20, + }); + expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toEqual([]); + + const changeRequests = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: `alice:${branch}`, + state: "open", + limit: 20, + }); + // GitManager drops a cross-repository MR whose head project is unnamed. + expect(changeRequests).toMatchObject([ + { + number: 1, + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/upstream", + headRepositoryOwnerLogin: "alice", + }, + { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" }, + { number: 3, isCrossRepository: false }, + { number: 4, isCrossRepository: true }, + ]); + expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toHaveLength(2); + expect(apiCalls).toEqual( + expect.arrayContaining([ + ["api", "projects/101"], + ["api", "projects/102"], + ]), + ); + }), +); + const withRepository = ( test: (input: { readonly git: (...args: string[]) => Effect.Effect; diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..c5a2d56037172 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -210,6 +210,13 @@ it.effect( headSelectors: ["octocat:feature", "feature"], state: "open", }), + { headSelectors: ["octocat:feature"], limit: 100 }, + ); + assert.deepStrictEqual( + provider.headBranchProbe?.({ + headSelectors: ["feature", "octocat:feature"], + state: "open", + }), { headSelectors: ["feature"], limit: 100 }, ); }), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts index a7d5b71ca47d3..2a2d4ac3e199c 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("gitlab"), - // GitLab lists fork merge requests by source branch with no owner filter, so read a full page. - headBranchProbe: ({ headSelectors }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), - limit: 100, - }), + // GitLab lists fork merge requests by source branch with no owner filter, so read a full page + // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork + // head, which tells the list to name fork source projects. + headBranchProbe: ({ headSelectors }) => { + const byBranch = new Map(); + for (const selector of headSelectors) { + const branch = SourceControlProvider.sourceBranch({ headSelector: selector }); + if (!byBranch.has(branch)) byBranch.set(branch, selector); + } + return { headSelectors: [...byBranch.values()], limit: 100 }; + }, readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")( function ({ cwd, treeish }) { return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute); diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts index ef4438f5ff3ee..a40abd786cf85 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord { readonly isCrossRepository?: boolean; readonly headRepositoryNameWithOwner?: string | null; readonly headRepositoryOwnerLogin?: string | null; + /** Set when a cross-repository MR names its source project only by id. */ + readonly unresolvedSourceProjectId?: number; } const GitLabProjectReferenceSchema = Schema.Struct({ @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord( ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + ...(isCrossRepository === true && + !sourceProjectPath && + typeof raw.source_project_id === "number" + ? { unresolvedSourceProjectId: raw.source_project_id } + : {}), + }; +} + +export function withSourceProjectPath( + record: NormalizedGitLabMergeRequestRecord, + sourceProjectPath: string | null, +): NormalizedGitLabMergeRequestRecord { + const { unresolvedSourceProjectId: _, ...resolved } = record; + const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath); + return { + ...resolved, + ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), }; } From 2c4310eb061373bb1c6ccefe6dafd0500ee8f5e3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 07:29:08 -0800 Subject: [PATCH 73/96] fix(web): pasting a chat message with text and a picture keeps both (#40909) --- apps/web/src/components/chat/ChatComposer.tsx | 23 ++++++++---- .../chat/composerAttachmentFiles.test.ts | 7 ++++ .../chat/composerAttachmentFiles.ts | 35 ++++++++++++++----- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6fb651c3471f6..af4871b451932 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,7 +133,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, - isImageOnlyClipboardHtml, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -2947,18 +2948,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const pastedContext = !isLiteralPendingAnswer && (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; + const htmlImageContent = + canAttachFiles && plainText.length > 0 + ? clipboardHtmlImageContent(event.clipboardData.getData("text/html")) + : "none"; if ( folders.length > 0 || - (!pastedContext && - activeThreadId && - files.length > 0 && + (canAttachFiles && shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment, - htmlIsOnlyImage: - plainText.length > 0 && - isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + htmlIsOnlyImage: htmlImageContent === "only-image", })) ) { event.preventDefault(); @@ -2971,6 +2973,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } if (pastedContext) return; + const imagesBesideText = imagesToAttachBesidePastedText({ + files, + plainText, + bypassAutoAttachment, + htmlHasImageAndText: htmlImageContent === "image-and-text", + }); + if (imagesBesideText.length > 0) void addComposerAttachments(imagesBesideText); if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index f842566d7cd60..ac43d667d80ca 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -13,6 +13,7 @@ import { composerFileAttachmentMimeType, fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, + imagesToAttachBesidePastedText, normalizeComposerImageFileMimeType, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; @@ -141,6 +142,12 @@ describe("composer attachment files", () => { expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( true, ); + // A QQ or WeChat message has its text beside an in the HTML: the image attaches too. + const message = { files: [image], plainText: "Look at this", htmlHasImageAndText: true }; + expect(shouldHandleComposerAttachmentPaste(message)).toBe(false); + expect(imagesToAttachBesidePastedText(message)).toEqual([image]); + expect(imagesToAttachBesidePastedText({ ...message, htmlHasImageAndText: false })).toEqual([]); + expect(imagesToAttachBesidePastedText({ ...message, bypassAutoAttachment: true })).toEqual([]); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 191c5841185ff..538d2dfd67304 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -247,11 +247,33 @@ function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { .every((line) => names.has(line)); } -/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ -export function isImageOnlyClipboardHtml(html: string): boolean { - if (html.length === 0) return false; +/** + * A browser's Copy Image puts only an in text/html; a chat message (QQ, WeChat) puts its text + * beside the ; rich text sources (Word, Pages) put only the text there. + */ +export function clipboardHtmlImageContent(html: string): "only-image" | "image-and-text" | "none" { + if (html.length === 0) return "none"; const body = new DOMParser().parseFromString(html, "text/html").body; - return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; + if (body.querySelector("img") === null) return "none"; + return (body.textContent ?? "").trim().length === 0 ? "only-image" : "image-and-text"; +} + +function isPastedImageFile(file: File): boolean { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; +} + +/** The images of a message copied with its text: they attach while the text pastes as text. */ +export function imagesToAttachBesidePastedText(input: { + readonly files: ReadonlyArray; + readonly plainText: string; + readonly bypassAutoAttachment?: boolean; + readonly htmlHasImageAndText: boolean; +}): File[] { + if (input.bypassAutoAttachment || input.plainText.length === 0 || !input.htmlHasImageAndText) { + return []; + } + return input.files.filter(isPastedImageFile); } export function shouldHandleComposerAttachmentPaste(input: { @@ -269,10 +291,7 @@ export function shouldHandleComposerAttachmentPaste(input: { ) { return true; } - const hasImage = input.files.some((file) => { - const classification = classifyComposerAttachmentFile(file); - return classification === "image" || classification === "unsupported-image"; - }); + const hasImage = input.files.some(isPastedImageFile); if (input.plainText.length === 0) { return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } From 344de5fe8e70e9eeaacaedc34e7aa5e2a29287d1 Mon Sep 17 00:00:00 2001 From: Lokkuchakreshkumar Date: Sun, 22 Nov 2026 21:53:23 +0530 Subject: [PATCH 74/96] fix(antigravity): bound silent post-settle background command holds (#40858) Co-authored-by: LVC-Chakresh Co-authored-by: Julius Marminge --- .../Adapters/AntigravityAdapterV2.test.ts | 119 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 7 ++ .../src/provider/acp/AntigravityProtocol.ts | 6 + packages/provider-acp/src/server/adapter.ts | 57 ++++++++- 4 files changed, 187 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..5cbb4975e5e57 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1327,6 +1327,16 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); yield* startTurn(1, false); yield* throughPromptSettled; + // Progress keeps a command past the post-settle hold bound, which counts silence only. + for (const minute of [10, 20, 30]) { + yield* TestClock.adjust("10 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "in_progress", + rawOutput: { output: `fetched ${minute} pages` }, + }); + } yield* TestClock.adjust("10 minutes"); yield* send({ sessionUpdate: "tool_call_update", @@ -1349,6 +1359,115 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // A command whose terminal update never arrives would hold the run in Working forever with + // an empty pending list and a finished reply above Stop. + it.effect("settles a silent background command after the post-settle hold timeout", () => + Effect.gen(function* () { + const { command, offers, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + const prompt = yield* throughPromptSettled; + + // A running tool keeps the inactivity watchdog re-armed, so 20 silent minutes do not + // settle this run on their own. + yield* TestClock.adjust("20 minutes"); + yield* TestClock.adjust("11 minutes"); + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal( + terminal?.type === "turn.terminal" && terminal.status, + "completed", + "the bounded hold finalizes the turn instead of leaving it running forever", + ); + assert.equal(terminal?.type === "turn.terminal" && terminal.failure, null); + assert.lengthOf(offers, 0, "a silent command produces no wake on its own"); + const commandItem = [...prompt, ...run].findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.isTrue( + commandItem?.type === "turn_item.updated" && commandItem.turnItem.status === "completed", + "the silent command is no longer left as live activity on a settled run", + ); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps a silent scheduled wake in its run past the command hold bound", () => + Effect.gen(function* () { + const { usage, offers, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + initialToolCalls: [ + { + sessionUpdate: "tool_call", + toolCallId: "call_schedule", + kind: "other", + title: "Run schedule", + status: "in_progress", + rawInput: { DurationSeconds: 3600, Prompt: "Continue the task" }, + }, + ], + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + yield* TestClock.adjust("61 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call_schedule", + status: "completed", + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Picked the task back up." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include( + JSON.stringify(run), + "Picked the task back up.", + "the wake reply stays in the run", + ); + assert.lengthOf(offers, 0); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps an unanswered question open past the command hold bound", () => + Effect.gen(function* () { + const { command, usage, send, startTurn, until, throughPromptSettled, requestPermission } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + yield* throughPromptSettled; + const question = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { toolCallId: "interaction_1", kind: "other", title: "Which port?" }, + options: [ + { optionId: "3000", name: "3000", kind: "allow_once" }, + { optionId: "8080", name: "8080", kind: "allow_once" }, + ], + }, + { requestId: "question-1", method: "session/request_permission" }, + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* TestClock.adjust("31 minutes"); + yield* Fiber.interrupt(question); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include(JSON.stringify(run), "Here is the chart.", "the question kept the run open"); + }).pipe(Effect.provide(layerSession)), + ); + // Command 2 finishes during reply 1; agy dequeues command 2 after reply 1's usage_update and // needs >3 s before streaming reply 2. Wait for reply 2 (bounded by the 2-minute quiet limit), // but still finalize at 3 s when both commands were batched into reply 1. diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..c20afa04e31b8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -41,6 +41,7 @@ import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTur import { antigravityApprovalOptions, antigravityToolOutlivesPrompt, + antigravityCommandOutlivesPrompt, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, @@ -244,6 +245,12 @@ export function makeAntigravityAcpAdapterFlavor( wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, toolOutlivesPrompt: antigravityToolOutlivesPrompt, + // agy sometimes loses the terminal update or wake for a background command, which would + // hold the turn in Working forever. 30 minutes still leaves long commands room. + postSettleCommandHold: { + timeout: "30 minutes", + isCommand: antigravityCommandOutlivesPrompt, + }, // session/cancel ends the agent's running commands, so only Stop sends it once the prompt // has ended. A message sent while a command runs leaves the command alone. preserveRuntimeOnSettledInterrupt: true, diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index c718667dcf42e..2e59a78e376b4 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -55,6 +55,12 @@ const ANTIGRAVITY_SCHEDULE_TITLES = new Set(["Run schedule", "Running schedule"] */ export function antigravityToolOutlivesPrompt(toolCall: AcpToolCallState): boolean { if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return true; + return antigravityCommandOutlivesPrompt(toolCall); +} + +/** A non-daemon command the agent awaits; unlike a schedule, it reports progress while it runs. */ +export function antigravityCommandOutlivesPrompt(toolCall: AcpToolCallState): boolean { + if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return false; const input = toolCall.data.rawInput; return toolCall.kind === "execute" && !(Predicate.isObject(input) && input.IsDaemon === true); } diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 21fe311588906..908c99e4eaeb3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -637,6 +637,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -2742,7 +2751,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4274,11 +4288,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -8835,6 +8853,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -9265,6 +9316,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9665,6 +9717,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { From 5ddcc2598d0338614c2b2ea84da9470fd16be0da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:31:10 -0800 Subject: [PATCH 75/96] fix(desktop): WSL is not offered or started when only the Windows install stub exists (#40918) --- .../src/wsl/DesktopWslEnvironment.test.ts | 42 ++++++++++++++++++- apps/desktop/src/wsl/DesktopWslEnvironment.ts | 42 ++++++++++++++++++- 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index a563b6a4ee3a7..470091f334fb7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -555,8 +555,40 @@ describe("parseResolvedPath", () => { // Path.layer joins with POSIX separators here, so the test windir is a POSIX path. const WSL_EXE = "/windows/System32/wsl.exe"; +const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; +const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; + +const registrySpawner = (keys: ReadonlyArray) => + ChildProcessSpawner.make((command) => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode( + command._tag === "StandardCommand" && + command.command === "reg.exe" && + keys.some((key) => command.args.includes(key)) + ? 0 + : 1, + ), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); -const isAvailable = (policy?: Parameters[0]) => +const isAvailable = ( + policy?: Parameters[0], + serviceKeys: ReadonlyArray = [STORE_SERVICE], +) => makeIsAvailable("win32", "/windows").pipe( Effect.provide( Layer.mergeAll( @@ -565,9 +597,17 @@ const isAvailable = (policy?: Parameters[ DesktopManagedPolicy.layerTest(policy), ), ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, registrySpawner(serviceKeys)), ); describe("makeIsAvailable", () => { + it.effect("needs a registered WSL service, not just the System32 install stub", () => + Effect.gen(function* () { + assert.isFalse(yield* isAvailable(undefined, [])); + assert.isTrue(yield* isAvailable(undefined, [INBOX_SERVICE])); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f1d2fccde537b..9d9540a65dc7d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1119,13 +1119,50 @@ const getUserHomeImpl = ( Effect.orElseSucceed(() => Option.none()), ); +// Store/MSI WSL registers WSLService and inbox WSL registers LxssManager; either key means installed. +const WSL_SERVICE_KEYS = [ + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", +] as const; +const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); + +const wslServiceRegistered = Effect.scoped( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const registered = yield* Effect.forEach( + WSL_SERVICE_KEYS, + (key) => + spawner + .spawn( + ChildProcess.make("reg.exe", ["query", key], { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + killSignal: "SIGTERM", + forceKillAfter: PROCESS_TERMINATE_GRACE, + }), + ) + .pipe(Effect.flatMap((handle) => handle.exitCode)), + { concurrency: "unbounded" }, + ); + return registered.some((exitCode) => (exitCode as unknown as number) === 0); + }), +).pipe( + Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.orElseSucceed(() => false), +); + export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* ( platform: NodeJS.Platform, windir: string, ): Effect.fn.Return< boolean, never, - FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy + | FileSystem.FileSystem + | Path.Path + | DesktopManagedPolicy.DesktopManagedPolicy + | ChildProcessSpawner.ChildProcessSpawner > { if (platform !== "win32") return false; const path = yield* Path.Path; @@ -1134,6 +1171,8 @@ export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable" if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) { return false; } + // System32\wsl.exe is also an install stub on Windows without WSL, so check for its service. + if (!(yield* wslServiceRegistered)) return false; // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none. return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( Effect.map((found) => found === undefined), @@ -1245,6 +1284,7 @@ export const layer = Layer.effect( // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O. const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, environment.path), Effect.provideService( DesktopManagedPolicy.DesktopManagedPolicy, From ad446450e1cd66763cf03ed5c4b012913826f5d7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:33:25 -0800 Subject: [PATCH 76/96] fix(server): idle /ws connections behind a reverse proxy no longer drop every 60s (#40932) --- apps/server/src/socketHeartbeat.test.ts | 39 +++++++++++++++++++++++++ apps/server/src/socketHeartbeat.ts | 27 +++++++++++++++++ apps/server/src/ws.ts | 30 ++++++++++--------- 3 files changed, 82 insertions(+), 14 deletions(-) create mode 100644 apps/server/src/socketHeartbeat.test.ts create mode 100644 apps/server/src/socketHeartbeat.ts diff --git a/apps/server/src/socketHeartbeat.test.ts b/apps/server/src/socketHeartbeat.test.ts new file mode 100644 index 0000000000000..2cb002bbf8862 --- /dev/null +++ b/apps/server/src/socketHeartbeat.test.ts @@ -0,0 +1,39 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import * as Socket from "effect/socket/Socket"; +import * as TestClock from "effect/testing/TestClock"; + +import { + SOCKET_HEARTBEAT_FRAME, + SOCKET_HEARTBEAT_INTERVAL, + withSocketHeartbeat, +} from "./socketHeartbeat.ts"; + +describe("withSocketHeartbeat", () => { + it.effect("writes a heartbeat each interval until the writer's scope closes", () => + Effect.gen(function* () { + const written: Array = []; + const socket = withSocketHeartbeat( + Socket.make({ + reader: Effect.never, + writer: Effect.succeed({ + write: (chunk) => Effect.sync(() => void written.push(chunk)), + writeAll: (chunks) => Effect.sync(() => void written.push(...chunks)), + }), + }), + ); + const scope = yield* Scope.make(); + yield* Scope.provide(socket.writer, scope); + + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.deepStrictEqual(written, [SOCKET_HEARTBEAT_FRAME, SOCKET_HEARTBEAT_FRAME]); + + yield* Scope.close(scope, Exit.void); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.strictEqual(written.length, 2); + }), + ); +}); diff --git a/apps/server/src/socketHeartbeat.ts b/apps/server/src/socketHeartbeat.ts new file mode 100644 index 0000000000000..6ffd9c9cf785c --- /dev/null +++ b/apps/server/src/socketHeartbeat.ts @@ -0,0 +1,27 @@ +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Socket from "effect/socket/Socket"; + +// Reverse proxies close a socket after 60 seconds without upstream bytes +// (nginx proxy_read_timeout, AWS ALB), and a suspended client stops pinging. +export const SOCKET_HEARTBEAT_INTERVAL = Duration.seconds(20); + +// RPC clients count any decoded frame as liveness and ignore unsolicited pongs. +export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}'; + +/** Server side: writes a heartbeat frame on an interval for as long as the writer is open. */ +export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket { + return Socket.make({ + reader: socket.reader, + writer: Effect.tap(socket.writer, (writer) => + writer + .write(SOCKET_HEARTBEAT_FRAME) + .pipe( + Effect.delay(SOCKET_HEARTBEAT_INTERVAL), + Effect.forever, + Effect.ignore, + Effect.forkScoped, + ), + ), + }); +} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ddd07fcfad656..d1db4372ab871 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -201,6 +201,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; +import { withSocketHeartbeat } from "./socketHeartbeat.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; import { remoteSshDeviceHosts } from "./device/localSshDeviceHost.ts"; @@ -3826,20 +3827,21 @@ export const layer = Layer.unwrap( ), ), ); - const framedRpcWebSocketHttpEffect = url.value.searchParams.has( - SOCKET_FRAME_PARTS_QUERY_PARAM, - ) - ? rpcWebSocketHttpEffect.pipe( - Effect.provideService( - HttpServerRequest.HttpServerRequest, - // The RPC server upgrades the request itself, so its socket is - // wrapped through the request it reads. - Object.create(request, { - upgrade: { value: Effect.map(request.upgrade, splitLargeSocketFrames) }, - }), - ), - ) - : rpcWebSocketHttpEffect; + const splitFrames = url.value.searchParams.has(SOCKET_FRAME_PARTS_QUERY_PARAM); + const framedRpcWebSocketHttpEffect = rpcWebSocketHttpEffect.pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + // The RPC server upgrades the request itself, so its socket is + // wrapped through the request it reads. + Object.create(request, { + upgrade: { + value: Effect.map(request.upgrade, (socket) => + withSocketHeartbeat(splitFrames ? splitLargeSocketFrames(socket) : socket), + ), + }, + }), + ), + ); return yield* Effect.acquireUseRelease( sessions.markConnected(session.sessionId), () => From cc4bb17955287e5a7ad2a64b05f491879ee888fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:42:51 -0800 Subject: [PATCH 77/96] fix(server): thread reads no longer attribute T3 Code's compact-before-send /compact to the user (#40934) --- apps/server/src/cli/thread.ts | 7 +- .../OrchestratorMcpService.activity.test.ts | 129 ++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 4 +- 3 files changed, 138 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 09ee65c32172b..48d62fb4575b7 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -1024,7 +1024,12 @@ const threadShowCommand = Command.make("show", { const messages = yield* Effect.forEach(latest, (item) => readFullText(tools, threadId, item).pipe( Effect.map((text) => ({ - role: item.type === "user_message" ? "user" : "assistant", + role: + item.type === "assistant_message" + ? "assistant" + : item.createdBy === "system" + ? "system" + : "user", runId: item.runId, text, })), diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index a0953eb509e5f..cbe4be1e4b42f 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + MessageId, NodeId, type OrchestratorMcpThreadReadResult, type OrchestrationV2ThreadProjection, @@ -431,6 +432,134 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn }).pipe(Effect.provide(layer), Effect.runPromise); }); +it("readThread does not attribute the /compact T3 Code sends before a stale send to the user", async () => { + const compactRunId = RunId.make("run-mcp-compact-on-return"); + const sendRunId = RunId.make("run-mcp-held-send"); + const compactMessageId = MessageId.make("message-mcp-compact-on-return"); + const sendMessageId = MessageId.make("message-mcp-held-send"); + const projection = { + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [ + makeRun({ id: compactRunId, ordinal: 1, status: "completed" }), + makeRun({ id: sendRunId, ordinal: 2, status: "completed" }), + ], + visibleTurnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [ + { + id: compactMessageId, + threadId: parentThreadId, + runId: compactRunId, + role: "user", + text: "/compact", + attachments: [], + createdBy: "user", + creationSource: "web", + idleCompaction: "onReturn", + }, + { + id: sendMessageId, + threadId: parentThreadId, + runId: sendRunId, + role: "user", + text: "use webgpu", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + ], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + const userRow = (position: number, runId: RunId, messageId: MessageId, text: string) => ({ + position, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make(`turn-item-mcp-user-${position}`), + item: { + type: "user_message", + runId, + messageId, + status: "completed", + title: null, + text, + attachments: [], + updatedAt: now, + }, + }); + const rows = [ + userRow(0, compactRunId, compactMessageId, "/compact"), + { + position: 1, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make("turn-item-mcp-compaction"), + item: { + type: "compaction", + runId: compactRunId, + status: "completed", + title: null, + summary: "Context compacted", + updatedAt: now, + }, + }, + userRow(2, sendRunId, sendMessageId, "use webgpu"), + ]; + + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getTimelinePage: () => + Effect.succeed({ + items: rows as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"], + totalItems: rows.length, + hasMore: false, + hasEarlier: false, + }), + getThreadRecords: () => Effect.succeed(projection), + getProjectThreadRecords: () => Effect.succeed(projection), + getRunCount: () => Effect.succeed(projection.runs.length), + getThreadShell: () => + Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({ + list: () => Effect.succeed({ tasks: [] }), + } satisfies Partial), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + } satisfies Partial), + NodeCrypto.layer, + ), + ), + ); + + await Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + for (const view of ["activity", "messages"] as const) { + const result = yield* service.readThread(makeScope(), { threadId: parentThreadId, view }); + const fromUser = result.items.filter( + (item) => item.type === "user_message" && item.createdBy === "user", + ); + expect(fromUser.map((item) => item.text)).toEqual(["use webgpu"]); + } + }).pipe(Effect.provide(layer), Effect.runPromise); +}); + it("readThread returns the newest items that fit the response budget", async () => { const projection = { thread: baseThread({ diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index f9ad32a6e1d3e..156555c74d695 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,6 +1,7 @@ import { CommandId, type RunId, + idleCompactionOf, isProviderAvailable, MessageId, type ModelSelection, @@ -1228,7 +1229,8 @@ function timelineItem(input: { ...(input.row.item.type === "subagent" ? { subagentId: input.row.item.subagentId } : {}), runId: input.row.item.runId, messageId, - createdBy: message?.createdBy ?? null, + createdBy: + message === undefined ? null : idleCompactionOf(message) ? "system" : message.createdBy, creationSource: message?.creationSource ?? null, ...(message?.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }), type: input.row.item.type, From 9de4ec1bfa0b222e71f8fc2ed71257c1c1d1a281 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:49:19 +0100 Subject: [PATCH 78/96] fix(web,mobile): @-file mentions show by name in message previews, not as raw links (#40924) --- .../threads/threadQueueControlPresentation.ts | 5 ++- .../src/components/chat/ComposerStashMenu.tsx | 5 ++- .../src/components/chat/QueuedRunsControl.tsx | 5 ++- .../components/sidebar/SidebarDraftBlock.tsx | 5 ++- .../src/operations/threadTitle.ts | 3 +- .../shared/src/composerInlineTokens.test.ts | 14 +++++++ packages/shared/src/composerInlineTokens.ts | 15 ++++++++ ...-message-shows-file-mention-by-name.e2e.ts | 37 +++++++++++++++++++ 8 files changed, 84 insertions(+), 5 deletions(-) create mode 100644 scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts index 8a6ed2e03085a..50a004d679003 100644 --- a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts +++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts @@ -5,6 +5,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = msg("Remove queued message"); @@ -43,7 +44,9 @@ export function resolveThreadQueueRowControls(input: { displayText: isAttachmentOnlyBootstrapPrompt(input.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(input.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(input.text, (reference) => reference.label), + ), ).trim(), isEditing, }; diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index c55d843510080..46e3fec307bf1 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -3,6 +3,7 @@ import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react"; import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { RelativeTime } from "../RelativeTime"; import { m, type MessageResolver } from "~/i18n/messages"; @@ -18,7 +19,9 @@ function missingImageCount(entry: PromptStashEntry): number { export function stashEntrySnippet(entry: PromptStashEntry, resolve: MessageResolver = m): string { const trimmed = assistantCitationsToPlainText( - replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + ), ) .trim() .replace(/\s+/g, " "); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index d8318b7279e7d..20ea71f88adcd 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -10,6 +10,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { parseGoalCommand, type ChatAttachment as ContractChatAttachment, @@ -272,7 +273,9 @@ export function QueuedRunsControl({ const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(item.text, (reference) => reference.label), + ), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; // The server decides on the agent's text, and a goal command can stop the turn. diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 4cb082a1f7ddd..e0b0d92a764ac 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -3,6 +3,7 @@ import type { ContextMenuSource } from "@t3tools/contracts"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { T, useGT } from "gt-react"; import { SquarePenIcon, XIcon } from "lucide-react"; import { @@ -85,7 +86,9 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const gt = useGT(); const promptPreview = assistantCitationsToPlainText( - replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + ), ) .trim() .split("\n", 1)[0] ?? ""; diff --git a/packages/client-runtime/src/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.ts index 0f57de34036a5..bb1fcd7648dbf 100644 --- a/packages/client-runtime/src/operations/threadTitle.ts +++ b/packages/client-runtime/src/operations/threadTitle.ts @@ -3,6 +3,7 @@ import type { MFunctionType } from "gt-i18n/types"; import type { ChatAttachment } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { truncate } from "@t3tools/shared/String"; import { collectComposerModelMentions } from "../composerModelMentions.ts"; @@ -45,7 +46,7 @@ export function threadTitleTextFromPrompt( return reference.label; }); return ( - normalizeTitleSeed(modelMentionsAsSlugs(prose)) || + normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) || (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "") ); } diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index 5317347aad13b..c8c17b84a9b7b 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { collectComposerInlineTokens as collectWithoutMath, type CollectComposerInlineTokensOptions, + composerFileLinksToPlainText, composerMathRanges, } from "./composerInlineTokens.ts"; import { markdownMathRanges } from "./markdownMath.ts"; @@ -230,3 +231,16 @@ describe("collectComposerInlineTokens", () => { ).toEqual(["$x_i$"]); }); }); + +describe("composerFileLinksToPlainText", () => { + it("shows file mentions by name and leaves other links as written", () => { + const mentions = ["src/foo.ts", ".gitignore", "pkg/__init__.py", "docs/My File (draft).md"] + .map(serializeComposerFileLink) + .join(" "); + expect(composerFileLinksToPlainText(`Review ${mentions}`)).toBe( + "Review foo.ts .gitignore __init__.py My File (draft).md", + ); + const links = "See [docs](https://example.com) and [the config](src/config.ts)"; + expect(composerFileLinksToPlainText(links)).toBe(links); + }); +}); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index b11a42b74a945..80a1b4d6916ae 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,3 +1,5 @@ +import { fileBasename } from "./path.ts"; + /** The formulas a Markdown parser finds in text, as source offsets. */ export type FindMathRanges = ( text: string, @@ -173,3 +175,16 @@ export function collectComposerInlineTokens( ) .sort((left, right) => left.start - right.start); } + +/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */ +export function composerFileLinksToPlainText(text: string): string { + let result = ""; + let cursor = 0; + // The composer reads a link as a mention only before whitespace, so one may end the text. + for (const token of collectMentionTokens(`${text} `)) { + if (!token.source.startsWith("[")) continue; + result += text.slice(cursor, token.start) + fileBasename(token.value); + cursor = token.end; + } + return result + text.slice(cursor); +} diff --git a/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts new file mode 100644 index 0000000000000..8ee5453bbba20 --- /dev/null +++ b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A queued message shows its @-file mention by name, not as a raw link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/foo.ts": "export {};\n" }); + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @foo"); + await screen.getByRole("option", "foo.ts", { exact: false }).tap(); + await expect(composer).toContainText("foo.ts"); + + // The showcase recording streams for several seconds, long enough to queue behind its turn. + await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show me again"])); + await screen.getByText("Working for", { exact: false }).waitFor(); + // Enter steers by default; the alternate send queues. + await browser.keyboard.press("ControlOrMeta+Enter"); + + const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent"); + await queued.waitFor(); + // Read the row once: the queued message sends, and its row goes, when the turn ends. + const text = await queued.textContent(); + await app.screenshot("queued-row"); + expect(text).toContain("Review foo.ts"); + }, +); From 7ddc81d639aa75ca6e0cbffb0f394ea3f0d83308 Mon Sep 17 00:00:00 2001 From: Matthew Waters Date: Sun, 22 Nov 2026 17:10:23 +0000 Subject: [PATCH 79/96] fix(web): tool calls stay grouped after a usage-limit pause again (#40905) --- apps/web/src/components/ChatView.tsx | 6 +++++ .../chat/MessagesTimeline.logic.test.ts | 24 ++++++++++++++++++- .../components/chat/MessagesTimeline.logic.ts | 11 +++++++-- .../src/components/chat/MessagesTimeline.tsx | 3 +++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d17af4f620755..4f1d764ffef29 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1085,6 +1085,11 @@ export default function ChatView(props: ChatViewProps) { recovery: activeThreadShell?.limitRecovery, snoozedUntil: activeThreadShell?.snoozedUntil, }); + // The run whose limit rows client-runtime hides (deriveUsageLimitNoticeRows). + const usageLimitRunId = + serverRuntime?.status === "failed" && serverRuntime.lastErrorClass === "usage_limit" + ? (serverLatestRun?.runId ?? null) + : null; const timelineThreadError = limitRecoveryRun !== null && visibleThreadError === serverRuntime?.lastError ? null @@ -3644,6 +3649,7 @@ export default function ChatView(props: ChatViewProps) { listRef={legendListRef} runs={serverProjection?.runs ?? []} latestRun={activeActivityRun} + usageLimitRunId={usageLimitRunId} announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])} detailBehindShell={isDetailBehindShell( activeLatestRun, diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 0a703a675f0ac..76dc0aa6471bf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -4744,7 +4744,29 @@ describe("failed turn transcript", () => { ); expect(work.at(-1)?.detail).toBe("The provider stopped this turn.\nRetry later."); expect(work.at(-1)?.createdAt).toBe("2026-09-20T12:00:00.000Z"); - if (isLatest) return; + if (isLatest) { + // The recovery notice hides the failure row; the run's work stays grouped. + const noticeRows = deriveMessagesTimelineRows({ + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items.filter((row) => row.item.type !== "error"), + optimisticMessages: [], + }), + latestRun: { + runId, + status: "failed", + startedAt: DateTime.formatIso(at), + completedAt: DateTime.formatIso(at), + }, + usageLimitRunId: runId, + isWorking: false, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(noticeRows.find((row) => row.kind === "work-toggle")).toEqual( + expect.objectContaining({ hiddenCount: 3, expanded: false }), + ); + return; + } const entriesWithoutTools = deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: items.filter((row) => row.item.type !== "command_execution"), optimisticMessages: [], diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index b00a48185b9db..2d920ad816277 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1056,8 +1056,9 @@ function failedTimelineRunIds( function itemizedFailedRunIds( entries: ReadonlyArray, failedRunIds: ReadonlySet, + usageLimitRunId: RunId | null, ) { - const usageLimited = new Set(); + const usageLimited = new Set(usageLimitRunId ? [usageLimitRunId] : []); const otherFailures = new Set(); for (const entry of entries) { const item = timelineEntryFailedItem(entry); @@ -1612,6 +1613,8 @@ export function deriveMessagesTimelineRows( timelineEntries: ReadonlyArray; pendingApprovalRequestIds?: ReadonlySet; latestRun?: TimelineLatestRun | null; + /** The usage-limited run whose failure row the recovery notice replaces. */ + usageLimitRunId?: RunId | null; runningRunId?: RunId | null; expandedRunIds?: ReadonlySet; expandedAttemptIds?: ReadonlySet; @@ -1663,7 +1666,11 @@ export function deriveMessagesTimelineRows( const nextRows: MessagesTimelineRow[] = []; const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries); const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null); - const itemizedRunIds = itemizedFailedRunIds(timelineEntries, failedRunIds); + const itemizedRunIds = itemizedFailedRunIds( + timelineEntries, + failedRunIds, + input.usageLimitRunId ?? null, + ); const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries); const retainedAssistantReplyIds = retainedAssistantReplyEntryIds(timelineEntries); const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 89cc3f8701c55..fe60471993e36 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -257,6 +257,7 @@ interface MessagesTimelineProps { listRef: React.RefObject; timelineEntries: ReadonlyArray; latestRun: TimelineLatestRun | null; + usageLimitRunId?: RunId | null; /** The run the screen reader announcer follows; see announcedRun. */ announcedRun?: { readonly runId: RunId; readonly status: TimelineLatestRun["status"] } | null; /** See isDetailBehindShell. */ @@ -381,6 +382,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ activeFindMatch = null, findNavigationId = 0, latestRun, + usageLimitRunId = null, announcedRun = null, detailBehindShell = false, runningRunId = null, @@ -748,6 +750,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ timelineEntries, pendingApprovalRequestIds, latestRun, + usageLimitRunId, runningRunId, expandedRunIds: visibleExpandedRunIds, expandedAttemptIds: visibleExpandedAttemptIds, From ec35ad6618ea8ca72069b3f35198786deabb550a Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:00:38 +0100 Subject: [PATCH 80/96] fix(server): t3 doctor no longer reports a database just under 1 GiB as "1024.0 MiB" (#40952) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> --- apps/server/src/cli/doctor.test.ts | 28 ++++++++++++++++++++++++++++ apps/server/src/cli/doctor.ts | 14 +++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/apps/server/src/cli/doctor.test.ts b/apps/server/src/cli/doctor.test.ts index 6315378d07cb8..44dfd1bc27eff 100644 --- a/apps/server/src/cli/doctor.test.ts +++ b/apps/server/src/cli/doctor.test.ts @@ -8,6 +8,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as TestClock from "effect/testing/TestClock"; +import * as TestConsole from "effect/testing/TestConsole"; import * as BootService from "../cloud/bootService.ts"; import { runDoctor } from "./doctor.ts"; @@ -118,6 +119,33 @@ it.effect( }).pipe(Effect.provide(layerHost)), ); +it.effect("reports sizes just under the next unit in that unit", () => + Effect.gen(function* () { + yield* runDoctor( + { dbPath: "/test/statev2.sqlite", serverRuntimeStatePath: "/test/server-runtime.json" }, + { fix: false, dryRun: true }, + ).pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BootService.BootService)({}), + Layer.mock(DatabaseMaintenance)({ + inspect: () => + Effect.succeed({ + databaseBytes: 1024 ** 3 - 4096, + reclaimableBytes: 1024 ** 2 - 512, + incrementalVacuumEnabled: true, + legacyDatabaseBytes: null, + legacyOnlyRecords: null, + }), + }), + ), + ), + ); + const [summary] = yield* TestConsole.logLines; + assert.strictEqual(summary, "Database: 1.00 GiB, 1.0 MiB reclaimable."); + }).pipe(Effect.provide(Layer.merge(layerHost, TestConsole.layer))), +); + it.effect("warns how long reclaiming can take and reports each step with its elapsed time", () => Effect.gen(function* () { const output: string[] = []; diff --git a/apps/server/src/cli/doctor.ts b/apps/server/src/cli/doctor.ts index 50cd852e5b4b1..60af29ac41e7b 100644 --- a/apps/server/src/cli/doctor.ts +++ b/apps/server/src/cli/doctor.ts @@ -13,12 +13,16 @@ import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntim import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; -const formatBytes = (bytes: number) => - bytes >= 1024 ** 3 +// Pick the unit after rounding, so a size just under 1 GiB reads "1.00 GiB", not "1024.0 MiB". +const formatBytes = (bytes: number) => { + const mebibytes = (bytes / 1024 ** 2).toFixed(1); + const kibibytes = Math.ceil(bytes / 1024); + return Number(mebibytes) >= 1024 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB` - : bytes >= 1024 ** 2 - ? `${(bytes / 1024 ** 2).toFixed(1)} MiB` - : `${Math.ceil(bytes / 1024)} KiB`; + : kibibytes >= 1024 + ? `${mebibytes} MiB` + : `${kibibytes} KiB`; +}; const formatElapsed = (nanos: bigint) => { const seconds = Number(nanos / 1_000_000_000n); From 69720261214c047e583b494675ea9624bbe3a00a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:02:10 +0100 Subject: [PATCH 81/96] fix(web): show clone failure after progress is dismissed (#40951) Co-authored-by: Julius Marminge --- .../ProjectCloneToastCoordinator.tsx | 57 +++++---- ...e-failure-after-dismissing-progress.e2e.ts | 113 ++++++++++++++++++ 2 files changed, 148 insertions(+), 22 deletions(-) create mode 100644 scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx index 846644c537a12..778c195e2d29e 100644 --- a/apps/web/src/components/ProjectCloneToastCoordinator.tsx +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -45,6 +45,8 @@ interface TrackedToast { readonly toastId: ReturnType; readonly renderedKey: string; readonly phase: ProjectCloneSnapshot["phase"]; + readonly startedAt: ProjectCloneSnapshot["startedAt"]; + readonly closed?: true; } function renderKey(clone: ProjectCloneSnapshot): string { @@ -98,6 +100,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI seen.add(clone.projectId); const key = renderKey(clone); const tracked = toasts.current.get(clone.projectId); + const sameAttempt = tracked?.startedAt === clone.startedAt; const name = projectCloneDisplayName(clone); const closeToast = () => { const current = toasts.current.get(clone.projectId); @@ -111,7 +114,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } - if (tracked?.renderedKey === key) continue; + if (sameAttempt && tracked.renderedKey === key) continue; if ( isProjectCloneToastSilenced(ref) && (clone.phase === "running" || clone.phase === "done") @@ -119,6 +122,34 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } + if ( + sameAttempt && + tracked.closed && + (tracked.phase !== "running" || clone.phase !== "failed") + ) { + continue; + } + + const showToast = (options: ReturnType) => { + const rendered = { renderedKey: key, phase: clone.phase, startedAt: clone.startedAt }; + if (tracked && !tracked.closed) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { toastId: tracked.toastId, ...rendered }); + return; + } + + const toastId = toastManager.add({ + ...options, + // Updates to a closing toast are ignored, even before it has been removed. + onClose: () => { + const current = toasts.current.get(clone.projectId); + if (current?.toastId === toastId) { + toasts.current.set(clone.projectId, { ...current, closed: true }); + } + }, + }); + toasts.current.set(clone.projectId, { toastId, ...rendered }); + }; if (clone.phase === "running") { const options = stackedThreadToast({ @@ -136,13 +167,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" }); - } + showToast(options); continue; } @@ -161,13 +186,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" }); - } + showToast(options); continue; } @@ -199,13 +218,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase }); - } + showToast(options); } for (const [projectId, tracked] of toasts.current) { diff --git a/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts new file mode 100644 index 0000000000000..739497a827757 --- /dev/null +++ b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts @@ -0,0 +1,113 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fixture holds Git's HTTP request open. +import * as NodeHttp from "node:http"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { ProjectId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Stream from "effect/Stream"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +test( + "Dismissing clone progress leaves the later failure notification visible", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Other work", messages: ["Start"] }); + const gitRequest = Promise.withResolvers(); + const remote = NodeHttp.createServer((_request, response) => { + gitRequest.resolve(response); + }); + + try { + await new Promise((resolve) => remote.listen(0, "127.0.0.1", resolve)); + const address = remote.address(); + if (!address || typeof address === "string") throw new Error("No Git fixture port"); + const projectId = ProjectId.make( + await runPromise( + SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), + Effect.provide(NodeCrypto.layer), + ), + ), + ); + const name = "pending-clone"; + const origin = app.baseUrl ?? ""; + await t3.open(thread); + await screen.getByText("Start", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + const createdAt = DateTime.formatIso(yield* DateTime.now); + yield* client["projectClone.start"]({ + projectId, + title: name, + createdAt, + remoteUrl: `http://127.0.0.1:${address.port}/${name}.git`, + destinationPath: `${project}/../${name}`, + }); + }).pipe(Effect.scoped), + ); + const response = await gitRequest.promise; + + const toastTitle = (title: string) => + browser.locator(`[data-slot="toast-title"]:text-is("${title}")`); + const dismiss = async (title: string) => { + await browser + .locator( + `[data-position]:has(> div > [data-slot="toast-close"]):has([data-slot="toast-title"]:text-is("${title}"))`, + ) + .getByRole("button", "Dismiss notification", { exact: true }) + .tap(); + await toastTitle(title).waitFor({ state: "detached" }); + }; + const progress = toastTitle(`Cloning ${name}`); + const failure = toastTitle(`Failed to clone ${name}`); + + await progress.waitFor(); + await dismiss(`Cloning ${name}`); + + response.writeHead(404).end(); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client.subscribeProjectClones({}).pipe( + Stream.filter((clones) => + clones.some((clone) => clone.projectId === projectId && clone.phase === "failed"), + ), + Stream.runHead, + ); + }).pipe(Effect.scoped, Effect.timeout("10 seconds")), + ); + + try { + await expect(failure).toBeVisible(); + } finally { + await app.screenshot("after-background-clone-fails"); + } + + await dismiss(`Failed to clone ${name}`); + + const retryRequest = Promise.withResolvers(); + remote.once("request", (_request, response) => retryRequest.resolve(response)); + const retry = await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + return yield* client["projectClone.retry"]({ projectId }); + }).pipe(Effect.scoped), + ); + await expect(retry.applied).toBe(true); + const retryResponse = await retryRequest.promise; + await expect(progress).toBeVisible(); + retryResponse.writeHead(404).end(); + await expect(failure).toBeVisible(); + } finally { + remote.close(); + remote.closeAllConnections(); + } + }, +); From bc13afaa3c42be200956b6181d21642883d77903 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:31:53 +0100 Subject: [PATCH 82/96] Invalidate pending theme imports when a replacement is too large (#40965) Co-authored-by: Julius Marminge --- .../ThemeImportDialog.browser.test.tsx | 52 +++++++++++++++ .../components/settings/ThemeImportDialog.tsx | 5 +- ...-theme-file-supersedes-earlier-read.e2e.ts | 64 +++++++++++++++++++ 3 files changed, 119 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index 8eecf79f5d33a..fd5b90f9c6c19 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -157,6 +157,58 @@ it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => { ); }); +it.each(["failed read", "batch install"])( + "keeps the oversized replacement warning after a superseded %s", + async (earlierImport) => { + using _themes = isolateThemes(); + await using _screen = await render( + {}} + onImported={() => true} + onImportedMany={() => {}} + />, + ); + const earlierRead = Promise.withResolvers(); + const readStarted = Promise.withResolvers(); + const earlierFile = Object.assign(themeFile("Dusk"), { + text() { + readStarted.resolve(); + return earlierRead.promise; + }, + }); + const input = document.querySelector('input[type="file"]')!; + const files = new DataTransfer(); + if (earlierImport === "batch install") files.items.add(themeFile("Dawn")); + files.items.add(earlierFile); + await act(async () => { + input.files = files.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + await readStarted.promise; + }); + await expect.element(page.getByRole("button", { name: "Readingโ€ฆ" })).toBeDisabled(); + await userEvent.upload( + input, + new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }), + ); + const warning = page.getByText(/^That file is/); + await expect.element(warning).toBeVisible(); + + await act(async () => { + if (earlierImport === "batch install") { + earlierRead.resolve(JSON.stringify(theme("Dusk"))); + } else { + earlierRead.reject(new Error("Could not read Dusk")); + } + await earlierRead.promise.catch(() => {}); + }); + + expect(getCustomThemes().map((theme) => theme.label)).toEqual([]); + expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/); + await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled(); + }, +); + function themeJsonc(name: string, background: string) { return `{ // VS Code themes use JSONC even with a .json extension. diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index 189560efdee9e..aeac23821884f 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -233,19 +233,20 @@ function ThemeImportBody({ const [isReading, setIsReading] = useState(false); const [isDropTarget, setIsDropTarget] = useState(false); const [conflicts, setConflicts] = useState | null>(null); - // A newer read supersedes an older one still in flight. + // A new file selection supersedes a pending import even if the selection is rejected. const importRequestRef = useRef(0); const isCurrentRequest = (requestId: number) => requestId === importRequestRef.current && !signal.aborted; const readThemeFile = async (file: ImportableThemeFile) => { + const requestId = ++importRequestRef.current; const oversized = describeOversizedThemeFile(file.size); if (oversized) { + setIsReading(false); setError(oversized); return; } - const requestId = ++importRequestRef.current; setIsReading(true); const fileText = await settlePromise(() => file.text()); if (!isCurrentRequest(requestId)) return; diff --git a/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts new file mode 100644 index 0000000000000..49186eaa4429a --- /dev/null +++ b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts @@ -0,0 +1,64 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +declare global { + interface Window { + releaseOldThemeRead: () => void; + } +} + +test( + "An earlier theme file cannot become the draft after its replacement is rejected", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + + await browser.evaluate(() => { + const target = document.querySelector('input[type="file"]')?.parentElement; + if (!target) throw new Error("No theme file drop target"); + + const gate = Promise.withResolvers(); + const theme = JSON.stringify({ + version: 1, + name: "Earlier theme", + appearance: "dark", + colors: { accent: "#734ee4" }, + }); + const first = new File([theme], "earlier.json", { type: "application/json" }); + const text = File.prototype.text; + File.prototype.text = function () { + if (this.name === first.name) return gate.promise.then(() => theme); + return text.call(this); + }; + window.releaseOldThemeRead = gate.resolve; + + const drop = (file: File) => { + const files = new DataTransfer(); + files.items.add(file); + target.dispatchEvent( + new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }), + ); + }; + drop(first); + drop(new File([" ".repeat(300_000)], "replacement.json", { type: "application/json" })); + return null; + }); + + await dialog.getByText(/That file is/).waitFor(); + await browser.evaluate(async () => { + window.releaseOldThemeRead(); + // Let the earlier file response and its React update reach the dialog. + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + return null; + }); + await app.screenshot("dialog-after-earlier-theme-read-finishes"); + await expect(dialog.getByRole("button", "Add theme", { exact: true })).toBeDisabled(); + }, +); From 4e1c1fea7aa21189b2b363aefd38892377625307 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:06:09 +0100 Subject: [PATCH 83/96] fix(mobile): show linked thread history page errors (#40973) --- .../threads/LinkedThreadSheet.test.tsx | 134 ++++++++++++++++++ .../features/threads/LinkedThreadSheet.tsx | 21 ++- apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/mobile/vite.config.ts | 1 + 13 files changed, 164 insertions(+), 2 deletions(-) create mode 100644 apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx new file mode 100644 index 0000000000000..748fb333239a0 --- /dev/null +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx @@ -0,0 +1,134 @@ +import { expect, it } from "@effect/vitest"; +import { + followLinkedThread, + type LinkedThreadView as LinkedThreadState, +} from "@t3tools/client-runtime/linked-thread"; +import { EnvironmentId, type OrchestrationV2ThreadHistoryPage } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { vi } from "vite-plus/test"; + +import { v2Projection } from "../../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures"; +import { useLinkedThreadView } from "../../state/linkedThread"; +import { LinkedThreadView } from "./LinkedThreadSheet"; + +vi.mock("@react-navigation/native", () => ({ + StackActions: {}, + useIsFocused: () => true, + useNavigation: () => ({}), +})); +vi.mock("react-native", () => { + const Container = ({ children }: { children: ReactNode }) =>
{children}
; + return { + AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) }, + Platform: { OS: "android" }, + Pressable: Container, + ScrollView: Container, + Text: Container, + View: Container, + }; +}); +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) })); +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); +vi.mock("../../components/ui/Button", () => ({ + Button: (props: { label: string; disabled?: boolean; onPress: () => void }) => ( + + ), +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../native/SelectableMarkdownText", () => ({ SelectableMarkdownText: () => null })); +vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) })); +vi.mock("../../state/linkedThread", () => ({ + useConnectLinkedEnvironment: () => ({ state: { phase: "idle" } }), + useLinkedThreadView: vi.fn(), +})); +vi.mock("../../state/peerLinks", () => ({ peerLinkEnvironment: {} })); +vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({}) })); +vi.mock("../files/FileMarkdownPreview", () => ({ useMarkdownPreviewStyles: () => ({}) })); +vi.mock("./ReadOnlyComposerBar", () => ({ + ReadOnlyComposerBar: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("./thread-inspector-header", () => ({ ThreadInspectorHeader: () => null })); +vi.mock("./useOpenLinkedThread", () => ({ useOpenLinkedThread: () => undefined })); + +it.effect( + "shows a page error after Load earlier fails on an already disconnected linked chat", + () => + Effect.gen(function* () { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const target = { + viaEnvironmentId: EnvironmentId.make("via"), + environmentId: EnvironmentId.make("linked"), + threadId: v2Projection.thread.id, + label: "Linked test environment", + title: null, + }; + const warning = "Linked test environment is not answering this environment"; + const pageError = "Could not load earlier turns. Try again."; + const loadEarlier = () => + [...container.querySelectorAll("button")].find( + (button) => button.textContent === "Load earlier", + )!; + + try { + const unavailable = { _tag: "PeerLinkThreadReadError", reason: "unreachable" }; + const pages = + yield* Queue.unbounded< + Effect.Effect + >(); + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.make({ + kind: "snapshot", + snapshotSequence: 1, + projection: v2Projection, + historyCursor: "before-recent", + hasMoreHistory: true, + } as const).pipe(Stream.concat(Stream.fail(unavailable))), + historyPage: () => Queue.take(pages).pipe(Effect.flatten), + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + + const renderNext = Effect.gen(function* () { + const view = yield* Queue.take(views); + vi.mocked(useLinkedThreadView).mockReturnValue({ + view, + error: view.error ?? null, + retry() {}, + }); + act(() => root.render()); + }); + + yield* renderNext; // Initial snapshot. + yield* renderNext; // Connection warning. + expect(container.textContent).toContain(warning); + expect(container.textContent).not.toContain(pageError); + + act(() => loadEarlier().click()); + yield* renderNext; + yield* Queue.offer(pages, Effect.fail(unavailable)); + yield* renderNext; + expect(loadEarlier().parentElement?.textContent).toContain(pageError); + expect(container.textContent).toContain(warning); + + act(() => loadEarlier().click()); + yield* renderNext; + expect(container.textContent).not.toContain(pageError); + expect(loadEarlier().disabled).toBe(true); + } finally { + act(() => root.unmount()); + vi.unstubAllGlobals(); + } + }).pipe(Effect.scoped), +); diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index 0096c9d576a91..7ec2c4dac2cc8 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -286,6 +286,9 @@ export function LinkedThreadView(props: { const scroll = useRef>(null); // Follows new items only while the reader is already at the end. const atEnd = useRef(true); + const showHistoryError = + view !== null && view.thread.historyCursor !== null && view.history.failed; + const lastLayoutHadHistoryError = useRef(false); const working = projection !== null && isLinkedThreadWorking(projection); const connection = useConnectLinkedEnvironment(target); const connectState = connection.state; @@ -334,7 +337,12 @@ export function LinkedThreadView(props: { atEnd.current = contentSize.height - layoutMeasurement.height - contentOffset.y < 80; }} onContentSizeChange={() => { - if (atEnd.current) scroll.current?.scrollToEnd({ animated: false }); + // A page error can resize the top of a short feed whose reader is also near the end. + const historyErrorChanged = lastLayoutHadHistoryError.current !== showHistoryError; + lastLayoutHadHistoryError.current = showHistoryError; + if (atEnd.current && !historyErrorChanged) { + scroll.current?.scrollToEnd({ animated: false }); + } }} > {view === null || projection === null ? ( @@ -351,7 +359,7 @@ export function LinkedThreadView(props: { ) : ( <> {view.thread.historyCursor !== null ? ( - +