From 5793cadee461914c83f714cd71d279330e21036b Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 16:47:17 +0200 Subject: [PATCH 001/221] fix(server): workflows find a project named by its Windows folder (#41456) Co-authored-by: Julius Marminge --- .../src/workflows/WorkflowAgentLinks.test.ts | 51 +++++++++++++++---- .../src/workflows/WorkflowAgentLinks.ts | 14 ++++- apps/server/src/workflows/WorkflowAgents.ts | 4 +- .../src/workflows/WorkflowForge.test.ts | 21 ++++++++ 4 files changed, 76 insertions(+), 14 deletions(-) diff --git a/apps/server/src/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts index 92b7a4f7b2fff..8fcba6dc9f3f8 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.test.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -113,26 +113,55 @@ it.effect("starts a thread there by the project's folder, with the step's key as ); it.effect("registers a folder that is not a project there yet", () => + Effect.gen(function* () { + for (const [project, title] of [ + [input.project, "app"], + ["/work/team\\api", "team\\api"], + ["C:\\work\\app", "app"], + ]) { + const there = peer({ + t3_project_list: [{ projects: [], nextCursor: null }], + t3_project_create: [{ id: "p-new", workspaceRoot: project }], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start({ ...input, project }, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ); + assert.deepStrictEqual( + there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), + [ + ["t3_project_list", undefined], + ["t3_project_create", title], + ["t3_thread_launch", "p-new"], + ], + ); + } + }), +); + +it.effect("finds a Windows folder there however its separators are written", () => Effect.gen(function* () { const there = peer({ - t3_project_list: [{ projects: [], nextCursor: null }], - t3_project_create: [{ id: "p-new", workspaceRoot: "/work/app" }], + t3_project_list: [ + { projects: [{ id: "p-app", workspaceRoot: "C:\\work\\app" }], nextCursor: null }, + ], t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], }); yield* Effect.provide( Effect.flatMap(WorkflowAgentLinks.make, (links) => - links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + links.start( + { ...input, project: "C:/work/app" }, + "env-b", + "workflow:k", + EnvironmentId.make("env-a"), + ), ), there.layer, ); - assert.deepStrictEqual( - there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), - [ - ["t3_project_list", undefined], - ["t3_project_create", "app"], - ["t3_thread_launch", "p-new"], - ], - ); + assert.equal(there.calls.at(-1)?.arguments.projectId, "p-app"); }), ); diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts index 6a0836fc0162c..8d0bdc1d0c672 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -7,6 +7,11 @@ import { OrchestratorMcpThreadSendResult, OrchestratorMcpThreadWaitResult, } from "@t3tools/contracts"; +import { + fileBasename, + isWindowsDrivePath, + normalizeProjectPathForComparison, +} from "@t3tools/shared/path"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -77,6 +82,7 @@ export const make = Effect.gen(function* () { environment: string, path: string, ) { + const target = normalizeProjectPathForComparison(path); let cursor: number | null = 0; while (cursor !== null) { const page: Schema.Schema.Type = @@ -86,7 +92,9 @@ export const make = Effect.gen(function* () { ProjectToolkit.tools.t3_project_list.successSchema, { cursor, limit: 100 }, ); - const found = page.projects.find((project) => project.workspaceRoot === path); + const found = page.projects.find( + (project) => normalizeProjectPathForComparison(project.workspaceRoot) === target, + ); if (found !== undefined) return found.id; cursor = page.nextCursor; } @@ -104,7 +112,9 @@ export const make = Effect.gen(function* () { ) { const known = yield* listed(environment, path); if (known !== undefined) return known; - const title = path.split("/").findLast((part) => part.length > 0) ?? path; + const title = isWindowsDrivePath(path) + ? fileBasename(path) + : (path.split("/").findLast((part) => part.length > 0) ?? path); const created = yield* call( environment, "t3_project_create", diff --git a/apps/server/src/workflows/WorkflowAgents.ts b/apps/server/src/workflows/WorkflowAgents.ts index 674b72c69aa3d..834a781340269 100644 --- a/apps/server/src/workflows/WorkflowAgents.ts +++ b/apps/server/src/workflows/WorkflowAgents.ts @@ -4,6 +4,7 @@ import type { ProviderInteractionMode, RuntimeMode, } from "@t3tools/contracts"; +import { isWindowsDrivePath } from "@t3tools/shared/path"; import * as Context from "effect/Context"; import type * as Duration from "effect/Duration"; import type * as Effect from "effect/Effect"; @@ -67,7 +68,8 @@ export const launchOnContinue = new WorkflowAgentError({ }); /** A project named by its folder instead of its id. */ -export const isProjectPath = (project: string) => project.startsWith("/"); +export const isProjectPath = (project: string) => + project.startsWith("/") || isWindowsDrivePath(project); /** Where agent steps run. The server implements it with threads; tests stand in for it. */ export class WorkflowAgents extends Context.Service< diff --git a/apps/server/src/workflows/WorkflowForge.test.ts b/apps/server/src/workflows/WorkflowForge.test.ts index 58f9626423510..1d402227c57b4 100644 --- a/apps/server/src/workflows/WorkflowForge.test.ts +++ b/apps/server/src/workflows/WorkflowForge.test.ts @@ -85,6 +85,27 @@ it.effect("what a step does through the forge is kept against it, one key per th }).pipe(Effect.provide(forge)), ); +it.effect("a step can name its project by a Windows folder", () => + Effect.gen(function* () { + const { pullRequests } = yield* WorkflowForge.WorkflowForge; + const noted: Array = []; + const inStep = Context.make(StepReferences, { + note: (reference) => Effect.sync(() => void noted.push(reference)), + }); + for (const project of ["C:\\Users\\me\\app", "C:/Users/me/app"]) { + yield* Effect.provideContext( + pullRequests.act({ project, url: "https://github.com/Me/App/pull/7" }, "merge"), + inStep, + ); + } + const address = { projectId, host: "github.com", repository: "me/app", number: 7 }; + assert.deepStrictEqual( + noted.map((reference) => reference.address), + [address, address], + ); + }).pipe(Effect.provide(forge)), +); + it("a step's pull requests are the ones its thread was linked to while it ran", () => { const link = (number: number, linkedAt: string, source = "agent") => ({ host: "github.com", From fd0331ca9b1596ed7018c80f52b7e6730014f593 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 16:48:20 +0200 Subject: [PATCH 002/221] fix(client-runtime): a workflow reply with no space before the limit is cut at the limit (#41488) Co-authored-by: Julius Marminge --- packages/client-runtime/src/workflows.test.ts | 3 +++ packages/client-runtime/src/workflows.ts | 10 +++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/workflows.test.ts b/packages/client-runtime/src/workflows.test.ts index 9fce777fd5642..14991a1c65438 100644 --- a/packages/client-runtime/src/workflows.test.ts +++ b/packages/client-runtime/src/workflows.test.ts @@ -298,6 +298,9 @@ describe("workflowSaidStart", () => { expect(workflowSaidStart(said, 200)).toBeNull(); expect(workflowSaidStart(said, 40)).toBe("It is a real bug.\n\n**Where:** line 5."); expect(workflowSaidStart(said, 10)).toBe("It is a real bug."); + const unspaced = "这个问题出现在解析器中。".repeat(60); + expect(workflowSaidStart(unspaced, 10)).toBe("这个问题出现在解析器…"); + expect(workflowSaidStart("😀".repeat(30), 9)).toBe(`${"😀".repeat(4)}…`); }); }); diff --git a/packages/client-runtime/src/workflows.ts b/packages/client-runtime/src/workflows.ts index 3808f94703237..2a4eac6c00b45 100644 --- a/packages/client-runtime/src/workflows.ts +++ b/packages/client-runtime/src/workflows.ts @@ -700,7 +700,15 @@ export function workflowSaidStart(said: string, limit: number): string | null { kept = `${kept}\n\n${paragraph}`; } // One paragraph that runs on is cut at a word, which can still split markup but not a word. - if (kept.length > limit * 2) kept = `${kept.slice(0, kept.lastIndexOf(" ", limit))}…`; + // Text with no space before the limit, such as Chinese, is cut at the limit, never inside a + // surrogate pair. + if (kept.length > limit * 2) { + const space = kept.lastIndexOf(" ", limit); + const before = kept.charCodeAt(limit - 1); + const highSurrogateLast = before >= 0xd800 && before <= 0xdbff; + const end = space > 0 ? space : highSurrogateLast ? limit - 1 : limit; + kept = `${kept.slice(0, end)}…`; + } return kept === said ? null : kept; } From 9d6c750a75ba9d6763e9632b8b820b17f5ee9078 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:49:01 -0800 Subject: [PATCH 003/221] test(web): load history documents without re-evaluating the app graph (#41497) From 28c58b19b58b6e4f129da288190befa9fefe9192 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:52:35 -0800 Subject: [PATCH 004/221] fix(server): an unfinished control sequence no longer delays terminal output (#41420) Co-authored-by: viktorce --- apps/server/src/terminal/Manager.test.ts | 126 +++++++++++++++++++++++ apps/server/src/terminal/Manager.ts | 92 +++++++++++++---- 2 files changed, 197 insertions(+), 21 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 8af803db1fd8c..aa0953142aac9 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -3,6 +3,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { + DEFAULT_MAX_TERMINAL_BUFFER_BYTES, DEFAULT_TERMINAL_ID, ProjectId, ThreadId, @@ -488,6 +489,98 @@ it("restores bounded history across append compaction, clears and split Unicode" expect(persisted).toBe("z".repeat(maxBytes)); }); +it("stops holding a control sequence that outgrows its limit", () => { + const limit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; + // No final byte for a CSI and no terminator for a string. + const filler = "0123456789 123\r\n".repeat(64); + const fed = filler.repeat(Math.ceil(limit / filler.length) + 2); + // The terminal runs the line breaks inside a CSI while it waits for the final byte. + const lineBreaks = fed.replaceAll(/[^\r\n]/g, ""); + for (const { name, open, end, history } of [ + { name: "OSC, BEL", open: ["\u001b]0;"], end: ["\u0007"], history: "\u001b\\" }, + { + name: "OSC, split ST", + open: ["\u001b]0;"], + end: ["\u001b", "\\\u001b[31m"], + history: "\u001b\\\u001b[31m", + }, + // The last UTF-8 byte of U+20805 is 0x85, NEL, which ends the DCS and replays as ESC E. + { + name: "DCS, split code point", + open: ["\u001bPstuck"], + end: ["\ud842", "\udc05"], + history: "\u001b\\\u001bE", + }, + // The dropped CSI's ESC ended the title, so history ends it too. Its final byte would have + // made it a query that the replay answers. + { + name: "CSI after a title its ESC cuts short", + open: ["\u001b]0;title", "\u001b["], + end: ["\n6n"], + history: `\u001b]0;title\u001b\\${lineBreaks}\n`, + }, + { + name: "CSI, ESC", + open: ["\u001b["], + end: ["\n\u001b[31m"], + history: `\u001b\\${lineBreaks}\n\u001b[31m`, + }, + ]) { + let held = ""; + let visible = ""; + const feed = (data: string) => { + const sanitized = TerminalManager.sanitizeTerminalHistoryChunk(held, data); + held = sanitized.pendingControlSequence; + visible += sanitized.visibleText; + }; + + feed("before\n"); + for (const data of open) feed(data); + for (let offset = 0; offset < fed.length; offset += filler.length) { + feed(fed.slice(offset, offset + filler.length)); + } + expect(held.length, name).toBeLessThanOrEqual(3); + + for (const data of end) feed(data); + feed("after\n"); + expect(held, name).toBe(""); + expect(visible, name).toBe(`before\n${history}after\n`); + } + + // Held text of exactly the limit stays held, and a sequence that ends in the chunk where it + // passes the limit is kept whole. + for (const atLimit of ["\u001b]".padEnd(limit, "0"), "\u001b[".padEnd(limit, "0")]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", atLimit)).toEqual({ + visibleText: "", + pendingControlSequence: atLimit, + }); + const ended = `${atLimit}0${atLimit[1] === "]" ? "\u0007" : "m"}`; + expect(TerminalManager.sanitizeTerminalHistoryChunk("", ended)).toEqual({ + visibleText: ended, + pendingControlSequence: "", + }); + } + + // An escape sequence keeps its first four intermediates, the only ones libghostty reads. + const escape = '\u001b!"#$'; + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&")).toEqual({ + visibleText: "", + pendingControlSequence: escape, + }); + expect(TerminalManager.sanitizeTerminalHistoryChunk(escape, "%&B")).toEqual({ + visibleText: `${escape}%&B`, + pendingControlSequence: "", + }); + + // A completed escape sequence stays when another ESC follows it at once. + for (const kept of ["OLD\u001bc\u001b[31mNEW", "abc\u001b7\u001b[2;5HB\u001b8Z"]) { + expect(TerminalManager.sanitizeTerminalHistoryChunk("", kept)).toEqual({ + visibleText: kept, + pendingControlSequence: "", + }); + } +}); + it.layer( Layer.mergeAll( NodeServices.layer, @@ -1756,6 +1849,39 @@ it.layer( }), ); + it.effect("starts a snapshot inside the sequence the terminal has not finished", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const outputs = yield* Queue.unbounded(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" ? Queue.offer(outputs, undefined).pipe(Effect.asVoid) : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + const historyAfter = Effect.fnUntraced(function* (data: string) { + process.emitData(data); + yield* Queue.take(outputs); + return (yield* manager.open(openInput())).history; + }); + + expect(yield* historyAfter("A\u001b]0;ti")).toBe("A\u001b]0;ti"); + // A long string would push history out of the client's budget, so its payload is left out. + expect(yield* historyAfter("x".repeat(4_096))).toBe("A\u001b]"); + // Past the limit only the introducer is left to replay. + expect(yield* historyAfter("x".repeat(DEFAULT_MAX_TERMINAL_BUFFER_BYTES))).toBe( + "A\u001b\\\u001b]", + ); + expect(yield* historyAfter("\u0007B")).toBe("A\u001b\\B"); + + // Saved history has no live output to finish the sequence. + process.emitData("\u001b]0;open"); + yield* Queue.take(outputs); + yield* manager.close({ threadId: "thread-1" }); + expect(yield* readFileString(yield* historyLogPath(logsDir))).toBe("A\u001b\\B"); + }), + ); + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index e87ba67cf5837..92600d0a326a8 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -415,7 +415,7 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { worktreePath: session.worktreePath, status: session.status, pid: session.pid, - history: session.history.value(), + history: session.history.value() + unfinishedSequenceReplay(session), exitCode: session.exitCode, exitSignal: session.exitSignal, label: terminalWireLabel(session), @@ -1394,7 +1394,32 @@ function findEscapeSequenceEndIndex(input: string, start: number): number | null const HISTORY_SEQUENCE_START = /\u001b/; const NEXT_HISTORY_SEQUENCE_START = new RegExp(HISTORY_SEQUENCE_START.source, "g"); -function sanitizeTerminalHistoryChunk( +// Clients keep this much output and drop a sequence their trim cuts through, so none of them +// could replay a longer string or CSI whole. +const MAX_HELD_SEQUENCE_LENGTH = DEFAULT_MAX_TERMINAL_BUFFER_BYTES; +// ESC and four intermediates: libghostty ignores every intermediate past the fourth. +const MAX_HELD_ESCAPE_LENGTH = 5; +// Leads the held text of a string or CSI that outgrew its limit and stays out of history. Only its +// introducer is still held, with a final ESC or high surrogate that may begin its end. Other held +// text starts with ESC. +const OVERSIZED_SEQUENCE = "\u0018"; +// Stands in for the ESC of an oversized sequence, which ended any string history left open. +const STRING_TERMINATOR = "\u001b\\"; + +// Longer held text is cut to its introducer in a snapshot, so it cannot push history out of the +// client's budget or add its size to every resync. +const MAX_SNAPSHOT_SEQUENCE_LENGTH = 4_096; + +// History leaves out the sequence the terminal is still inside. A client that starts from a +// snapshot needs it, or it prints the rest of the sequence as text. +function unfinishedSequenceReplay(session: TerminalSessionState): string { + const held = session.pendingHistoryControlSequence; + if (held.startsWith(OVERSIZED_SEQUENCE)) return held.slice(1); + if (held.length <= MAX_SNAPSHOT_SEQUENCE_LENGTH) return held; + return held.slice(0, 2) + (/[\u001b\ud800-\udbff]$/.exec(held)?.[0] ?? ""); +} + +export function sanitizeTerminalHistoryChunk( pendingControlSequence: string, data: string, ): { visibleText: string; pendingControlSequence: string } { @@ -1402,9 +1427,12 @@ function sanitizeTerminalHistoryChunk( return { visibleText: data, pendingControlSequence: "" }; } - const input = `${pendingControlSequence}${data}`; - // Only the pending prefix's final ESC can begin a terminator split across chunks. - const pendingScanStart = Math.max(0, pendingControlSequence.length - 1); + const resumesOversized = pendingControlSequence.startsWith(OVERSIZED_SEQUENCE); + const held = resumesOversized ? pendingControlSequence.slice(1) : pendingControlSequence; + const input = `${held}${data}`; + // Only the held text's final code unit, an ESC or a high surrogate, can begin an end split + // across chunks. + const pendingScanStart = Math.max(0, held.length - 1); let visibleText = ""; let index = 0; // Set when a C1 code point began the sequence at `index`: the ESC form that stands in for it. @@ -1421,6 +1449,7 @@ function sanitizeTerminalHistoryChunk( // Empty for a sequence the input introduces itself, which starts with ESC at `index`. const prefix = c1Introducer; c1Introducer = ""; + const oversized = resumesOversized && index === 0; const contentStart = prefix.length > 0 ? index : index + 2; const nextCodePoint = (prefix || input).charCodeAt(prefix.length > 0 ? 1 : index + 1); if (Number.isNaN(nextCodePoint)) { @@ -1428,19 +1457,21 @@ function sanitizeTerminalHistoryChunk( } if (nextCodePoint === 0x5b) { - let cursor = contentStart; + // A held CSI has not ended, so only its last code unit is scanned again. + let cursor = index === 0 ? Math.max(contentStart, pendingScanStart) : contentStart; // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would // print in ground state. None join the parameters; only executed ones survive a strip. - let body = ""; - let executedControls = ""; + const executedControls = () => + input.slice(contentStart, cursor).replace(/[^\x00-\x0f]+/g, ""); while (cursor < input.length) { const cursorCodePoint = input.charCodeAt(cursor); const cancelled = isControlSequenceCancel(cursorCodePoint); if (cancelled || isCsiFinalByte(cursorCodePoint)) { - if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { + const body = input.slice(contentStart, cursor).replace(/[^\x20-\x7e]+/g, ""); + if (!oversized && (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? ""))) { append(prefix + input.slice(index, cursor + 1)); } else { - append(executedControls); + append(executedControls()); } index = cursor + 1; break; @@ -1452,10 +1483,10 @@ function sanitizeTerminalHistoryChunk( if (c1) { // The CSI ends here undispatched, so it is kept only when the terminal is back in // ground with nothing to answer. - if (c1.next.length === 0 && !c1.query) { + if (!oversized && c1.next.length === 0 && !c1.query) { append(prefix + input.slice(index, end)); } else { - append(executedControls + c1.safe); + append(executedControls() + c1.safe); } c1Introducer = c1.next; index = end; @@ -1466,19 +1497,24 @@ function sanitizeTerminalHistoryChunk( } // An ESC abandons the CSI and starts the next sequence, which may be stripped. if (cursorCodePoint === 0x1b) { - append(executedControls); + append(executedControls()); index = cursor; break; } - if (cursorCodePoint < 0x10) { - executedControls += input[cursor]; - } else if (cursorCodePoint >= 0x20 && cursorCodePoint !== 0x7f) { - body += input[cursor]; - } cursor += 1; } if (cursor >= input.length) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + // The terminal has run these controls already, so history takes them as they come. + append((oversized ? "" : STRING_TERMINATOR) + executedControls()); + const endStart = /[\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: `${OVERSIZED_SEQUENCE}\u001b[${endStart}`, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } continue; } @@ -1495,7 +1531,16 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5d, ); if (stringEnd === null) { - return { visibleText, pendingControlSequence: prefix + input.slice(index) }; + const unfinished = prefix + input.slice(index); + if (oversized || unfinished.length > MAX_HELD_SEQUENCE_LENGTH) { + append(oversized ? "" : STRING_TERMINATOR); + const endStart = /[\u001b\ud800-\udbff]$/.exec(unfinished)?.[0] ?? ""; + return { + visibleText, + pendingControlSequence: OVERSIZED_SEQUENCE + unfinished.slice(0, 2) + endStart, + }; + } + return { visibleText, pendingControlSequence: unfinished }; } const { end, c1 } = stringEnd; const content = stripStringTerminator( @@ -1505,6 +1550,7 @@ function sanitizeTerminalHistoryChunk( // has its own terminator. Without one, the query ends at the next ESC, which history may // strip, so ST would not replay the same and the query stays. if ( + !oversized && nextCodePoint === 0x5d && isOscPaletteQuery(content) && /[\x07\x18\x1a]$|\x1b\\$/.test(input.slice(index, end)) @@ -1514,6 +1560,7 @@ function sanitizeTerminalHistoryChunk( continue; } const strip = + oversized || (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { @@ -1532,7 +1579,10 @@ function sanitizeTerminalHistoryChunk( const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1); if (escapeSequenceEndIndex === null) { - return { visibleText, pendingControlSequence: input.slice(index) }; + return { + visibleText, + pendingControlSequence: input.slice(index, index + MAX_HELD_ESCAPE_LENGTH), + }; } // ESC Z (DECID) is the legacy primary device attributes query. if (nextCodePoint !== 0x5a) { From fab237d62629925f271f4b48f2ffa4eedc95a271 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:56:56 -0800 Subject: [PATCH 005/221] fix(server): service commands no longer stop systemd-oomd watching the user manager (#41495) --- apps/server/src/cloud/bootService.test.ts | 2 + apps/server/src/cloud/bootService.ts | 20 +++--- .../src/cloud/serviceLauncherClient.test.ts | 36 +++++++++- .../server/src/cloud/serviceLauncherClient.ts | 64 +++++++++++------ apps/server/src/cloud/serviceProtection.ts | 11 +-- apps/server/src/cloud/userManagerOom.test.ts | 72 +++++++++++++++++++ apps/server/src/cloud/userManagerOom.ts | 22 ++++++ apps/server/src/serviceLauncher.test.ts | 2 +- apps/server/src/serviceLauncher.ts | 16 ++++- 9 files changed, 206 insertions(+), 39 deletions(-) create mode 100644 apps/server/src/cloud/userManagerOom.test.ts create mode 100644 apps/server/src/cloud/userManagerOom.ts diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index ad926f2b5154d..8e69e7cdcd7af 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -22,6 +22,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { serviceLauncherLockPath } from "../serviceLauncher.ts"; import * as BootService from "./bootService.ts"; import { pinnedRuntimePaths } from "./pinnedRuntime.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { decodeServiceUnit, disabledServiceTask, @@ -1406,6 +1407,7 @@ process.disconnect(); const outcome = yield* inside.restart; expect(commands).toEqual([ "systemctl --user daemon-reload", + `/bin/sh -c ${RESTORE_OOMD_WATCH_SCRIPT}`, "systemctl --user enable t3code.service", "systemctl --user reset-failed t3code.service", "systemctl --user restart --no-block t3code.service", diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 4f81ec8641931..3a930f02dabc1 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -19,6 +19,7 @@ import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as ProcessRunner from "../processRunner.ts"; import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { serviceLauncherIsRunning, serviceLauncherLockPath, @@ -329,12 +330,21 @@ function systemdManager(input: { command: "systemctl", args: ["--user", "reset-failed", BOOT_SERVICE_UNIT_FILE], }; - const prepareActivation = [ + const reload = [ { step: "reloading systemd user units", command: "systemctl", args: ["--user", "daemon-reload"], }, + { + step: "restoring systemd-oomd's watch on the user manager", + optional: true, + command: "/bin/sh", + args: ["-c", RESTORE_OOMD_WATCH_SCRIPT], + }, + ]; + const prepareActivation = [ + ...reload, { step: "enabling the service", command: "systemctl", @@ -388,13 +398,7 @@ function systemdManager(input: { timeout: STOP_STEP_TIMEOUT, }, ], - finalize: [ - { - step: "reloading systemd user units", - command: "systemctl", - args: ["--user", "daemon-reload"], - }, - ], + finalize: reload, }; } diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 85661360020f6..8c52725dd8a3c 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -6,6 +6,7 @@ import * as PlatformError from "effect/PlatformError"; import { assert, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import { @@ -83,11 +84,42 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])( }; const host = new FakeLauncherProcess({ protocol, childVersion: "1.1.0", update: pending }); host.env["HOME"] = root; - const client = yield* makeClient(host, "1.1.0"); + // The launcher reloads the user manager after commit, so oomd's watch must already be mirrored. + const bin = path.join(root, "bin"); + const calls = path.join(root, "systemctl-calls"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString( + path.join(bin, "systemctl"), + [ + "#!/bin/sh", + `echo "$*" >>'${calls}'`, + 'case "$*" in', + " *ControlGroup*) echo /user.slice/user-1000.slice/user@1000.service ;;", + " *ManagedOOMMemoryPressureLimit*) echo 0 ;;", + " *ManagedOOMMemoryPressure\\ *) echo kill ;;", + "esac", + "", + ].join("\n"), + ); + yield* fs.chmod(path.join(bin, "systemctl"), 0o755); + host.env["PATH"] = `${bin}:/usr/bin:/bin`; + const sentPrepared = yield* Deferred.make(); + const send = host.send; + host.send = (message, callback) => { + Deferred.doneUnsafe(sentPrepared, Effect.void); + return send(message, callback); + }; + const client = yield* makeClient(host, "1.1.0").pipe( + Effect.provideService(HostProcess.Platform, "linux"), + ); const prepared = yield* Effect.forkChild(client.prepareTrial({ baseDir }), { startImmediately: true, }); - yield* Effect.yieldNow; + yield* Deferred.await(sentPrepared); + // Nothing runs systemctl after "prepared", so the log is what ran before it. + expect(yield* fs.readFileString(calls)).toContain( + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill", + ); expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]); assert.equal(yield* fs.readLink(installed), exe("1.0.0")); diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index 3e7f4abfc2d57..50b596b0e30d5 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -8,6 +8,8 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import packageJson from "../../package.json" with { type: "json" }; import { @@ -24,6 +26,7 @@ import { type ServiceLauncherParentMessage, type SupportedLauncherProtocol, } from "./serviceProtocol.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; export class ServiceLauncherClientError extends Schema.TaggedError()( "ServiceLauncherClientError", @@ -264,6 +267,22 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o const path = yield* Path.Path; const environment = yield* HostProcess.Environment; const platform = yield* HostProcess.Platform; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // The launcher that commits a remote update is the old one; its reload after commit + // keeps oomd's watch only if the policy is mirrored before it. + const keepOomdWatch = + platform === "linux" + ? spawner + .exitCode( + ChildProcess.make("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + env: environment, + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + }), + ) + .pipe(Effect.timeout("30 seconds"), Effect.ignore) + : Effect.void; const exchange = ( message: ServiceLauncherChildMessage, @@ -343,28 +362,31 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o : context.update; const prepareTrial = (input: { readonly baseDir: string }) => pending !== undefined - ? exchange( - { type: "prepared", updateId: pending.id }, - (reply) => reply.type === "committed" && reply.updateId === pending.id, - ).pipe( - Effect.flatMap((reply) => - reply.type !== "committed" - ? Effect.die("service launcher returned an impossible prepared response") - : repointLaunchers({ - baseDir: input.baseDir, - targetVersion: pending.targetVersion, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fs), - Effect.provideService(Path.Path, path), - Effect.provideService(HostProcess.Environment, environment), - Effect.provideService(HostProcess.Platform, platform), - Effect.as({ - id: pending.id, - fromVersion: pending.fromVersion, + ? Effect.andThen( + keepOomdWatch, + exchange( + { type: "prepared", updateId: pending.id }, + (reply) => reply.type === "committed" && reply.updateId === pending.id, + ).pipe( + Effect.flatMap((reply) => + reply.type !== "committed" + ? Effect.die("service launcher returned an impossible prepared response") + : repointLaunchers({ + baseDir: input.baseDir, targetVersion: pending.targetVersion, - status: "committed" as const, - }), - ), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HostProcess.Platform, platform), + Effect.as({ + id: pending.id, + fromVersion: pending.fromVersion, + targetVersion: pending.targetVersion, + status: "committed" as const, + }), + ), + ), ), ) : Effect.succeed(outcome); diff --git a/apps/server/src/cloud/serviceProtection.ts b/apps/server/src/cloud/serviceProtection.ts index 48790bcf6cc05..a8952ce299fd9 100644 --- a/apps/server/src/cloud/serviceProtection.ts +++ b/apps/server/src/cloud/serviceProtection.ts @@ -8,6 +8,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProcessRunner from "../processRunner.ts"; import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; const PROTECT_DROP_IN = "90-t3code-protect.conf"; const SYSTEM_UNIT_DIR = "/etc/systemd/system"; @@ -210,10 +211,12 @@ export const detectRemoteAccessUnits = run("list remote-access services", "syste Effect.withSpan("ServiceProtection.detectRemoteAccessUnits"), ); -const reloadUserManager = run("reload systemd user units", "systemctl", [ - "--user", - "daemon-reload", -]); +const reloadUserManager = Effect.andThen( + run("reload systemd user units", "systemctl", ["--user", "daemon-reload"]), + run("restore systemd-oomd's watch", "/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT]).pipe( + Effect.ignore, + ), +); const writeDropIns = Effect.fn("ServiceProtection.writeDropIns")(function* ( dropIns: ReadonlyArray, diff --git a/apps/server/src/cloud/userManagerOom.test.ts b/apps/server/src/cloud/userManagerOom.test.ts new file mode 100644 index 0000000000000..67c0e51e11639 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.test.ts @@ -0,0 +1,72 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { expect, it } from "vite-plus/test"; + +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; + +const userService = "/user.slice/user-1001.slice/user@1001.service"; + +it.each([ + [ + "mirrors the system manager's kill policy onto the user manager's root slice", + { cgroup: userService, mode: "kill", limit: "4252017622", duration: "" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=99.00%", + ], + [ + "keeps a custom duration and an unset limit", + { cgroup: userService, mode: "kill", limit: "0", duration: "20s" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=0.00% ManagedOOMMemoryPressureDurationSec=20s", + ], + [ + "leaves the slice alone when oomd is not told to kill", + { cgroup: userService, mode: "auto", limit: "0", duration: "infinity" }, + undefined, + ], + [ + "leaves the slice alone outside a user@ service", + { cgroup: "/system.slice/foo.service", mode: "kill", limit: "0", duration: "infinity" }, + undefined, + ], +])("%s", (_name, system, expected) => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-oomd-")); + try { + const calls = NodePath.join(root, "calls"); + NodeFS.writeFileSync( + NodePath.join(root, "systemctl"), + [ + "#!/bin/sh", + 'echo "$*" >>"$CALLS"', + 'case "$*" in', + ' *ControlGroup*) echo "$CGROUP" ;;', + ' *ManagedOOMMemoryPressureLimit*) echo "$LIMIT" ;;', + ' *ManagedOOMMemoryPressureDurationUSec*) echo "$DURATION" ;;', + ' *ManagedOOMMemoryPressure\\ *) echo "$MODE" ;;', + "esac", + "", + ].join("\n"), + { mode: 0o755 }, + ); + const result = NodeChildProcess.spawnSync("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + encoding: "utf8", + env: { + PATH: `${root}:/usr/bin:/bin`, + CALLS: calls, + CGROUP: system.cgroup, + MODE: system.mode, + LIMIT: system.limit, + DURATION: system.duration, + }, + }); + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + const setProperty = NodeFS.readFileSync(calls, "utf8") + .split("\n") + .find((call) => call.includes("set-property")); + expect(setProperty).toBe(expected); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/server/src/cloud/userManagerOom.ts b/apps/server/src/cloud/userManagerOom.ts new file mode 100644 index 0000000000000..6f23427b83999 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.ts @@ -0,0 +1,22 @@ +/** + * Run after `systemctl --user daemon-reload`. The user manager's -.slice shares the cgroup of + * user@.service and reports it to systemd-oomd as `auto` on reload, which drops the system + * manager's `kill` watch (systemd/systemd#43174). Mirroring that policy onto -.slice restores the + * watch and keeps it through later reloads. Best effort: exits 0 when there is nothing to mirror. + */ +export const RESTORE_OOMD_WATCH_SCRIPT = [ + "unit=$(systemctl --user show --property=ControlGroup --value -- -.slice) || exit 0", + "unit=${unit##*/}", + "case $unit in user@*.service) ;; *) exit 0 ;; esac", + 'show() { systemctl show --property="$1" --value "$unit"; }', + '[ "$(show ManagedOOMMemoryPressure)" = kill ] || exit 0', + "limit=$(show ManagedOOMMemoryPressureLimit)", + "case $limit in '' | *[!0-9]*) exit 0 ;; esac", + // The limit is a fraction of 2^32; set-property takes a percentage. + "p=$(( (limit * 10000 + 2147483648) / 4294967296 ))", + 'set -- ManagedOOMMemoryPressure=kill "ManagedOOMMemoryPressureLimit=$((p / 100)).$(printf %02d $((p % 100)))%"', + "duration=$(show ManagedOOMMemoryPressureDurationUSec)", + 'case $duration in "" | infinity) ;; *) set -- "$@" "ManagedOOMMemoryPressureDurationSec=$duration" ;; esac', + 'exec systemctl --user set-property --runtime -- -.slice "$@"', + "", +].join("\n"); diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index c7259b4bd84fb..0f51100fb368b 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -553,7 +553,7 @@ setInterval(() => {}, 1_000); ); yield* fs.writeFileString( path.join(bin, "systemctl"), - `#!/bin/sh\necho reload >> '${path.join(root, "reloads")}'\n`, + `#!/bin/sh\n[ "$*" = "--user daemon-reload" ] && echo reload >> '${path.join(root, "reloads")}'\n`, ); yield* fs.chmod(path.join(bin, "busctl"), 0o755); yield* fs.chmod(path.join(bin, "systemctl"), 0o755); diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 8dcd7886fce51..3c6bdf6913187 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -8,6 +8,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; import { acquireServiceSelectionLock } from "./cloud/serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./cloud/userManagerOom.ts"; import { isNoCopyOnWrite, markNoCopyOnWrite } from "./noCopyOnWrite.ts"; import type { @@ -224,8 +225,8 @@ async function serviceUnitFromEnvironment( ); return { path: NodePath.join(unitDir, unitName), - reload: () => - new Promise((resolve, reject) => { + reload: async () => { + await new Promise((resolve, reject) => { NodeChildProcess.spawn("systemctl", ["--user", "daemon-reload"], { stdio: "ignore", timeout: 30_000, @@ -236,7 +237,16 @@ async function serviceUnitFromEnvironment( ? resolve() : reject(new Error(`systemctl --user daemon-reload exited with ${code ?? signal}`)), ); - }), + }); + await new Promise((resolve) => { + NodeChildProcess.spawn("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + stdio: "ignore", + timeout: 30_000, + }) + .once("error", () => resolve()) + .once("exit", () => resolve()); + }); + }, }; } From 0948100035d7710b3d5410fee975f8960c1824eb Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Mon, 23 Nov 2026 15:01:08 +0000 Subject: [PATCH 006/221] fix(server): a compaction or manual continuation keeps its session busy like a turn (#41490) Co-authored-by: Julius Marminge --- .../ProviderSessionManager.test.ts | 99 +++++++++++ .../ProviderSessionManager.ts | 164 ++++++++++-------- 2 files changed, 195 insertions(+), 68 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index f2f992d8f4ee9..e6652c5963905 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -611,6 +611,8 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( resumeCount: current.resumeCount + 1, })).pipe(Effect.as(threadInput.providerThread)), startTurn: () => options.startTurn ?? Effect.void, + resumeTurn: () => options.startTurn ?? Effect.void, + compactThread: () => options.startTurn ?? Effect.void, steerTurn: () => Effect.void, interruptTurn: () => Ref.update(state, (current) => ({ @@ -2137,6 +2139,103 @@ it.effect.each([ }), ); +const idleReleaseAroundRun = (start: "compactThread" | "resumeTurn") => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make(`thread-${start}-outlasts-idle-timeout`); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const subscriber = yield* runtime.subscribeEvents!; + const terminal = yield* subscriber.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + Effect.forkScoped, + ); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: `native-${threadId}`, + }); + const runId = idAllocator.derive.run({ threadId, ordinal: 1 }); + const run = { + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + modelSelection, + runtimePolicy, + }; + const messageId = yield* idAllocator.allocate.message({ threadId, ordinal: 1 }); + yield* start === "compactThread" + ? runtime.compactThread!({ + ...run, + message: { + createdBy: "user", + creationSource: "web", + messageId, + text: "/compact", + attachments: [], + }, + }) + : runtime.resumeTurn!({ ...run, messageId }); + + // A running compaction or continuation can go minutes without a provider event. + yield* TestClock.adjust("2 seconds"); + assert.isTrue(yield* manager.isLive(providerSessionId)); + + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(queue); + yield* Queue.offer(queue!, { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: `native-turn-${start}`, + }), + runOrdinal: 1, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + // The event pump marks the run idle before it publishes the event. + yield* Fiber.join(terminal); + yield* TestClock.adjust("2 seconds"); + assert.isFalse(yield* manager.isLive(providerSessionId)); + }).pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000 }))); + }); + +it.effect.each([ + { run: "compaction", start: "compactThread" }, + { run: "manual continuation", start: "resumeTurn" }, +] as const)( + "ProviderSessionManagerV2 keeps a session through a $run that outlasts the idle timeout", + ({ start }) => idleReleaseAroundRun(start), +); + it.effect.each(["session metadata", "session status changes", "provider work"] as const)( "ProviderSessionManagerV2 expires idle sessions according to %s", (activity) => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index dc1ae318a4c2a..291ac02272a26 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2532,6 +2532,80 @@ export const layerWithOptions = ( modelFamily: normalizeModelMetricLabel(model), }, }); + // A start, continuation or compaction keeps the session busy until its turn.terminal. + const busyTurn = ( + input: Pick< + ProviderAdapter.ProviderAdapterV2TurnInput, + "threadId" | "providerThread" | "runOrdinal" | "runId" + >, + run: () => Effect.Effect, + ) => + observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. + Effect.andThen( + holdThreadLoaded({ + providerSessionId, + threadId: input.threadId, + providerThread: input.providerThread, + }), + ), + Effect.andThen( + Effect.acquireUseRelease( + markBusy( + providerSessionId, + busyTurnKey(input.providerThread.id, input.runOrdinal), + runtime, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.activity-failed", { + providerSessionId, + cause, + }).pipe(Effect.as(true)), + ), + // A release between attach and markBusy leaves nothing to mark: fail the + // start instead of running it on a runtime being torn down. + Effect.flatMap((marked) => + marked + ? Effect.void + : Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: "The provider session was released while the turn started.", + }), + ), + ), + ), + run, + (_, exit) => + Exit.isFailure(exit) + ? observeActivity( + providerSessionId, + markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), + ).pipe( + // A failed start can leave its native thread gone (Claude rejecting a + // resume), so the next start must ask the adapter to resume it again. + Effect.andThen( + forgetProviderThreadLoaded({ + providerSessionId, + threadId: input.threadId, + runtime, + }), + ), + ) + : Effect.void, + ), + ), + ); return { ...runtime, // Pi replaces its session snapshot as metadata changes. @@ -2663,78 +2737,32 @@ export const layerWithOptions = ( Effect.map(({ loaded }) => loaded), ), startTurn: (input) => - observeActivity( - providerSessionId, - ensureThreadAttached({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - }), - ).pipe( - // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. - Effect.andThen( - holdThreadLoaded({ - providerSessionId, - threadId: input.threadId, - providerThread: input.providerThread, - }), + busyTurn(input, () => + agentFeedbackMode.pipe( + Effect.flatMap((agentFeedback) => runtime.startTurn({ ...input, agentFeedback })), + turnMetrics("send", input.modelSelection.model), ), - Effect.andThen( - Effect.acquireUseRelease( - markBusy( - providerSessionId, - busyTurnKey(input.providerThread.id, input.runOrdinal), - runtime, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.activity-failed", { - providerSessionId, - cause, - }).pipe(Effect.as(true)), - ), - // A release between attach and markBusy leaves nothing to mark: fail the - // start instead of running it on a runtime being torn down. - Effect.flatMap((marked) => - marked - ? Effect.void - : Effect.fail( - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause: "The provider session was released while the turn started.", - }), - ), + ), + ...(runtime.resumeTurn === undefined + ? {} + : { + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + busyTurn(input, () => + runtime.resumeTurn!(input).pipe( + turnMetrics("resume", input.modelSelection.model), ), ), - () => - agentFeedbackMode.pipe( - Effect.flatMap((agentFeedback) => - runtime.startTurn({ ...input, agentFeedback }), - ), - turnMetrics("send", input.modelSelection.model), + }), + ...(runtime.compactThread === undefined + ? {} + : { + compactThread: (input: ProviderAdapter.ProviderAdapterV2TurnInput) => + busyTurn(input, () => + runtime.compactThread!(input).pipe( + turnMetrics("compact", input.modelSelection.model), ), - (_, exit) => - Exit.isFailure(exit) - ? observeActivity( - providerSessionId, - markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), - ).pipe( - // A failed start can leave its native thread gone (Claude rejecting a - // resume), so the next start must ask the adapter to resume it again. - Effect.andThen( - forgetProviderThreadLoaded({ - providerSessionId, - threadId: input.threadId, - runtime, - }), - ), - ) - : Effect.void, - ), - ), - ), + ), + }), steerTurn: (input) => observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( Effect.andThen(runtime.steerTurn(input).pipe(turnMetrics("steer"))), From f0d901502a3b3cb961f9bfcb89a1d8f5233b78d9 Mon Sep 17 00:00:00 2001 From: 4dwaffle Date: Mon, 23 Nov 2026 16:07:09 +0100 Subject: [PATCH 007/221] fix(server): Azure DevOps PRs read by number get their full URL (#41472) Co-authored-by: Vaclav Berny Co-authored-by: Julius Marminge --- .../toolkits/pullRequests/handlers.test.ts | 34 +++++++++++++++++++ .../src/pullRequest/pullRequestTarget.ts | 19 +++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index f0b9db206bbb6..95f816f151b9d 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -944,6 +944,40 @@ describe("source control tools", () => { }), ); + it.effect("reads an Azure DevOps PR by number at its organization and project", () => + Effect.gen(function* () { + const asked: Array = []; + const harness = yield* makeHarness({ + project: makeProject({ + canonicalKey: "dev.azure.com/contoso/project/_git/repo", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://contoso@dev.azure.com/contoso/project/_git/repo", + }, + provider: SourceControlProviderKind.make("azure-devops"), + displayName: "contoso/project/_git/repo", + owner: "contoso", + name: "repo", + }), + pullRequests: { + detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)), + activity: () => Effect.succeed(activity), + }, + }); + const result = yield* harness.call("pull_request_read", { number: 123 }); + expect(result).toMatchObject({ + host: "dev.azure.com", + repository: "contoso/project/_git/repo", + number: 123, + url: "https://dev.azure.com/contoso/project/_git/repo/pullrequest/123", + }); + expect(asked).toMatchObject([ + { host: "dev.azure.com", repository: "contoso/project/_git/repo", number: 123 }, + ]); + }), + ); + it.effect("pages a long conversation and the PR list through the cursors they return", () => Effect.gen(function* () { const comment = (body: string) => diff --git a/apps/server/src/pullRequest/pullRequestTarget.ts b/apps/server/src/pullRequest/pullRequestTarget.ts index 52d9c3605b069..45312f8304634 100644 --- a/apps/server/src/pullRequest/pullRequestTarget.ts +++ b/apps/server/src/pullRequest/pullRequestTarget.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts"; +import { pullRequestSyncKey } from "./pullRequestSyncKey.ts"; export interface PullRequestTarget { readonly url?: string | undefined; @@ -102,12 +103,26 @@ export const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(func if (input.repository === undefined || input.number === undefined) { return yield* new PullRequestTargetIncompleteError({}); } + // Azure DevOps tools name the project's repository by its bare name, which no URL can be built + // from, so it is read as the project's full repository path. + const own = + project?.repositoryIdentity == null || input.repository.includes("/") + ? null + : pullRequestSyncKey( + { + projectId: project.id, + host: input.host, + repository: input.repository, + number: input.number, + }, + project.repositoryIdentity, + ); const projectHost = projectHostAndProvider(project); - const host = (input.host ?? projectHost.host)?.toLowerCase(); + const host = (own?.host ?? input.host ?? projectHost.host)?.toLowerCase(); if (host === undefined) { return yield* new PullRequestHostRequiredError({}); } - const repository = input.repository.toLowerCase(); + const repository = (own?.repository ?? input.repository).toLowerCase(); // Without a URL, a public forge host says what shape its change request URLs take; // any other host is taken to run the project's own forge. const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind; From 0359b044e99e9cf5bddea19c889e1dcbb8a161cd Mon Sep 17 00:00:00 2001 From: 3xcalibur <79220116+3xcalibur-tech@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:13:46 +0400 Subject: [PATCH 008/221] fix(desktop): agent screenshots and clicks work while T3 Code is hidden, minimized or covered (#40263) Co-authored-by: Julius Marminge --- .../src/preview/DesktopBrowserHost.test.ts | 97 +++++++++++++++++++ .../desktop/src/preview/DesktopBrowserHost.ts | 96 ++++++++++++++++-- 2 files changed, 187 insertions(+), 6 deletions(-) diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 8e96129293fc8..b086f67829181 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -50,6 +50,10 @@ const makeDebuggee = ( readonly deferFocus?: boolean; /** The guest is still loading its first page. */ readonly loading?: boolean; + /** Like a guest of a hidden window: it answers a capture only once Electron captures it. */ + readonly drawsOnlyWhenCaptured?: () => boolean; + /** Electron's capture of this guest never settles. */ + readonly capturesStall?: () => boolean; readonly refuse?: (method: string, sessionId: string | undefined) => boolean; } = {}, ) => { @@ -90,7 +94,14 @@ const makeDebuggee = ( }), }); let destroyed = false; + let nativeCaptures = 0; const webContents = Object.assign(new NodeEvents.EventEmitter(), { + capturePage: () => { + nativeCaptures += 1; + if (options.capturesStall?.()) return new Promise(() => {}); + if (options.drawsOnlyWhenCaptured?.()) pending.splice(0).forEach((resolve) => resolve()); + return Promise.resolve({}); + }, getURL: () => "http://localhost/", getTitle: () => "Page", getUserAgent: () => "Electron", @@ -117,6 +128,7 @@ const makeDebuggee = ( /** Refuses the pending command the debugger received with this id. */ refuse: (id: number) => rejects[sent.indexOf(id)]?.(), focusEmulation, + nativeCaptures: () => nativeCaptures, nextSend: () => new Promise((resolve) => sendWaiters.push(resolve)), release: () => pending.splice(0).forEach((resolve) => resolve()), releaseFirst: () => pending.shift()?.(), @@ -364,6 +376,91 @@ describe("DesktopBrowserHost", () => { }).pipe(Effect.scoped), ); + it.effect("prods a guest its window stopped drawing until what waits on it settles", () => + Effect.gen(function* () { + let drawsWhenCaptured = true; + let capturesStall = false; + const host = yield* makeDrawnHost; + const debuggee = makeDebuggee({ + drawsOnlyWhenCaptured: () => drawsWhenCaptured, + capturesStall: () => capturesStall, + }); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const painting = yield* watchPainting(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([1]); + yield* TestClock.adjust("250 millis"); + expect(yield* Queue.take(replies)).toBe(1); + expect(debuggee.nativeCaptures()).toBe(1); + + // A wait that settles within a frame is never prodded. + yield* command(host, 3, "Page.captureScreenshot"); + yield* settle; + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(3); + yield* TestClock.adjust("1 second"); + expect(debuggee.nativeCaptures()).toBe(1); + + // A long wait is prodded less often as it goes on, once per tick though it holds focus too. + drawsWhenCaptured = false; + yield* command(host, 4, "Page.captureScreenshot"); + yield* settle; + for (const [wait, prods] of [ + ["250 millis", 2], + ["500 millis", 3], + ["1 second", 4], + ["2 seconds", 5], + ["2 seconds", 6], + ] as const) { + yield* TestClock.adjust(wait); + expect(debuggee.nativeCaptures()).toBe(prods); + } + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(4); + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(6); + + // A command that outlasts its first prod is painted like a capture, which also unthrottles it. + // A wait the agent's turn gave up on is no longer prodded. + yield* command(host, 5, "Runtime.evaluate"); + yield* settle; + painting.length = 0; + yield* TestClock.adjust("250 millis"); + expect(debuggee.nativeCaptures()).toBe(7); + expect(painting).toEqual([true]); + yield* host.handleCommandLine( + encodeJson({ type: "turn", threadId: key.threadId, active: false }), + ); + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(7); + expect(painting).toEqual([true, false]); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(5); + + // Captures Electron never settles pile up no further than two. + capturesStall = true; + yield* command(host, 6, "Runtime.evaluate"); + yield* settle; + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(9); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(6); + // Even across a reattach of the same guest, as when DevTools closes. + host.detach(key); + host.attach(key, debuggee.tab); + const reattached = yield* watchReplies(host); + yield* command(host, 7, "Runtime.evaluate"); + yield* settle; + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(9); + debuggee.releaseFirst(); + expect(yield* Queue.take(reattached)).toBe(7); + }).pipe(Effect.scoped), + ); + it.effect("stops waiting on a screenshot the page navigated away from", () => Effect.gen(function* () { const host = yield* makeDrawnHost; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index ce5d7074a786c..b3812e90d54bf 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -32,6 +32,12 @@ const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]); const FOCUS_IDLE = "5 seconds"; /** How long a screenshot waits for the client to draw its guest at full detail. */ const CAPTURE_DRAW_WAIT = "1 second"; +/** Most waits settle within a frame or two of this, so a quick one is never prodded. */ +const PAINT_NUDGE_FIRST_MS = 250; +/** A long wait, such as a page awaiting a timer, is prodded less often as it goes on. */ +const PAINT_NUDGE_LONGEST_MS = 2_000; +/** Electron's capture has no deadline and a cold guest can stall one, so a second may follow. */ +const PAINT_NUDGE_IN_FLIGHT = 2; /** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */ const FIRST_PAGE_TIMEOUT = "5 seconds"; const ERR_ABORTED = -3; @@ -73,6 +79,11 @@ interface AttachedTab { readonly focusPending: Map; /** Screenshots Chromium was sent and has not answered; each keeps its wake lock until then. */ readonly capturing: Set; + /** Each wait on the guest's next frame, as whether it still waits; the guest is prodded until none do. */ + readonly frameWaits: Set<() => boolean>; + nudging: Fiber.Fiber | null; + /** A wait outlasted its first nudge, so the guest is painted and unthrottled like a capture. */ + frameStalled: boolean; /** Whether the client keeps the guest painting, as published on `painting`. */ painting: boolean; /** @@ -243,7 +254,7 @@ export const make = Effect.gen(function* () { }; /** - * Electron composites no offscreen guest, so its screenshot or screencast waits for a frame + * Electron composites no offscreen guest, so a screenshot, screencast or stalled command waits for a frame * that never comes. The client paints the guest behind the app while one is pending; the * capture then finishes on its own, and the guest goes back offscreen once none is. */ @@ -252,12 +263,78 @@ export const make = Effect.gen(function* () { tabs.get(keyOf(tab.key)) === tab && (tab.screencasts.size > 0 || tab.capturing.size > 0 || + tab.frameStalled || tab.waitingScreenshots.some((waiting) => waiting.live())); if (tab.painting === active) return; tab.painting = active; runFork(PubSub.publish(painting, { key: tab.key, active })); }; + /** By guest rather than attachment, since reopening DevTools reattaches the same guest. */ + const nativeCaptures = new WeakMap(); + const startNudging = (tab: AttachedTab) => { + tab.nudging ??= runFork(nudgePaint(tab, PAINT_NUDGE_FIRST_MS)); + }; + + const endNudging = (tab: AttachedTab) => { + tab.nudging = null; + if (!tab.frameStalled) return; + tab.frameStalled = false; + syncPainting(tab); + }; + + /** + * A hidden, minimized or covered window (which Electron reports as visible) stops drawing its + * guest, so a wait on its next frame never ends. Electron's own capture still draws one. + */ + const nudgePaint = (tab: AttachedTab, delayMs: number): Effect.Effect => + Effect.sleep(delayMs).pipe( + Effect.andThen( + Effect.suspend(() => { + const { webContents } = tab.debuggee; + for (const waits of tab.frameWaits) if (!waits()) tab.frameWaits.delete(waits); + if ( + tab.frameWaits.size === 0 || + tabs.get(keyOf(tab.key)) !== tab || + webContents.isDestroyed() + ) { + endNudging(tab); + return Effect.void; + } + // On Windows a hidden window's throttled guest draws nothing, and capturePage cannot wake it. + if (!tab.frameStalled) { + tab.frameStalled = true; + syncPainting(tab); + } + const inFlight = nativeCaptures.get(webContents) ?? 0; + if (inFlight < PAINT_NUDGE_IN_FLIGHT) { + nativeCaptures.set(webContents, inFlight + 1); + const settled = () => { + nativeCaptures.set(webContents, (nativeCaptures.get(webContents) ?? 1) - 1); + }; + webContents.capturePage().then(settled, settled); + } + return nudgePaint(tab, Math.min(delayMs * 2, PAINT_NUDGE_LONGEST_MS)); + }), + ), + ); + + /** Prods the guest while `work` is pending and `waits` holds; one loop serves all of a tab's waits. */ + const nudgedUntilSettled = ( + tab: AttachedTab, + waits: () => boolean, + work: () => Promise, + ) => { + tab.frameWaits.add(waits); + startNudging(tab); + return work().finally(() => { + tab.frameWaits.delete(waits); + if (tab.frameWaits.size > 0 || tab.nudging === null) return; + runFork(Fiber.interrupt(tab.nudging)); + endNudging(tab); + }); + }; + /** A command may wait on the page's next frame, so the guest stays focused until it settles. */ const holdFocus = (tab: AttachedTab, owner: string | undefined, work: () => Promise) => { const pending = {}; @@ -265,7 +342,8 @@ export const make = Effect.gen(function* () { tab.focusUses += 1; setFocusEmulation(tab, true); releaseFocusWhenIdle(tab); - return work().finally(() => { + // Dropping the hold, at a turn's end or a new document, stops the prods too. + return nudgedUntilSettled(tab, () => tab.focusPending.has(pending), work).finally(() => { if (!tab.focusPending.delete(pending)) return; tab.focusUses += 1; releaseFocusWhenIdle(tab); @@ -296,11 +374,14 @@ export const make = Effect.gen(function* () { const sent = {}; tab.capturing.add(sent); syncPainting(tab); + const sendNudged = () => nudgedUntilSettled(tab, () => tab.capturing.has(sent), send); // Sent at once when already drawn, so it keeps its place among the commands after it. - return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => { - tab.capturing.delete(sent); - syncPainting(tab); - }); + return (drawnTabs.has(keyOf(tab.key)) ? sendNudged() : whenDrawn(tab).then(sendNudged)).finally( + () => { + tab.capturing.delete(sent); + syncPainting(tab); + }, + ); }; /** @@ -537,6 +618,9 @@ export const make = Effect.gen(function* () { focusUses: 0, focusPending: new Map(), capturing: new Set(), + frameWaits: new Set(), + nudging: null, + frameStalled: false, painting: false, agentUsed: false, focusReleasing: false, From 555512fbe16db3b2249be3cd7fee9d23f7dc7ef5 Mon Sep 17 00:00:00 2001 From: Michael Nemni Date: Mon, 23 Nov 2026 17:15:01 +0200 Subject: [PATCH 009/221] fix(server): a PR whose merge is refused for conflicts shows as conflicting (#41500) Co-authored-by: Julius Marminge --- .../pullRequest/PullRequestService.test.ts | 41 +++++++++++++++++++ .../src/pullRequest/PullRequestService.ts | 8 ++++ 2 files changed, 49 insertions(+) diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 26190320af16f..a2eb9c6486272 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -3090,6 +3090,47 @@ it.effect("close and reopen notify subscribed readers after invalidating their c }), ); +it.effect("a refused merge notifies readers so they re-read the conflicting state", () => + Effect.gen(function* () { + let mergeable = true; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestSummary: () => + Effect.succeed({ + ...changeRequest(1, "2026-09-16T00:00:00.000Z"), + mergeability: mergeable ? "mergeable" : "conflicting", + }), + runAction: () => + Effect.suspend(() => { + mergeable = false; + return Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "runAction", + reason: "failed", + detail: "Pull Request has merge conflicts", + }), + ); + }), + }), + ], + }); + + assert.strictEqual((yield* service.summary(reference)).mergeability, "mergeable"); + const refreshed = yield* service.subscribeRefreshes.pipe( + Stream.take(1), + Stream.mapEffect(() => service.summary(reference)), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* Effect.flip(service.runAction({ ...reference, action: "merge" })); + assert.strictEqual(Option.getOrThrow(yield* Fiber.join(refreshed)).mergeability, "conflicting"); + }), +); + it.effect("reads a host's repositories in one search, and files the rows back under each", () => Effect.gen(function* () { const asked: Array> = []; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index d0884ac6e7178..690b7c4153f98 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -3989,8 +3989,16 @@ export const make = Effect.gen(function* () { )(function* (input) { const ref = yield* canonicalRef(input); yield* readCache.invalidate(refScope(ref)); + // A refusal (e.g. a merge conflict) means readers hold stale state, so refresh them too. const { repository, summary } = yield* runAction(input).pipe( Effect.ensuring(readCache.invalidate(refScope(ref))), + Effect.tapError(() => + Effect.suspend(() => { + bumpRefEpoch(ref); + listingsEpoch = ++epochCounter; + return SubscriptionRef.set(pullRequestRefreshes, listingsEpoch); + }), + ), ); bumpRefEpoch({ ...ref, repository }); listingsEpoch = ++epochCounter; From 593885bd5dfdc187513e41a54f39d55f8903e5e1 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 09:18:51 -0600 Subject: [PATCH 010/221] fix(cli): a symlinked spelling of the T3 home is the same home for service uninstall (#41464) Co-authored-by: Julius Marminge --- apps/server/src/cli/service.test.ts | 1 + apps/server/src/cli/service.ts | 13 ++----- apps/server/src/cli/uninstall.test.ts | 25 ++++++++++--- apps/server/src/cli/uninstall.ts | 10 ++--- apps/server/src/cli/update.ts | 4 +- apps/server/src/cloud/bootService.test.ts | 22 +++++++++++ apps/server/src/cloud/bootService.ts | 32 ++++++++-------- apps/server/src/serviceLauncher.test.ts | 45 +++++++++++++++++++++++ apps/server/src/serviceLauncher.ts | 3 +- 9 files changed, 117 insertions(+), 38 deletions(-) diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts index ada548ba2bf39..70907ab446a09 100644 --- a/apps/server/src/cli/service.test.ts +++ b/apps/server/src/cli/service.test.ts @@ -288,6 +288,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands const { service, uninstalls } = makeTestService({ ...status, installedBaseDir: input.otherHome ? "/home/me/.t3" : baseDir, + ...(input.otherHome ? { otherBaseDir: "/home/me/.t3" } : {}), }); vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index fc2aa8d0889aa..4c55d1fa329da 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -325,19 +325,14 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags). flags, Effect.gen(function* () { const service = yield* BootService.BootService; - const path = yield* Path.Path; - const { baseDir } = yield* ServerConfig.ServerConfig; // An unreadable unit stays removable; only a unit known to serve another home is kept. - const installedBaseDir = yield* service.status.pipe( - Effect.map((status) => status.installedBaseDir), + const otherBaseDir = yield* service.status.pipe( + Effect.map((status) => status.otherBaseDir), Effect.orElseSucceed(() => undefined), ); - if ( - installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(baseDir) - ) { + if (otherBaseDir !== undefined) { yield* Console.log( - `The T3 Code service serves ${installedBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(installedBaseDir)}\` to remove it.`, + `The T3 Code service serves ${otherBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(otherBaseDir)}\` to remove it.`, ); return; } diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index 7bb1046199c4e..19093032fc3d3 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -89,23 +89,38 @@ it.live("reports failure when the Windows cleanup shell cannot start", () => ); it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => { - it.effect("names another home's service it leaves installed", () => + it.effect.each([ + { + label: "names another home's service it leaves installed", + otherFromRead: 1, + removed: [], + output: "--base-dir '/home/me/.t3'", + }, + { + label: "leaves a service that serves another home by the time it is removed", + otherFromRead: 2, + removed: [], + output: "Left the background service: it now serves another T3 home.", + }, + ])("$label", (input) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-cli-test-" }); const uninstalls: Array = []; + let reads = 0; vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( BootService.BootService, BootService.BootService.of({ - status: Effect.succeed({ + status: Effect.sync(() => ({ supported: true, installed: true, current: true, installedBaseDir: "/home/me/.t3", + ...(++reads >= input.otherFromRead ? { otherBaseDir: "/home/me/.t3" } : {}), unitPath: "/home/me/.config/systemd/user/t3code.service", logPath: "/home/me/.t3/userdata/logs/boot-service.log", - }), + })), withStopped: (operation) => operation, restart: Effect.die("unexpected restart"), install: () => Effect.die("unexpected install"), @@ -133,8 +148,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall com ), ), ); - assert.deepStrictEqual(uninstalls, []); - assert.include(output, "--base-dir '/home/me/.t3'"); + assert.deepStrictEqual(uninstalls, input.removed); + assert.include(output, input.output); }), ); }); diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index 5624e6c2a894c..ae884caa63fe7 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -155,9 +155,7 @@ const planUninstall = Effect.fn("cli.uninstall.plan")(function* (input: { const status = yield* service.status; const installedBaseDir = status.supported && status.installed ? status.installedBaseDir : undefined; - const servesThisHome = - installedBaseDir !== undefined && - path.resolve(installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = installedBaseDir !== undefined && status.otherBaseDir === undefined; const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir); const runtimeDir = path.dirname(versionsDir); const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined; @@ -258,12 +256,14 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { } } - if (plan.service) { + // The prompt can wait a long time; keep a service or launcher that changed hands meanwhile. + if (plan.service && (yield* service.status).otherBaseDir !== undefined) { + yield* Console.log("Left the background service: it now serves another T3 home."); + } else if (plan.service) { yield* service.uninstall; yield* Console.log("Removed the background service."); } for (const launcher of plan.launchers) { - // The prompt can wait a long time; never delete a file that replaced the launcher meanwhile. if (!(yield* ownsLauncher(launcher, plan.versionsDir))) { yield* Console.log(`Left ${launcher}: it no longer runs this t3.`); continue; diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 07f3458fb3b66..dc798afdaa4da 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -423,9 +423,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: { const status = yield* service.status; // Service names are per user, so another home's unit belongs to a different install. - const servesThisHome = - status.installedBaseDir !== undefined && - path.resolve(status.installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = status.installedBaseDir !== undefined && status.otherBaseDir === undefined; const serviceInstalled = status.supported && status.installed && servesThisHome; const foreground = yield* findForegroundServer({ serverRuntimeStatePath: input.serverRuntimeStatePath, diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 8e69e7cdcd7af..c327464ddfa24 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -1308,6 +1308,28 @@ process.disconnect(); }), ); + it.effect("treats a symlinked T3 home path as the same home", () => + Effect.gen(function* () { + const { service, fs, baseDir, commands, makeService } = yield* makeHarness(); + yield* service.install(); + const path = yield* Path.Path; + const linkDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-symlink-home-" }); + const aliasDir = path.join(linkDir, "a$$b"); + yield* fs.symlink(baseDir, aliasDir); + + const alias = yield* makeService(undefined, "1.2.3", aliasDir); + expect(yield* alias.status).toMatchObject({ current: true }); + expect((yield* alias.status).otherBaseDir).toBeUndefined(); + expect(yield* alias.restart).toBe("restarted"); + commands.length = 0; + yield* alias.withStopped(Effect.void); + expect(commands).toContain("systemctl --user stop t3code.service"); + expect((yield* alias.install()).baseDir).toBe(aliasDir); + expect(yield* service.status).toMatchObject({ current: true }); + expect((yield* service.status).otherBaseDir).toBeUndefined(); + }), + ); + it.effect("hands the whole install to systemd without changing the running service", () => Effect.gen(function* () { const { fs, commands, invocations, control, makeService } = yield* makeHarness(); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 3a930f02dabc1..90d01b10526f3 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -1024,12 +1024,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir); const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE); const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE); + const canonicalPath = (dir: string) => + fs.realPath(dir).pipe(Effect.orElseSucceed(() => path.resolve(dir))); + const isThisHome = (dir: string) => + Effect.zipWith(canonicalPath(dir), canonicalPath(input.baseDir), (a, b) => a === b); const otherBaseDirOf = (unit: string) => { const installedBaseDir = bootServiceBaseDirOf(unit); - return installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ? installedBaseDir - : undefined; + return installedBaseDir === undefined + ? Effect.undefined + : Effect.map(isThisHome(installedBaseDir), (same) => (same ? undefined : installedBaseDir)); }; const writeDurably = (filePath: string, contents: string | Uint8Array) => Effect.scoped( @@ -1261,7 +1264,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const refuseOtherBaseDir = Effect.gen(function* () { const existingUnit = yield* readUnit().pipe(Effect.option); const installedBaseDir = Option.isSome(existingUnit) - ? otherBaseDirOf(existingUnit.value) + ? yield* otherBaseDirOf(existingUnit.value) : undefined; if (installedBaseDir !== undefined) { return yield* new BootServiceOtherBaseDirError({ @@ -1491,10 +1494,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return "skipped" as const; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return "skipped" as const; } // Writes no state, and the launcher lets an update transition in flight @@ -1524,10 +1524,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return yield* operation; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return yield* operation; } // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid. @@ -1607,7 +1604,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? serviceStateActiveVersion(stateText.value) : undefined; const installedBaseDir = bootServiceBaseDirOf(unit); - const otherBaseDir = otherBaseDirOf(unit); + const otherBaseDir = yield* otherBaseDirOf(unit); + // Another spelling of this home is current; repairing it would flip the unit between spellings. + const thisHomeUnit = + installedBaseDir !== undefined && otherBaseDir === undefined + ? unit.replaceAll(installedBaseDir, () => input.baseDir) + : unit; const normalizeUnit = (contents: string) => manager.kind === "launchd" ? contents.replace(/(PATH<\/key>\n\s*)[^<]*(<\/string>)/, "$1$2") @@ -1629,7 +1631,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { current: problems.length === 0 && !(manager.kind === "systemd" && systemdUnsafeValue(planForUnit(unit))) && - normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) && + normalizeUnit(thisHomeUnit) === normalizeUnit(manager.render(planForUnit(unit))) && runtimeEntryExists && Option.isSome(runtimeSentinel) && runtimeSentinel.value.trim() === input.cliVersion && diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index 0f51100fb368b..86df5b092ac89 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -896,6 +896,51 @@ process.exit(0); }), ); + it.effect("repoints a unit that names this T3 home through a symlink", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-alias-" }); + const alias = path.join(root, "alias"); + yield* fs.symlink(root, alias); + const statePath = path.join(root, "runtime", "service-state.json"); + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", "1.1.0"), + "setInterval(() => {}, 1_000);\n", + ); + yield* Effect.promise(() => + writeServiceState(statePath, { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.1.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + status: "committed", + }, + }), + ); + const unit = yield* fakeServiceUnit(fs, path, alias, "1.0.0"); + const launcher = new Launcher( + root, + yield* Effect.promise(() => readServiceState(statePath)), + { + serviceUnit: unit, + }, + ); + const running = launcher.run(); + yield* Effect.promise(() => launcher.stop("SIGTERM")); + yield* Effect.promise(() => running); + + assert.equal( + yield* fs.readFileString(unit.path), + renderBootServiceUnit(unitPlan(alias, "1.1.0")), + ); + }), + ); + it.effect("waits without exiting and restarts once the other owner releases the T3 home", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 3c6bdf6913187..44220f2c4b148 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -1416,9 +1416,10 @@ export class Launcher { } const contents = decodeServiceUnit(await NodeFSP.readFile(unit.path)); const installedBaseDir = serviceUnitBaseDirOf(contents); + const real = (dir: string) => NodeFSP.realpath(dir).catch(() => NodePath.resolve(dir)); if ( installedBaseDir === undefined || - NodePath.resolve(installedBaseDir) !== NodePath.resolve(this.#baseDir) + (await real(installedBaseDir)) !== (await real(this.#baseDir)) ) { return; } From 37a70fa0419db077d576fa44e2e381bacb4b1305 Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 16:33:26 +0100 Subject: [PATCH 011/221] fix(server): preserve number formats when XLSX styles are relocated (#41486) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 34 ++++++++++++------- .../src/provider/userInputAttachments.test.ts | 4 +-- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 47e9b2a57f107..7dfd82f02f187 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -627,12 +627,19 @@ async function* document(path: string, extension: string): AsyncGenerator name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase()); + const folded = new Map(); + for (const name of files.keys()) + if (!folded.has(foldAscii(name))) folded.set(foldAscii(name), name); + const part = (name: string) => (files.has(name) ? name : (folded.get(foldAscii(name)) ?? name)); + const has = (name: string) => files.has(part(name)); const notes: string[] = []; const skip = (name: string) => notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`); const read = (name: string): XmlNode => { try { - const data = files.get(name); + const data = files.get(part(name)); if (!data) throw new Error("Missing document part"); return xml(data, extension); } catch (error) { @@ -649,14 +656,14 @@ async function* document(path: string, extension: string): AsyncGenerator rel.attrs.Type?.endsWith("/officeDocument") && rel.attrs.TargetMode !== "External", )?.attrs.Target : undefined; const main = target && NodePath.posix.normalize(target).replace(/^\//, ""); - yield* paragraphs(read(main && files.has(main) ? main : "word/document.xml")); + yield* paragraphs(read(main && has(main) ? main : "word/document.xml")); } else if ([".odt", ".ods", ".odp"].includes(extension)) { const content = read("content.xml"); if (extension === ".odt") yield* paragraphs(content); @@ -683,12 +690,19 @@ async function* document(path: string, extension: string): AsyncGenerator { + const target = workbookRelations.find((rel) => rel.Type?.endsWith(`/${part}`))?.Target; + return target ? NodePath.posix.resolve("/xl", target).slice(1) : `xl/${part}.xml`; + }; const dateSystem = ["1", "true"].includes( all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "", ) ? "1904" : "1900"; - const styles = files.has("xl/styles.xml") ? read("xl/styles.xml") : undefined; + const stylesPath = workbookPartPath("styles"); + const styles = has(stylesPath) ? read(stylesPath) : undefined; const customFormats = new Map( styles ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode]) @@ -696,14 +710,8 @@ async function* document(path: string, extension: string): AsyncGenerator - rel.Type?.endsWith("/sharedStrings"), - )?.Target; - const sharedPath = sharedTarget - ? NodePath.posix.resolve("/xl", sharedTarget).slice(1) - : "xl/sharedStrings.xml"; - const strings = files.has(sharedPath) ? [...all(read(sharedPath), "si")] : []; + const sharedPath = workbookPartPath("sharedStrings"); + const strings = has(sharedPath) ? [...all(read(sharedPath), "si")] : []; const populatedStrings = strings.map(hasCellText); for (const sheet of all(workbook, "sheet")) { yield `\n## Sheet: ${sheet.attrs.name}\n`; @@ -797,7 +805,7 @@ async function* document(path: string, extension: string): AsyncGenerator { "xl/workbook.xml": '', "xl/_rels/workbook.xml.rels": - '', + '', "catalog/items.xml": "Lantern", - "xl/styles.xml": + "formatting/cells.xml": '', "xl/worksheets/second.xml": '037', From 79979166731a3ed40dc467ced2dcb782233c22f2 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 09:43:34 -0600 Subject: [PATCH 012/221] fix(web): Markdown previews load relative images in timestamped and root folders (#41505) Co-authored-by: Julius Marminge --- .../components/files/FileMarkdownPreview.tsx | 2 +- .../files/FilePreviewPanel.browser.test.tsx | 36 ++++++++++++++++--- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/files/FileMarkdownPreview.tsx b/apps/web/src/components/files/FileMarkdownPreview.tsx index a4b4957201792..f3cc04bf6bf20 100644 --- a/apps/web/src/components/files/FileMarkdownPreview.tsx +++ b/apps/web/src/components/files/FileMarkdownPreview.tsx @@ -21,7 +21,7 @@ export function FileMarkdownPreview(props: { ); const imageBaseDir = lastSeparator >= 0 - ? resolvePathLinkTarget(props.relativePath.slice(0, lastSeparator), props.cwd) + ? resolvePathLinkTarget(props.relativePath.slice(0, lastSeparator + 1), props.cwd) : props.cwd; return ( diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index 07e05010baab3..4a6e5da91b871 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -18,6 +18,7 @@ const state = vi.hoisted(() => ({ optimistic: null as ProjectReadFileResult | null, writeFile: vi.fn(), assetUrl: { _tag: "Loading" } as import("~/assets/assetUrls").AssetUrlState, + assetResources: [] as Array, mintUrl: vi.fn<() => Promise>(), browserAssetMints: 0, openedBrowserUrls: [] as string[], @@ -65,7 +66,13 @@ vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({ vi.mock(import("~/assets/assetUrls"), async (original) => ({ ...(await original()), useAssetUrlRefresh: () => state.mintUrl, - useAssetUrlState: () => state.assetUrl, + useAssetUrlState: ( + _environmentId: unknown, + resource: import("@t3tools/contracts").AssetResource | null, + ) => { + if (resource) state.assetResources.push(resource); + return state.assetUrl; + }, })); vi.mock(import("~/browser/previewRuntime"), async (original) => ({ ...(await original()), @@ -173,6 +180,7 @@ function setup() { state.file = null; state.optimistic = null; state.assetUrl = { _tag: "Loading" }; + state.assetResources = []; state.openedBrowserUrls = []; let mints = 0; state.mintUrl.mockReset().mockImplementation(async () => `/assets/report.docx?mint=${++mints}`); @@ -188,14 +196,18 @@ function setup() { }; } -function markdownPreview(truncated: boolean, contents = "- [ ] Keep the rest of this file\n") { +function markdownPreview( + truncated: boolean, + contents = "- [ ] Keep the rest of this file\n", + relativePath = "tasks.md", +) { state.file = { - relativePath: "tasks.md", + relativePath, contents, byteLength: truncated ? 1_200_000 : contents.length, truncated, }; - return filePreview("tasks.md"); + return filePreview(relativePath); } function filePreview(relativePath: string, workspaceMutationId: string | null = null) { @@ -717,3 +729,19 @@ describe("rendered Markdown select all", () => { await expectFileOnlySelection(); }); }); + +describe("rendered Markdown relative images", () => { + it.each([ + ["2026-11-23T14:05/README.md", "/workspace/2026-11-23T14:05/diagram.png"], + ["/README.md", "/diagram.png"], + ])("resolves relative images in %s against its folder", async (relativePath, expectedPath) => { + using _settings = setup(); + await using _screen = await render( + markdownPreview(false, "![diagram](diagram.png)\n", relativePath), + ); + await vi.waitFor(() => expect(state.assetResources).not.toHaveLength(0)); + expect(state.assetResources).toContainEqual( + expect.objectContaining({ _tag: "media-file", path: expectedPath }), + ); + }); +}); From a2d64160430ab67486717b83d2cbe2f8161430d9 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 17:47:59 +0200 Subject: [PATCH 013/221] fix(server): RTF text in an ANSI font reads as code page 1252 under any document code page (#41508) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 31 +++++++++++++------ .../src/provider/userInputAttachments.test.ts | 20 ++++++++++++ 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 7dfd82f02f187..cf25d9c2f40d2 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -463,6 +463,7 @@ function* notebook(source: string): Generator { // Per-byte decoding only supports the single-byte \fcharset values. const FONT_CODE_PAGES = new Map([ + [0, "windows-1252"], [77, "macintosh"], [161, "windows-1253"], [162, "windows-1254"], @@ -475,6 +476,18 @@ const FONT_CODE_PAGES = new Map([ [238, "windows-1250"], ]); +// Per-byte decoding only supports single-byte code pages. +const singleByteCodePage = (value: number) => + value === 0 + ? "windows-1252" + : value === 866 + ? "ibm866" + : value === 10000 + ? "macintosh" + : value === 874 || (value >= 1250 && value <= 1258) + ? `windows-${value}` + : undefined; + function* rtf(source: string): Generator { if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document"); let state = { @@ -484,10 +497,12 @@ function* rtf(source: string): Generator { uc: 1, font: 0, fontTable: false, + fontFile: false, decoder: new TextDecoder("windows-1252"), }; const stack: Array = []; - // A font's \fcharset, not the document code page, encodes the bytes written in that font. + // A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in + // that font. A \cpg inside \fontfile encodes the font's file name instead. const fonts = new Map(); let defaultFont = 0; const decoder = () => fonts.get(state.font) ?? state.decoder; @@ -561,6 +576,7 @@ function* rtf(source: string): Generator { ) state.skip = true; if (control === "fonttbl") state.fontTable = true; + else if (control === "fontfile") state.fontFile = true; else if (control === "deff") state.font = defaultFont = value; else if (control === "f") { state.font = value; @@ -568,6 +584,9 @@ function* rtf(source: string): Generator { } else if (control === "fcharset" && state.fontTable) { const codePage = FONT_CODE_PAGES.get(value); if (codePage) fonts.set(state.font, new TextDecoder(codePage)); + } else if (control === "cpg" && state.fontTable && !state.fontFile) { + const codePage = singleByteCodePage(value); + if (codePage) fonts.set(state.font, new TextDecoder(codePage)); } if (control === "deleted") state.deleted = value !== 0; else if (control === "v") state.hiddenText = value !== 0; @@ -579,15 +598,7 @@ function* rtf(source: string): Generator { if (control === "mac" || (control === "ansicpg" && value === 10000)) state.decoder = new TextDecoder("macintosh"); else if (control === "ansicpg") { - // Per-byte decoding only supports single-byte code pages. - const label = - value === 0 - ? "windows-1252" - : value === 866 - ? "ibm866" - : value === 874 || (value >= 1250 && value <= 1258) - ? `windows-${value}` - : undefined; + const label = singleByteCodePage(value); if (!label) throw new Error("Unsupported RTF code page"); state.decoder = new TextDecoder(label, { fatal: true }); } else if (control === "uc") { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index ad0430804c63d..be2aab625142d 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -366,6 +366,26 @@ describe("question answer paths", () => { \f0 \'e3\'e1\'c7\'cd\'d9\'c9\f1 : caf\'e9, \f0\plain\'c7a}`, "ملاحظة: café, Ça", ], + [ + "ANSI font under another code page", + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`, + "€5 café", + ], + [ + "font code page", + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`, + "Привет", + ], + [ + "ANSI font in a Macintosh document", + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`, + "pridržana", + ], + [ + "Macintosh font code page", + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0\cpg10000 Geneva;}\f0 Caf\'8e}`, + "Café", + ], [ "font character set outside the font table", String.raw`{\rtf1\ansi{\fonttbl{\f0\fcharset178 A;}{\f0\fcharset0 B;}{\f1\fcharset0 C;}{\f2\fcharset178 D;}{\f2 E;}}{\stylesheet{\s0\f1\fcharset178 N;}}\f0 \'e3\f1\'e3\f2\'e3}`, From 14c697c4f19dbd23d21c2e91c555859f0d482e39 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 17:51:04 +0200 Subject: [PATCH 014/221] fix(web): RTF previews read text in an ANSI font as code page 1252 under any document code page (#41514) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 12 ++++++ .../files/extendedDocumentPreview.ts | 43 ++++++++++++------- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index d7242cc0ba587..8b72060d5d050 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -299,6 +299,18 @@ Third}`; for (const [rtf, expected] of [ [String.raw`{\rtf1\ansi\ansicpg0 Caf\'e9}`, "

Café

"], [String.raw`{\rtf1\ansi\ansicpg866 \'8f\'e0\'a8\'a2\'a5\'e2}`, "

Привет

"], + [ + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`, + "

€5 café

", + ], + [ + String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`, + "

pridržana

", + ], + [ + String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`, + "

Привет

", + ], ] as const) { const decoded = openRtf(bytes(rtf)); if (decoded.type !== "document") throw new Error("Expected document"); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 76c55283854af..f14b35fbbc80e 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -538,6 +538,21 @@ const RTF_CHARACTERS = new Map([ ["rtlmark", "\u200f"], ]); +const rtfCodePageLabel = (codePage: number) => + ( + { + 0: "windows-1252", + 866: "ibm866", + 65001: "utf-8", + 932: "shift_jis", + 936: "gbk", + 949: "euc-kr", + 950: "big5", + 874: "windows-874", + 10000: "macintosh", + } as Record + )[codePage] ?? `windows-${codePage}`; + export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { if (bytes.byteLength > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-large" }); // Keep byte offsets intact for binary destinations and multibyte code pages. @@ -556,8 +571,11 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { uc: 1, font: 0, fontTable: false, + fontFile: false, decoder: new TextDecoder("windows-1252"), }; + // A font's \cpg, else its \fcharset, encodes the bytes written in that font. A \cpg inside + // \fontfile encodes the font's file name instead. const fonts = new Map(); let defaultFont = 0; const stack: (typeof state)[] = []; @@ -668,7 +686,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "fcharset" && state.fontTable) { const label = ( { - 0: state.decoder.encoding, + 0: "windows-1252", 1: state.decoder.encoding, 77: "macintosh", 128: "shift_jis", @@ -688,6 +706,13 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { } as Record )[arg]; if (label) fonts.set(state.font, new TextDecoder(label)); + } else if (word === "fontfile") state.fontFile = true; + else if (word === "cpg" && state.fontTable && !state.fontFile) { + try { + fonts.set(state.font, new TextDecoder(rtfCodePageLabel(arg))); + } catch { + // An unknown font code page leaves the font on its \fcharset. + } } else if ( [ "colortbl", @@ -712,22 +737,8 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { state.skip = true; else if (word === "mac") state.decoder = new TextDecoder("macintosh"); else if (word === "ansicpg") { - const label = - ( - { - 0: "windows-1252", - 866: "ibm866", - 65001: "utf-8", - 932: "shift_jis", - 936: "gbk", - 949: "euc-kr", - 950: "big5", - 874: "windows-874", - 10000: "macintosh", - } as Record - )[arg] ?? `windows-${arg}`; try { - state.decoder = new TextDecoder(label); + state.decoder = new TextDecoder(rtfCodePageLabel(arg)); } catch { throw new PreviewError({ code: "rtf-code-page" }); } From 77c230e45650a5f5f3dcf45f538683eb2383e196 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 10:01:16 -0600 Subject: [PATCH 015/221] fix(web): notebook previews show errors saved without a traceback (#41511) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 20 +++++++++++++++++++ .../files/extendedDocumentPreview.ts | 16 +++++++++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 8b72060d5d050..b32a64fd18373 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -438,6 +438,23 @@ Third}`; "final entry", ], }, + { + output_type: "error", + ename: "ZeroDivisionError", + evalue: "division by zero", + traceback: [], + }, + { + output_type: "error", + evalue: "\u001b[31mbad input\u001b[0m", + traceback: [], + }, + { + output_type: "error", + ename: "RuntimeError", + evalue: "kernel reset", + traceback: ["\u001b[31m\u001b[0m", " \n"], + }, ], }, ], @@ -458,6 +475,9 @@ Third}`; kind: "text", text: "Traceback (most recent call last):\nCell In[3], line 1\n----> 1 fail()\nValueError: preview proof\nfinal entry", }, + { kind: "text", text: "ZeroDivisionError: division by zero" }, + { kind: "text", text: "bad input" }, + { kind: "text", text: "RuntimeError: kernel reset" }, ]); expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow( expect.objectContaining({ code: "notebook-unsupported" }), diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index f14b35fbbc80e..d04f1c9882ee9 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -501,12 +501,16 @@ export function openNotebook(bytes: ArrayBuffer): OfficeWorkerResult { } const html = notebookText(data["text/html"]); if (html.trim() && htmlImagesFit(html)) return { kind: "html" as const, text: html }; - return { - kind: "text" as const, - text: terminalOutputPlainText( - notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)), - ), - }; + const text = terminalOutputPlainText( + notebookText(output.text ?? data["text/plain"] ?? tracebackLines(output.traceback)), + ); + if (text.trim() || output.output_type !== "error") return { kind: "text" as const, text }; + const summary = [output.ename, output.evalue] + .filter((part) => typeof part === "string") + .map((part) => terminalOutputPlainText(notebookText(part))) + .filter((part) => part.trim().length > 0) + .join(": "); + return { kind: "text" as const, text: summary }; }) .filter((output) => output.text.trim().length > 0), }; From e6ba483403910c3b7597d4c2bb1ff117573cb8a8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 08:06:11 -0800 Subject: [PATCH 016/221] fix(server): a declined steer of a delegated completion still wakes the parent (#41521) --- .../src/orchestration-v2/Orchestrator.ts | 3 + .../SteeringCompletion.integration.test.ts | 143 ++++++++++++++++++ 2 files changed, 146 insertions(+) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6c499c3ea32a7..e93b794b7ad71 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7710,6 +7710,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio delivery.generation !== requestedCompletion.generation || delivery.messageId !== command.messageId || (projection.messages.some((candidate) => candidate.id === command.messageId) && + command.steerFollowUpOfRunId === undefined && !isUndeliveredMailboxSteer(projection, command.messageId)) ) { return yield* new OrchestratorDispatchError({ @@ -7786,6 +7787,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandNotice = noticeKind === "command" && command.creationSource === "server"; if ( !freshContext && + // A steer follow-up was declined by the active turn; steering it again loses it. + command.steerFollowUpOfRunId === undefined && // Steering refuses a command, so a notice that reads like one stays queued. !isSlashCommand(command) && (delegatedCompletion !== undefined diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 229fb66ff8791..0fc200d0c5715 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1723,6 +1723,149 @@ it.effect.each(declinedSteerTimings)( }), ); +// regression: #41509 a declined steer of a delegated completion wake must still queue the wake +it.effect("queues a delegated completion wake whose steer the provider declined", () => + Effect.gen(function* () { + const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "steering-declined-delegated-completion", + false, + true, + Effect.void, + true, + undefined, + (turn) => + Effect.fail( + new ProviderAdapter.ProviderAdapterSteerDeclinedError({ + driver, + providerThreadId: turn.providerThread.id, + providerTurnId: turn.providerTurnId, + }), + ), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + const messageId = MessageId.make("message:declined-wake"); + const taskId = NodeId.make("task:declined-wake"); + const parentRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === first.runId, + )!; + const now = yield* DateTime.now; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:declined-wake:cohort"), + type: "run.updated", + threadId, + runId: first.runId, + occurredAt: now, + payload: { + ...parentRun, + delegatedCompletion: { + disposition: "open", + nextGeneration: 2, + delivery: { generation: 1, messageId, taskIds: [taskId] }, + }, + }, + }, + { + id: EventId.make("event:declined-wake:task"), + type: "subagent.updated", + threadId, + runId: first.runId, + nodeId: taskId, + occurredAt: now, + payload: { + id: taskId, + threadId, + runId: first.runId, + parentNodeId: first.rootNodeId, + origin: "app_owned", + createdBy: "agent", + driver, + providerInstanceId: instanceId, + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Do background work", + title: "Background test", + model: null, + completionWake: "always", + completionDelivery: { state: "claimed", observedByRunId: null }, + status: "completed", + result: "done", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("wake"), + threadId, + messageId, + text: "Delegated task completed", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + delegatedCompletion: { parentRunId: first.runId, generation: 1, taskIds: [taskId] }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + const effects = yield* (yield* EffectOutbox.EffectOutboxV2).listByCommandId( + CommandId.make("wake"), + ); + assert.deepEqual( + effects.map((effect) => [effect.request.type, effect.status]), + [["provider-turn.steer", "succeeded"]], + "the declined steer's queue fallback was rejected", + ); + const pending = yield* orchestrator.getThreadProjection(threadId); + const queued = pending.runs.find( + (run) => run.userMessageId === messageId && run.id !== first.runId, + ); + assert.equal(queued?.status, "queued"); + + const turn = pending.providerTurns[0]!; + const settled = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === first.runId && + event.payload.status === "waiting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now }, + }); + yield* Queue.offer(events, { + type: "turn.terminal", + driver, + providerThreadId: turn.providerThreadId, + providerTurnId: turn.id, + runOrdinal: first.runOrdinal, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Fiber.join(settled); + yield* worker.drain(); + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); + assert.equal(started[1]?.message.messageId, messageId, "the parent was never woken"); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #26695 cancelling a Copilot prompt to steer it kills its background agents it.effect("queues a steer until the turn ends when the provider cannot steer it", () => Effect.gen(function* () { From 856b105fa23f9cb9fdd49a8f102cb66a71b78265 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 23 Nov 2026 08:13:01 -0800 Subject: [PATCH 017/221] test(server): HTML preview revision test no longer depends on a fine kernel clock (#40931) Co-authored-by: Claude Opus 5.5 --- apps/server/src/assets/AssetAccess.test.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 64831512a9ef7..0f3f8519bddc7 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1306,8 +1306,16 @@ describe("AssetAccess", () => { const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-asset-revision-" }); const pages = path.join(root, "pages"); yield* fileSystem.makeDirectory(pages); + // Coarse kernel clocks can stamp two quick same-size writes alike, so each edit gets its own mtime. + let editedAt = 1_000; const write = (name: string, text: string) => - fileSystem.writeFileString(path.join(pages, name), text); + fileSystem + .writeFileString(path.join(pages, name), text) + .pipe( + Effect.andThen( + Effect.promise(() => NodeFSP.utimes(path.join(pages, name), ++editedAt, editedAt)), + ), + ); yield* write("a.html", ''); yield* write("a.css", "body { color: red; }"); yield* write("b.html", "

b

"); From ba70b56b14b0781d57beea439eae1c2282a03e30 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 23 Nov 2026 08:19:10 -0800 Subject: [PATCH 018/221] test(server): PeerLinks refused-address test no longer reuses its closed port (#40415) Co-authored-by: Claude Opus 5.5 --- apps/server/src/peer/PeerLinks.test.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 8f1d6cc381d63..3861fbb97b074 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -859,9 +859,8 @@ it.effect("linking a picked machine that answers nowhere names it and links noth it.live("linking an address with nothing listening says so, unlike one that is not T3 Code", () => Effect.scoped( Effect.gen(function* () { - const closed = yield* Effect.scoped( - serveRaw(() => Effect.succeed(HttpServerResponse.empty({ status: 404 }))), - ); + // Any test worker can reuse a closed ephemeral port; port 2 is privileged and outside that range. + const closed = "http://127.0.0.1:2"; const notT3 = yield* serveRaw(() => Effect.succeed( HttpServerResponse.text("

Not Found

", { status: 404, contentType: "text/html" }), From 3b08d975ab58ed19ff7c61b077f69c4bd818989f Mon Sep 17 00:00:00 2001 From: Shadman Taqi <61359614+iamshadmantaqi@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:20:14 +0600 Subject: [PATCH 019/221] fix(web): the desktop app plays thread sounds after a reload (#41518) Co-authored-by: Julius Marminge --- ...NotificationCoordinator.badge.browser.test.ts | 16 +++++++++++++++- .../components/ThreadNotificationCoordinator.tsx | 2 ++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts index 7da8504990fe6..6b2414dfaf38b 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts +++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts @@ -16,6 +16,7 @@ const state = vi.hoisted(() => ({ shells: null as unknown as { set: (id: string, value: unknown) => void }, navigate: vi.fn(), sound: vi.fn(), + unlock: vi.fn(), badge: vi.fn(), settingsListeners: new Set<() => void>(), })); @@ -80,7 +81,7 @@ vi.mock(import("../hooks/useSettings"), async (original) => ({ vi.mock(import("../threadNotifications"), async (original) => ({ ...(await original()), playNotificationSound: state.sound, - unlockNotificationAudio: vi.fn(), + unlockNotificationAudio: state.unlock, setNotificationBadge: state.badge, })); @@ -293,6 +294,19 @@ it("presents completion notifications and sound as soon as the shell completes", expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function)); }); +it.each([ + { client: "desktop app", when: "at startup", bridge: {}, beforeGesture: 1 }, + { client: "browser", when: "on the first gesture", bridge: undefined, beforeGesture: 0 }, +])("readies notification sound in the $client $when", async ({ bridge, beforeGesture }) => { + await using app = setup(); + using _bridge = stubGlobal("desktopBridge", bridge); + state.mode = "sound"; + app.start(); + expect(state.unlock).toHaveBeenCalledTimes(beforeGesture); + document.dispatchEvent(new Event("pointerdown")); + expect(state.unlock).toHaveBeenCalledTimes(beforeGesture + 1); +}); + it.each([false, true])( "presents one completion when a monitor ends with a final wake (disconnected: %s)", async (disconnect) => { diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index e2801c97d6e8d..7f91d48643bbf 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -408,6 +408,8 @@ export function startThreadNotifications( }); } if (hasNotificationSound(nextMode)) { + // Electron's default autoplay policy needs no gesture, unlike browsers. + if (window.desktopBridge) unlockNotificationAudio(); document.addEventListener("pointerdown", unlockNotificationAudio); document.addEventListener("keydown", unlockNotificationAudio); stops.push(() => { From 9fae2cc22888b391d1935716f44b1d7447aa2b6e Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 10:35:57 -0600 Subject: [PATCH 020/221] fix(web): accept TIFF Exif and GPS pointers stored as IFD type 13 (#41526) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 42 ++++++++++++++----- .../components/files/imageDecode.worker.ts | 3 +- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 77e339925c97e..10c013cc04723 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -514,14 +514,16 @@ describe("bounded binary previews", () => { } }); - it("keeps WhiteIsZero TIFF brightness and alpha with SubIFDs tags and rejects oversized metadata before decoding", async () => { + it("keeps WhiteIsZero TIFF brightness and alpha with SubIFDs and type-13 ExifIFD pointers and rejects invalid metadata before decoding", async () => { let bytes = new ArrayBuffer(0); + let exifEntry = 0; for (const { pixels, expected } of [ { pixels: [0, 255], expected: [255, 255, 255, 255, 0, 0, 0, 255] }, { pixels: [0, 255, 255, 0], expected: [255, 255, 255, 255, 0, 0, 0, 0] }, ]) { const samples = pixels.length / 2; - const start = samples === 2 ? 158 : 146; + const start = samples === 2 ? 170 : 158; + const exif = start + pixels.length; const tags = [ [256, 2], [257, 1], @@ -535,8 +537,10 @@ describe("bounded binary previews", () => { [284, 1], [330, 0, 13], ...(samples === 2 ? [[338, 2]] : []), + [34665, exif, 13], ]; - bytes = new ArrayBuffer(start + pixels.length); + exifEntry = 10 + (tags.length - 1) * 12; + bytes = new ArrayBuffer(exif + 8); const view = new DataView(bytes); view.setUint16(0, 0x4949); view.setUint16(2, 42, true); @@ -563,14 +567,30 @@ describe("bounded binary previews", () => { URL.revokeObjectURL(src); } } - new DataView(bytes).setUint32(14, 1_000_000, true); - const invalid = URL.createObjectURL(new Blob([bytes])); - try { - await expect( - decodeImagePreview(invalid, false, new AbortController().signal), - ).rejects.toThrow("metadata"); - } finally { - URL.revokeObjectURL(invalid); + for (const [mutate, message] of [ + [ + (view: DataView) => view.setUint16(exifEntry + 2, 3, true), + "Invalid TIFF metadata pointer.", + ], + [ + (view: DataView) => view.setUint32(exifEntry + 4, 2, true), + "Invalid TIFF metadata pointer.", + ], + [ + (view: DataView) => view.setUint32(14, 1_000_000, true), + "This TIFF has too much or truncated metadata.", + ], + ] as const) { + const copy = bytes.slice(0); + mutate(new DataView(copy)); + const invalid = URL.createObjectURL(new Blob([copy])); + try { + await expect( + decodeImagePreview(invalid, false, new AbortController().signal), + ).rejects.toThrow(message); + } finally { + URL.revokeObjectURL(invalid); + } } }); }); diff --git a/apps/web/src/components/files/imageDecode.worker.ts b/apps/web/src/components/files/imageDecode.worker.ts index 9cd3140308612..a3661b22612fb 100644 --- a/apps/web/src/components/files/imageDecode.worker.ts +++ b/apps/web/src/components/files/imageDecode.worker.ts @@ -34,7 +34,8 @@ function validateTiffMetadata(bytes: ArrayBuffer) { if (start + length > bytes.byteLength || allocation > 8 * 1024 * 1024) throw new PreviewError({ code: "tiff-metadata-truncated" }); if (tag === 0x8769 || tag === 0x8825) { - if (type !== 4 || values !== 1) throw new PreviewError({ code: "tiff-metadata-pointer" }); + if ((type !== 4 && type !== 13) || values !== 1) + throw new PreviewError({ code: "tiff-metadata-pointer" }); inspect(view.getUint32(entry + 8, littleEndian), depth + 1); } } From f58085a1c2e5bea0b020ee2d4d69f8768b7b228d Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 10:38:17 -0600 Subject: [PATCH 021/221] fix(server): EPUBs with a percent-encoded package path extract their chapters (#41523) Co-authored-by: Julius Marminge --- .../server/src/provider/documentTextWorker.ts | 6 ++++- .../src/provider/userInputAttachments.test.ts | 27 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index cf25d9c2f40d2..027029139a77e 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -838,7 +838,7 @@ async function* document(path: string, extension: string): AsyncGenerator [item.attrs.id, item.attrs.href]), diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index be2aab625142d..2e44f3501355c 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -741,6 +741,33 @@ describe("question answer paths", () => { ], absent: ["[Extracted text truncated"], }, + { + ext: "epub", + parts: { + "META-INF/container.xml": + '', + "My Book/book 1.opf": + '', + "My Book/ch1.xhtml": "

Percent-encoded rootfile chapter text.

", + }, + expected: ["Percent-encoded rootfile chapter text."], + absent: ["[Skipped document part", "[Extracted text truncated"], + }, + { + ext: "epub", + parts: { + "META-INF/container.xml": + '', + "OPS/book%201.opf": + '', + "ops/book 1.opf": + '', + "OPS/correct.xhtml": "

Correct primary chapter

", + "ops/other.xhtml": "

Wrong alternate chapter

", + }, + expected: ["Correct primary chapter"], + absent: ["Wrong alternate chapter", "[Skipped document part"], + }, ...[false, true].flatMap((bom) => [false, true].map((bigEndian) => { const encode = (source: string) => { From e2e8a49d972219e926f0940246208e82d129c87a Mon Sep 17 00:00:00 2001 From: Anton Metzner Rodriguez Date: Mon, 23 Nov 2026 18:08:22 +0100 Subject: [PATCH 022/221] fix(web): a PDF keeps its place when the pane is resized (#41537) Co-authored-by: Julius Marminge --- .../files/PdfViewer.browser.test.tsx | 33 +++++++++++++++++++ apps/web/src/components/files/PdfViewer.tsx | 15 +++++---- apps/web/src/components/files/pdfLayout.ts | 12 +++++++ 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/files/PdfViewer.browser.test.tsx b/apps/web/src/components/files/PdfViewer.browser.test.tsx index ef339999e8d10..81bf3bcf91364 100644 --- a/apps/web/src/components/files/PdfViewer.browser.test.tsx +++ b/apps/web/src/components/files/PdfViewer.browser.test.tsx @@ -175,6 +175,39 @@ it("keeps the painted page while its width changes, then repaints it without a b } }); +it("keeps the page in view, with its painted canvas, when the pane narrows", async () => { + const page = { box: "0 0 612 792", rotate: 0, text: "BT /F1 24 Tf 30 700 Td (Text) Tj ET" }; + const url = URL.createObjectURL(testPdf(Array.from({ length: 6 }, () => page))); + try { + const container = document.createElement("div"); + container.style.cssText = "display:flex;width:500px;height:300px"; + await using screen = await render( + , + { container }, + ); + await expect.element(screen.getByText("4 / 6 pages"), { timeout: 10_000 }).toBeVisible(); + const region = screen.container.querySelector('[role="region"]')!; + const canvas = region.querySelector('canvas[aria-label="Page 4"]')!; + await vi.waitFor(() => expect(canvas.width).toBeGreaterThan(300)); + + container.style.width = "300px"; + await vi.waitFor(() => { + const top = region.getBoundingClientRect().top; + const box = canvas.getBoundingClientRect(); + expect(box.width).toBe(region.clientWidth - 32); + expect(box.top).toBeLessThanOrEqual(top); + expect(box.bottom).toBeGreaterThan(top); + }); + await expect.element(screen.getByText("4 / 6 pages")).toBeVisible(); + } finally { + URL.revokeObjectURL(url); + } +}); + it("jumps to the first hit while still counting and keeps later manual navigation", async () => { setup(4); const page = (text: string) => ({ diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index 31faf628fbeb9..9842a621c0302 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -27,6 +27,7 @@ import { pdfPageScrollTop, pdfPageText, pdfPageWidth, + pdfResizedScrollTop, pdfRestoredScrollTop, PDF_MAX_ZOOM, PDF_MIN_ZOOM, @@ -263,7 +264,7 @@ export default function PdfViewer(props: { const [zoom, setZoom] = useState(initialView.zoom); const [pageWidth, setPageWidth] = useState(612); const [viewport, setViewport] = useState({ width: 600, height: 800 }); - const [scrollTop, setScrollTop] = useState(0); + const [scrolled, setScrolled] = useState({ top: 0, width: 0, pdf }); const [query, setQuery] = useState(""); const [matches, setMatches] = useState([]); const [finding, setFinding] = useState(false); @@ -338,6 +339,9 @@ export default function PdfViewer(props: { }, []); const { scale, width } = pdfPageWidth(viewport.width, pageWidth, zoom); const offsets = pdfPageOffsets(ratios, width); + // A new page width moves every page, so the place in view has a new offset before the DOM scrolls. + const resized = pdf !== null && scrolled.pdf === pdf && scrolled.width !== width; + const scrollTop = resized ? pdfResizedScrollTop(ratios, scrolled, width) : scrolled.top; const current = currentPdfPage(offsets, ratios.length, scrollTop); const visible = visiblePdfPages(ratios, offsets, scrollTop, viewport.height); // Stable callbacks let page canvases survive scroll and find updates. @@ -374,7 +378,7 @@ export default function PdfViewer(props: { top: pdfRestoredScrollTop(ratios, width, initialView, savedPosition?.width), left: initialView.left, }); - setScrollTop(node.scrollTop); + setScrolled({ top: node.scrollTop, width, pdf }); saveView(node); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the saved PDF scroll position after the loaded document's page layout commits. @@ -392,7 +396,7 @@ export default function PdfViewer(props: { }; setZoom(value); }; - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the DOM scroll anchor after the new zoom width has committed to page layout. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the DOM scroll anchor after a zoom or resize has committed the new page width. useLayoutEffect(() => { const anchor = zoomAnchor.current; zoomAnchor.current = null; @@ -402,7 +406,7 @@ export default function PdfViewer(props: { node.scrollTo({ top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width, }); - } + } else if (resized) node.scrollTo({ top: scrollTop }); saveView(node, anchor !== null); }); const firstMatch = matches[0]; @@ -561,8 +565,7 @@ export default function PdfViewer(props: { tabIndex={0} className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto scrollbar-gutter-stable bg-muted/40" onScroll={(event) => { - const top = event.currentTarget.scrollTop; - setScrollTop(top); + setScrolled({ top: event.currentTarget.scrollTop, width, pdf }); saveView(event.currentTarget); }} onKeyDown={(event) => { diff --git a/apps/web/src/components/files/pdfLayout.ts b/apps/web/src/components/files/pdfLayout.ts index 9292fcf583b46..0f48a112aa07d 100644 --- a/apps/web/src/components/files/pdfLayout.ts +++ b/apps/web/src/components/files/pdfLayout.ts @@ -66,6 +66,18 @@ export function pdfRestoredScrollTop( ); } +/** Where the place at `from.top` lands after the page width changes from `from.width`. */ +export function pdfResizedScrollTop( + ratios: readonly number[], + from: { top: number; width: number }, + width: number, +) { + const offsets = pdfPageOffsets(ratios, from.width); + const page = currentPdfPage(offsets, ratios.length, from.top); + const offset = from.top - (offsets[page]! - PDF_PAGE_GAP); + return pdfRestoredScrollTop(ratios, width, { page, offset }, from.width); +} + export function pdfPageText( items: readonly ({ str: string; hasEOL: boolean } | { type: string })[], ) { From 990412468340b8362f82610de0eae70a5171abb7 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 11:09:55 -0600 Subject: [PATCH 023/221] fix(web): EPUBs with a percent-encoded package path open in the file preview (#41540) Co-authored-by: Julius Marminge --- .../components/files/FilePreviewPanel.test.ts | 26 +++++++++++++++++++ .../files/extendedDocumentPreview.ts | 5 ++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index b32a64fd18373..0b4d7dc46b49f 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -667,4 +667,30 @@ Third}`; expect(result.pages[1]!.html).toContain('src="data:image/png;base64,'); expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/); }); + + it.each([ + ["percent-encoded", "My%20Book/book%201.opf", "My Book/book 1.opf", "My Book/one.xhtml"], + ["literal percent", "My%20Book/book.opf", "My%20Book/book.opf", "My%20Book/one.xhtml"], + ["malformed percent", "Book%ZZ/book.opf", "Book%ZZ/book.opf", "Book%ZZ/one.xhtml"], + ])( + "reads EPUB packages with %s rootfile paths", + async (_label, fullPath, packagePath, chapterPath) => { + const archive = new JSZip() + .file( + "META-INF/container.xml", + ``, + ) + .file( + packagePath, + '', + ) + .file( + chapterPath, + "First

Hello

", + ); + const result = await openEpub(archive); + if (result.type !== "document") throw new Error("Expected document"); + expect(result.pages).toEqual([{ title: "First", html: "

Hello

" }]); + }, + ); }); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index d04f1c9882ee9..f57d9c59a101d 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -423,8 +423,9 @@ export async function openDocument( export async function openEpub(archive: JSZip): Promise { markupBytes = 0; const container = parseXml((await archive.file("META-INF/container.xml")?.async("string")) ?? ""); - const rootfile = find(container, "rootfile")[0]?.attrs["full-path"]; - if (!rootfile || !archive.file(rootfile)) throw new PreviewError({ code: "epub-no-package" }); + const fullPath = find(container, "rootfile")[0]?.attrs["full-path"] ?? ""; + const rootfile = [archivePath("", fullPath), fullPath].find((path) => path && archive.file(path)); + if (!rootfile) throw new PreviewError({ code: "epub-no-package" }); const packageRoot = parseXml(await archive.file(rootfile)!.async("string")); const manifest = new Map(find(packageRoot, "item").map((item) => [item.attrs.id, item])); const spine = find(packageRoot, "itemref"); From 7182abeeaab345f8a8e863a7835aead9b50ae57f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 09:19:01 -0800 Subject: [PATCH 024/221] fix(client-runtime): command failures show the server's text for string defects (#41550) --- .../src/errors/translatable.test.ts | 21 +++++++++++++++++++ packages/client-runtime/src/state/runtime.ts | 4 +++- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 packages/client-runtime/src/errors/translatable.test.ts diff --git a/packages/client-runtime/src/errors/translatable.test.ts b/packages/client-runtime/src/errors/translatable.test.ts new file mode 100644 index 0000000000000..de0339d9fd2d7 --- /dev/null +++ b/packages/client-runtime/src/errors/translatable.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; +import * as Schema from "effect/Schema"; + +import { squashAtomCommandFailure } from "../state/runtime.ts"; +import { thrownErrorMessage } from "./translatable.ts"; + +const decodeDefect = Schema.decodeUnknownSync(Schema.Defect()); + +describe("thrownErrorMessage", () => { + it("shows the text of a string defect that came back over RPC", () => { + const defect = decodeDefect( + "RPC contract is registered but unavailable in the control plane: projectClone.start", + ); + const error = squashAtomCommandFailure({ cause: Cause.die(defect) }); + + expect(thrownErrorMessage(error)).toBe( + "RPC contract is registered but unavailable in the control plane: projectClone.start", + ); + }); +}); diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index f91f838db78b0..b4674a07cb469 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -404,7 +404,9 @@ export function isAtomCommandInterrupted(result: AtomCommandResult; }): unknown { - return Cause.squash(result.cause); + const squashed = Cause.squash(result.cause); + // A server `Effect.die("text")` decodes over RPC as a bare string; callers read `Error`s. + return typeof squashed === "string" ? new Error(squashed) : squashed; } export async function settleAsyncResult( From 1c9ccc7127c386a50644535070ffc9168fbf8d74 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 09:29:00 -0800 Subject: [PATCH 025/221] fix(web): a grouped project's folder New thread starts on the viewed machine's copy (#41554) --- .../src/components/Sidebar.browser.test.tsx | 61 +++++++++++++++++++ apps/web/src/components/Sidebar.tsx | 13 +++- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 1fb930f55fabc..87f43d9f901f6 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -25,6 +25,7 @@ import { useNowMinute } from "../hooks/useNowMinute"; import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities"; +import { useConnectedEnvironmentIds, usePrimaryEnvironmentId } from "../state/environments"; import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; @@ -40,6 +41,7 @@ vi.mock(import("../state/olderSettledShelf"), async (original) => { return { ...actual, useOlderSettledShelf: vi.fn(actual.useOlderSettledShelf) }; }); vi.mock("../state/entities", { spy: true }); +vi.mock("../state/environments", { spy: true }); vi.mock("../hooks/useHandleNewThread", { spy: true }); vi.mock("../hooks/useNowMinute", { spy: true }); vi.mock("../hooks/useThreadRouteTarget", { spy: true }); @@ -132,6 +134,65 @@ describe("sidebar header new thread", () => { }); }); +// regression: #41549 a grouped project's folder New thread went to the primary copy +describe("sidebar project folder new thread", () => { + it("starts in the copy of the viewed thread, as the new-thread shortcut does", async () => { + using stack = new DisposableStack(); + const previousSettings = getClientSettings(); + stack.defer(() => __setClientSettingsForTests(previousSettings)); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, boringSidebarEnabled: true }); + const primary = EnvironmentId.make("local"); + const dev1 = EnvironmentId.make("dev1"); + const repositoryIdentity = { + canonicalKey: "github.com/acme/demo-repo", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "https://github.com/acme/demo-repo.git", + }, + displayName: "acme/demo-repo", + }; + const primaryCopy = { ...project("demo-primary"), repositoryIdentity }; + const dev1Copy = { + ...project("demo-dev1"), + environmentId: dev1, + repositoryIdentity, + }; + vi.mocked(usePrimaryEnvironmentId).mockReturnValue(primary); + vi.mocked(useConnectedEnvironmentIds).mockReturnValue([primary, dev1]); + vi.mocked(useProjects).mockReturnValue([primaryCopy, dev1Copy]); + const dev1Thread = makeThreadFixture({ + environmentId: dev1, + id: ThreadId.make("dev1-thread"), + projectId: dev1Copy.id, + title: "dev1 work", + }); + vi.mocked(useQuietThreadShells).mockReturnValue([dev1Thread]); + const threadRef = scopeThreadRef(dev1, dev1Thread.id); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef }); + const dev1ProjectRef = scopeProjectRef(dev1, dev1Copy.id); + const startThread = vi.fn().mockResolvedValue(null); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: dev1Thread, + defaultProjectRef: dev1ProjectRef, + defaultProjectFallbackReady: true, + handleNewThread: startThread, + routeDraftId: null, + routeThreadRef: threadRef, + }); + + await using screen = await render( + + + , + ); + await userEvent.click(screen.getByRole("button", { name: "New thread in acme/demo-repo" })); + + expect(startThread).toHaveBeenCalledExactlyOnceWith(dev1ProjectRef); + }); +}); + // regression: #38623 unsent drafts are listed above threads but mod+1..9 skipped them describe("sidebar numbered jumps", () => { it("numbers the unsent draft at the top before the threads below it", async () => { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 9c1918be6b8e7..59fcb56bfce9d 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -114,6 +114,7 @@ import { selectProjectGroupingSettings, } from "@t3tools/client-runtime/state/project-grouping"; import { + buildSidebarProjectPickerEntries, projectGroupsSpanEnvironments, resolveSidebarProjectScopeKeys, getSidebarProjectSettingsKey, @@ -135,7 +136,7 @@ import { useProjectPin } from "../hooks/useProjectGroupUpdate"; import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { registerSettleAndAdvance } from "../settleAndAdvance"; -import { startNewThreadFromContext } from "../lib/chatThreadActions"; +import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions"; import { useClientSettings } from "../hooks/useSettings"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; @@ -1267,7 +1268,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); const startThreadInProjectFolder = useStableCallback((group: SidebarProjectSnapshot) => { if (isMobile) setOpenMobile(false); - void handleNewThread(scopeProjectRef(group.environmentId, group.id)); + const [entry] = buildSidebarProjectPickerEntries({ + groups: [group], + preferredProjectRef: resolveThreadActionProjectRef({ + ...newThreadContext, + activeThread: newThreadContext.activeThread ?? undefined, + }), + }); + const target = entry?.targetProject ?? group; + void handleNewThread(scopeProjectRef(target.environmentId, target.id)); }); const handleProjectFolderContextMenu = useStableCallback( ( From a9bec417292b06e3c180bb0ee6b1eb9e70d47986 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 11:31:28 -0600 Subject: [PATCH 026/221] fix(web): Office previews open files with malformed external links or spaced sheet names (#41547) Co-authored-by: Julius Marminge --- .../components/files/officeArchive.test.ts | 85 ++++++++++++++++++- .../web/src/components/files/officeArchive.ts | 26 +++--- 2 files changed, 100 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/files/officeArchive.test.ts b/apps/web/src/components/files/officeArchive.test.ts index 7e50bf5c80b02..fd8718e21fdcf 100644 --- a/apps/web/src/components/files/officeArchive.test.ts +++ b/apps/web/src/components/files/officeArchive.test.ts @@ -15,6 +15,7 @@ async function wordFile( body: string, parts: Partial> = {}, section = "", + extraRels = "", ) { const zip = new JSZip(); zip.file( @@ -31,7 +32,7 @@ async function wordFile( parts, ) .map((part) => relationship(part, `${part}.xml`)) - .join("")}`, + .join("")}${extraRels}`, ); for (const [part, xml] of Object.entries(parts)) zip.file(`word/${part}.xml`, xml); zip.file( @@ -148,4 +149,86 @@ describe("Word preview limits", () => { expect(await result.part("word/footnotes.xml")).toBe(footnotes); expect(await result.part("word/document.xml")).toContain("Body"); }); + + it("drops a malformed external hyperlink relationship while keeping body text", async () => { + const result = await prepared( + await wordFile( + paragraph("Body text"), + {}, + "", + ``, + ), + ); + expect(result.truncated).toBe(false); + expect(await result.part("word/document.xml")).toContain("Body text"); + expect(await result.part("word/_rels/document.xml.rels")).not.toContain("badLink"); + }); +}); + +async function workbookFile( + target: string, + sheetPath: string, + extraRels = "", + targetMode = "Internal", +) { + const zip = new JSZip(); + zip.file( + "[Content_Types].xml", + ``, + ); + zip.file( + "_rels/.rels", + `${relationship("officeDocument", "xl/workbook.xml")}`, + ); + zip.file( + "xl/workbook.xml", + ``, + ); + zip.file( + "xl/_rels/workbook.xml.rels", + `${extraRels}`, + ); + zip.file( + sheetPath, + `42`, + ); + return zip.generateAsync({ type: "arraybuffer" }); +} + +describe("Workbook relationship targets", () => { + it.each(["sheet 1.xml", "sheet%201.xml", "sheet#1.xml"])( + "prepares a worksheet whose ZIP name matches its target literally (%s)", + async (name) => { + const result = await prepareOffice( + await workbookFile(`worksheets/${name}`, `xl/worksheets/${name}`), + "xlsx", + ); + const zip = await JSZip.loadAsync(result.bytes); + expect(result.truncated).toBe(false); + expect(await zip.file(`xl/worksheets/${name}`)?.async("string")).toContain("42"); + }, + ); + + it("refuses a worksheet whose relationship is external", async () => { + await expect( + prepareOffice( + await workbookFile("worksheets/sheet2.xml", "xl/worksheets/sheet2.xml", "", "External"), + "xlsx", + ), + ).rejects.toMatchObject({ code: "workbook-sheet-count" }); + }); + + it("handles a malformed external relationship in workbook relationships", async () => { + const result = await prepareOffice( + await workbookFile( + "worksheets/sheet1.xml", + "xl/worksheets/sheet1.xml", + ``, + ), + "xlsx", + ); + const zip = await JSZip.loadAsync(result.bytes); + expect(result.truncated).toBe(false); + expect(await zip.file("xl/worksheets/sheet1.xml")?.async("string")).toContain("42"); + }); }); diff --git a/apps/web/src/components/files/officeArchive.ts b/apps/web/src/components/files/officeArchive.ts index aabfc0b21f6dc..0e9b59ab8e9eb 100644 --- a/apps/web/src/components/files/officeArchive.ts +++ b/apps/web/src/components/files/officeArchive.ts @@ -598,10 +598,16 @@ async function boundWorkbook(archive: JSZip) { relationships.on("opentag", (tag) => { if (tag.local !== "Relationship") return; const type = tag.attributes.Type?.value; - const path = new URL( - tag.attributes.Target?.value ?? "", - "https://docx.invalid/xl/workbook.xml", - ).pathname.slice(1); + const target = tag.attributes.Target?.value ?? ""; + // Resolve as the engine does: literal ZIP names split on `/`, never URL syntax or escapes. + const segments = target.startsWith("/") ? [] : ["xl"]; + for (const segment of target.split("/")) { + if (segment === "..") segments.pop(); + else if (segment && segment !== ".") segments.push(segment); + } + const external = tag.attributes.TargetMode?.value.toLowerCase() === "external"; + // The engine reads an external worksheet from its default part, so leave it unresolved to refuse it. + const path = external && type?.endsWith("/worksheet") ? "" : segments.join("/"); if (type?.endsWith("/worksheet")) paths.set(tag.attributes.Id?.value ?? "", path); else if (/\/(?:chartsheet|dialogsheet|xlMacrosheet|xlIntlMacrosheet)$/.test(type ?? "")) otherSheets.add(tag.attributes.Id?.value ?? ""); @@ -755,13 +761,13 @@ function wordPartTypes() { const external = attr("TargetMode").toLowerCase() === "external" || /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(attr("Target")); - const folder = path === "_rels/.rels" ? "" : path.replace(/_rels\/[^/]+\.rels$/, ""); - // Preserve archive URL resolution, including literal query/fragment - // characters in ZIP names rather than silently classifying another file. - const target = new URL(attr("Target"), `https://docx.invalid/${folder}`) - .toString() - .slice("https://docx.invalid/".length); if (!external) { + const folder = path === "_rels/.rels" ? "" : path.replace(/_rels\/[^/]+\.rels$/, ""); + // Preserve archive URL resolution, including literal query/fragment + // characters in ZIP names rather than silently classifying another file. + const target = new URL(attr("Target"), `https://docx.invalid/${folder}`) + .toString() + .slice("https://docx.invalid/".length); if ( !WORD_BINARY_PARTS.has(role) && role !== "hyperlink" && From fa2ee196b5b4d371aecdedbebc3cdbc0c20c8553 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 09:35:37 -0800 Subject: [PATCH 027/221] fix(web): archived threads settings stay responsive with thousands of threads (#41539) --- .../settings/ArchivedThreadsPanel.tsx | 175 ++++++++++++------ 1 file changed, 118 insertions(+), 57 deletions(-) diff --git a/apps/web/src/components/settings/ArchivedThreadsPanel.tsx b/apps/web/src/components/settings/ArchivedThreadsPanel.tsx index c44d37a359b1b..0ea512be7f9d5 100644 --- a/apps/web/src/components/settings/ArchivedThreadsPanel.tsx +++ b/apps/web/src/components/settings/ArchivedThreadsPanel.tsx @@ -23,7 +23,8 @@ import { useSearchableSetting } from "./settingsSearch"; import { ProjectFavicon } from "../ProjectFavicon"; import { msg, T, useGT, useMessages } from "gt-react"; -import { useRef, useState } from "react"; +import { type ReactNode, useRef, useState } from "react"; +import { observeIntersection } from "~/lib/observeIntersection"; import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; const ARCHIVE_ACTIONS = [ @@ -44,6 +45,43 @@ const ARCHIVE_ACTIONS = [ ] as const; type ArchiveAction = (typeof ARCHIVE_ACTIONS)[number]["action"]; +const ARCHIVED_ROW_CHUNK_SIZE = 50; +const ESTIMATED_ARCHIVED_ROW_PX = 67; + +// Thousands of archived threads would mount at once, so each chunk of rows mounts only near the +// visible part of the settings scroller and otherwise keeps its last measured height. +function ArchivedThreadChunk(props: { + readonly rowCount: number; + readonly initiallyMounted: boolean; + readonly renderRows: () => ReactNode; +}) { + const { rowCount } = props; + const [view, setView] = useState({ + near: props.initiallyMounted, + rowHeight: ESTIMATED_ARCHIVED_ROW_PX, + }); + return ( +
{ + if (!node) return; + return observeIntersection( + node, + (entry) => + setView({ + near: entry.isIntersecting, + rowHeight: entry.boundingClientRect.height / rowCount, + }), + { root: node.closest("[data-settings-page-scroll]"), rootMargin: "1200px 0px" }, + ); + }} + className="*:not-first:border-t *:not-first:border-border/50" + style={view.near ? undefined : { height: view.rowHeight * rowCount }} + > + {view.near ? props.renderRows() : null} +
+ ); +} + export function ArchivedThreadsPanel() { const searchableSetting = useSearchableSetting(); const gt = useGT(); @@ -139,15 +177,21 @@ export function ArchivedThreadsPanel() { } } } - const sortedGroups = Array.from(groups, ([key, group]) => ({ - ...group, - key, - threads: group.threads.toSorted((left, right) => { - const leftKey = left.archivedAt ?? left.createdAt; - const rightKey = right.archivedAt ?? right.createdAt; - return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id); - }), - })); + const sortedGroups = []; + let firstRow = 0; + for (const [key, group] of groups) { + sortedGroups.push({ + ...group, + key, + firstRow, + threads: group.threads.toSorted((left, right) => { + const leftKey = left.archivedAt ?? left.createdAt; + const rightKey = right.archivedAt ?? right.createdAt; + return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id); + }), + }); + firstRow += group.threads.length; + } return { groups: sortedGroups, hasMultipleEnvironments }; })(); @@ -210,6 +254,54 @@ export function ArchivedThreadsPanel() { reportFailure(result, gt("Archived thread action failed")); }; + const renderRow = (thread: ArchivedThread) => { + const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); + return ( + { + event.preventDefault(); + void handleContextMenu(thread, { x: event.clientX, y: event.clientY }); + }} + title={thread.title} + description={ + + {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null} + + Archived + {" \u00b7 Created "} + + + + } + control={ +
+ {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => ( + + void handleThreadAction(action, thread)} + /> + } + > + + + {m(label)} + + ))} +
+ } + /> + ); + }; + return ( {archivedGroups.length === 0 ? ( @@ -240,59 +332,28 @@ export function ArchivedThreadsPanel() { /> ) : ( - archivedGroups.map(({ key, project, title, threads: projectThreads }, index) => ( + archivedGroups.map(({ key, project, title, firstRow, threads: projectThreads }, index) => ( } > - {projectThreads.map((thread) => { - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - return ( - { - event.preventDefault(); - void handleContextMenu(thread, { x: event.clientX, y: event.clientY }); - }} - title={thread.title} - description={ - - {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null} - - Archived - {" \u00b7 Created "} - - - - } - control={ -
- {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => ( - - void handleThreadAction(action, thread)} - /> - } - > - - - {m(label)} - - ))} -
- } - /> - ); - })} + {Array.from( + { length: Math.ceil(projectThreads.length / ARCHIVED_ROW_CHUNK_SIZE) }, + (_, chunkIndex) => { + const start = chunkIndex * ARCHIVED_ROW_CHUNK_SIZE; + const rows = projectThreads.slice(start, start + ARCHIVED_ROW_CHUNK_SIZE); + return ( + rows.map(renderRow)} + /> + ); + }, + )}
)) )} From 6aad800ecfe268c158af60d1102c3ec4acc9bab9 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 11:53:50 -0600 Subject: [PATCH 028/221] fix(server): EPUB chapters with a query in their href extract their text (#41553) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 2 +- apps/server/src/provider/userInputAttachments.test.ts | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 027029139a77e..3fe14f40ddbf6 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -864,7 +864,7 @@ async function* document(path: string, extension: string): AsyncGenerator { ], absent: ["[Extracted text truncated"], }, + { + ext: "epub", + parts: { + "META-INF/container.xml": '', + "book.opf": + '', + "q?1.xhtml": "

Encoded question mark chapter text.

", + }, + expected: ["Encoded question mark chapter text."], + absent: ["[Skipped document part", "[Extracted text truncated"], + }, { ext: "epub", parts: { From 0ea0db39e272a472f26b97e9bfc3a6c7805112f2 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 12:01:33 -0600 Subject: [PATCH 029/221] fix(shared): PascalCase test doubles like MockTransport.ts count as mocks (#41561) Co-authored-by: Julius Marminge --- packages/shared/src/changedFileKind.test.ts | 5 +++++ packages/shared/src/changedFileKind.ts | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/changedFileKind.test.ts b/packages/shared/src/changedFileKind.test.ts index f16ad777d895c..f77db79426740 100644 --- a/packages/shared/src/changedFileKind.test.ts +++ b/packages/shared/src/changedFileKind.test.ts @@ -6,6 +6,11 @@ describe("classifyChangedFile", () => { it.each([ ["src/contest.py", "code"], ["test/fixtures/pr.json", "mocks"], + ["src/MockTransport.ts", "mocks"], + ["src/FakeClock.ts", "mocks"], + ["src/Foo.Mock.ts", "mocks"], + ["src/Mockup.ts", "code"], + ["src/Stubborn.ts", "code"], ["pnpm-lock.yaml", "generated"], ["convex/_generated/api.d.ts", "generated"], ["src/agent.eval.ts", "tests"], diff --git a/packages/shared/src/changedFileKind.ts b/packages/shared/src/changedFileKind.ts index 7da5ba5cb0c11..dca226bd06fc8 100644 --- a/packages/shared/src/changedFileKind.ts +++ b/packages/shared/src/changedFileKind.ts @@ -47,8 +47,9 @@ const GENERATED_NAME = /(\.generated\.|\.gen\.|\.g\.dart$|\.pb\.go$|_pb2(_grpc)?\.py$|\.pb\.(cc|h)$|\.min\.(js|css)$|\.(js|css)\.map$)/; const GENERATED_DIRS = new Set(["__generated__", "_generated", "generated"]); -const MOCK_NAME = - /(\.snap$|\.(mocks?|fixtures?|stubs?|fakes?)\.[^.]+$|^(mocks?|fixtures?|stubs?|fakes?)([-_.A-Z]|$))/; +const MOCK_NAME = /(\.snap$|\.(mocks?|fixtures?|stubs?|fakes?)\.[^.]+$)/i; +// Case-sensitive after the prefix: `MockClock.ts` is a mock, `Mockup.ts` is not. +const MOCK_PREFIX = /^([Mm]ocks?|[Ff]ixtures?|[Ss]tubs?|[Ff]akes?)([-_.A-Z]|$)/; const MOCK_DIRS = new Set([ "__fixtures__", "__mocks__", @@ -99,7 +100,7 @@ export function classifyChangedFile(path: string): ChangedFileKind { const inDir = (set: ReadonlySet) => dirs.some((dir) => set.has(dir)); if (GENERATED_FILES.has(name.toLowerCase()) || GENERATED_NAME.test(name) || inDir(GENERATED_DIRS)) return "generated"; - if (MOCK_NAME.test(name) || inDir(MOCK_DIRS)) return "mocks"; + if (MOCK_NAME.test(name) || MOCK_PREFIX.test(name) || inDir(MOCK_DIRS)) return "mocks"; if (TEST_NAME.test(name) || CLASS_TEST_NAME.test(name) || inDir(TEST_DIRS)) return "tests"; if (DOCS_NAME.test(name) && !NOT_DOCS_NAME.test(name)) return "docs"; return "code"; From 7f0e736cdba5987e2bc9a9e82e03cfde2d80b62a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 10:21:19 -0800 Subject: [PATCH 030/221] fix(server): GitHub issue URLs with no project on their host name the missing project (#41581) --- apps/server/src/issue/IssueService.test.ts | 21 +++++++++++++++++++++ apps/server/src/issue/IssueService.ts | 5 ++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 26d02c06bfe66..f658c26f6c63c 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -349,6 +349,27 @@ describe("IssueService", () => { }), ); + it.effect( + "does not call a GitHub issue URL unbrowsable when no project is a GitHub checkout", + () => + Effect.gen(function* () { + // A plain folder project, while GitHub itself is a supported tracker. + const service = yield* makeService({ + projects: [project({ id: "folder" })], + trackers: [fakeTracker()], + }); + const resolved = yield* service + .resolveUrl("https://github.com/acme/web/issues/1", "folder" as ProjectId) + .pipe(Effect.result); + if (resolved._tag === "Failure") { + expect(resolved.failure).not.toMatchObject({ + _tag: "IssueUnavailableError", + reason: "tracker-unsupported", + }); + } + }), + ); + it.effect("resolves both legacy Azure work item URLs through the bound project", () => Effect.gen(function* () { const tracker = IssueTrackerKind.make("azure-devops"); diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 01d8b47382eef..1a913c9b0725f 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -824,7 +824,10 @@ const make = Effect.gen(function* () { if (standalone === null) { const found = serve(onTracker); if (found === null) { - return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + return yield* new IssueOperationError({ + operation: "resolveUrl", + detail: `No project in T3 Code is on ${link.host}. Add any ${link.host} project to read its issues.`, + }); } return found.resolved; } From a369642c1c5c7a9a1e6b906167e3309005ad23e4 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 12:32:01 -0600 Subject: [PATCH 031/221] fix(web): keys pressed on a focused video stay with the player (#41578) Co-authored-by: Julius Marminge --- .../components/chat/composerFocusRedirect.ts | 1 + .../chat/useChatShortcuts.browser.test.tsx | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/apps/web/src/components/chat/composerFocusRedirect.ts b/apps/web/src/components/chat/composerFocusRedirect.ts index cb187e73ea6a7..2fc544a31c9b4 100644 --- a/apps/web/src/components/chat/composerFocusRedirect.ts +++ b/apps/web/src/components/chat/composerFocusRedirect.ts @@ -12,6 +12,7 @@ const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [ "button", "a[href]", "summary", + "video[controls]", '[role="application"]', '[role="button"]', '[role="checkbox"]', diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx index 61127d1a9d9c8..378bc2b5cce74 100644 --- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx +++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx @@ -245,3 +245,21 @@ it("runs right panel commands from inside a side chat pane, but not thread comma expect(ran).toEqual(["toggle", "close", "toggle"]); }); + +it("leaves keys to a focused video player with controls", async () => { + const composerKeys: string[] = []; + await using _screen = await render( + <> + +
or in one piece (#41596) Co-authored-by: Julius Marminge --- packages/shared/src/markdownChunks.test.ts | 42 +++++++++++++++++++++- packages/shared/src/markdownChunks.ts | 34 +++++++++++++++++- 2 files changed, 74 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts index a5cf2a8017b35..8b4801ad7594f 100644 --- a/packages/shared/src/markdownChunks.test.ts +++ b/packages/shared/src/markdownChunks.test.ts @@ -76,9 +76,49 @@ describe("splitMarkdown", () => { "# literal", "", "", + "
", + "Answer", + "", + "Inside details", + "", + "
", + "", + "
", + "", + "```ts", + "inside a cell", + "```", + "", + "
", + "", + '
    ', + "", + "
  1. one
  2. ", + "", + "
  3. two
  4. ", + "", + "
", + "", + "```html", + "
", + "```", + "", + "after", + ].join("\n"); + expect(starts(text)).toEqual(["', + "", + "Inside details", + "", + "
", + "", "after", ].join("\n"); - expect(starts(text)).toEqual(["", open + 4); + if (close === -1) break; + kept += line.slice(at, open); + at = close + 3; + } + return kept + line.slice(at); +} + +function openedWrappers(line: string): number { + let opened = 0; + for (const [, closing] of withoutComments(line).matchAll(WRAPPER_TAG)) { + opened += closing ? -1 : 1; + } + return opened; +} /** Returns how to recognize the end of a block that `line` opens, or null for none. */ function blockCloser(line: string): ((line: string) => boolean) | null { @@ -44,7 +71,7 @@ function blockCloser(line: string): ((line: string) => boolean) | null { return close.test(line.slice(opener.length)) ? null : (next) => close.test(next); } // Other HTML blocks (CommonMark types 6 and 7) run until a blank line. - return HTML_BLOCK_START.test(line) ? (next) => next.trim() === "" : null; + return HTML_BLOCK_START.test(line) ? closesAtBlankLine : null; } export interface MarkdownChunk { @@ -86,6 +113,7 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S let afterDefinition = false; let afterHeading = false; let definitionChars = 0; + let openWrappers = 0; const flush = () => { chunks.push({ text: lines.join("\n"), lines: lines.length }); lines = []; @@ -98,8 +126,10 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S let seen = 0; closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; } else { + if (chars >= WRAPPED_MAX_CHARS) openWrappers = 0; const cut = chars >= targetChars && + openWrappers === 0 && (ATX_HEADING.test(line) || (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); if (cut) flush(); @@ -114,6 +144,8 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S definitionChars += line.length + 1; } } + if (closes === closesAtBlankLine) + openWrappers = Math.max(0, openWrappers + openedWrappers(line)); first = false; lines.push(line); chars += line.length + 1; From 0fcfc17c81a88eb5f0d9bff76425c5872f0465f5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 11:39:06 -0800 Subject: [PATCH 040/221] fix(server): older history no longer reads every attempt row to find steered ones (#41620) --- apps/server/src/persistence/Migrations.ts | 2 ++ .../Migrations/111_SupersededRunAttemptIndex.ts | 14 ++++++++++++++ .../reconcileV2PreviewMigration.test.ts | 2 ++ 3 files changed, 18 insertions(+) create mode 100644 apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 36762e9059b58..5c24577ad53ec 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -118,6 +118,7 @@ import Migration0107 from "./Migrations/107_DeferredSlashCommandIndex.ts"; import Migration0108 from "./Migrations/108_AgentFeedback.ts"; import Migration0109 from "./Migrations/109_IssueTrackerAccounts.ts"; import Migration0110 from "./Migrations/110_Workflows.ts"; +import Migration0111 from "./Migrations/111_SupersededRunAttemptIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -231,6 +232,7 @@ const migrationEntries = [ [108, "AgentFeedback", Migration0108], [109, "IssueTrackerAccounts", Migration0109], [110, "Workflows", Migration0110], + [111, "SupersededRunAttemptIndex", Migration0111], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts b/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts new file mode 100644 index 0000000000000..ad2f9f4a3817e --- /dev/null +++ b/apps/server/src/persistence/Migrations/111_SupersededRunAttemptIndex.ts @@ -0,0 +1,14 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Opening a thread's history looks up its few superseded attempts. Without this index that + // reads every attempt row of the thread, which is slow on a long thread with a cold cache. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_run_attempts_superseded_idx + ON orchestration_v2_projection_run_attempts(thread_id, run_id, root_node_id) + WHERE status = 'superseded' + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 1b8cf040b5fbc..de0d6a3f63ff5 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -90,6 +90,7 @@ describe("V2 preview upgrade", () => { [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], [110, "Workflows"], + [111, "SupersededRunAttemptIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -223,6 +224,7 @@ describe("V2 preview upgrade", () => { [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], [110, "Workflows"], + [111, "SupersededRunAttemptIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From 4ab87289acdce039c9c68626f1fb74e8a3b59d50 Mon Sep 17 00:00:00 2001 From: James Cane Date: Mon, 23 Nov 2026 19:40:16 +0000 Subject: [PATCH 041/221] fix(server): recover dropped T3 MCP tool results in ACP and OpenCode Code Mode (#41552) Co-authored-by: Julius Marminge --- apps/server/src/mcp/McpHttpServer.ts | 74 +++- apps/server/src/mcp/toolkits/core.test.ts | 41 +++ .../Adapters/AntigravityAdapterV2.test.ts | 330 +++++++++++++++++- .../Adapters/OpenCode2AdapterV2.test.ts | 196 ++++++++++- .../provider/acp/AntigravityProtocol.test.ts | 34 ++ .../src/provider/acp/AntigravityProtocol.ts | 56 ++- packages/provider-acp/src/server/adapter.ts | 135 ++++++- .../src/server/McpProviderSessions.test.ts | 161 +++++++++ .../src/server/McpProviderSessions.ts | 153 +++++++- .../provider-opencode/src/server/toolItems.ts | 128 ++++++- .../src/server/v2/adapter.ts | 97 ++++- packages/shared/src/toolOutput.test.ts | 13 + packages/shared/src/toolOutput.ts | 20 ++ 13 files changed, 1398 insertions(+), 40 deletions(-) create mode 100644 packages/provider-core/src/server/McpProviderSessions.test.ts diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index be41f8630b7dd..2b1deed86f037 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -56,6 +56,9 @@ import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; import * as McpWebhookTransport from "./McpWebhookTransport.ts"; +import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; +import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; @@ -1218,6 +1221,67 @@ const withToolAnalytics = return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer)); }); +/** + * ACP runtimes and Code Mode wrappers can drop or replace structured MCP tool results on + * completion. Recording each thread-scoped call's compact result before returning lets adapters + * recover sent messages, IDs, counts, and error flags without depending on output passthrough. + */ +const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(function* ( + registration: Effect.Effect, +) { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions); + if (Option.isNone(mcpSessions)) { + return yield* registration; + } + const capturingServer = McpServer.McpServer.of({ + ...server, + addTool: Effect.fn("McpServer.addTool")(function (options) { + const toolName = options.tool.name; + // html_render tracks its own path/hash recovery with publish cleanup in HtmlRender. + if (toolName === HTML_RENDER_TOOL_NAME) { + return server.addTool(options); + } + return server.addTool({ + ...options, + // Untraced: withToolSpans already opens a span per tool call. + handle: Effect.fnUntraced(function* (payload) { + const scopeOption = yield* Effect.serviceOption( + McpInvocationContext.McpInvocationContext, + ); + const thread = Option.getOrUndefined(scopeOption)?.thread; + const epoch = + thread === undefined + ? undefined + : yield* mcpSessions.value.toolResultEpoch(thread.threadId); + return yield* options.handle(payload).pipe( + Effect.onExit((exit) => { + if (thread === undefined) return Effect.void; + if (exit._tag === "Success" && exit.value instanceof McpSchema.InputRequired) { + return Effect.void; + } + if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) { + return Effect.void; + } + const output = + exit._tag === "Success" + ? compactT3McpToolOutput(toolName, exit.value) + : { isError: true }; + return output === undefined + ? Effect.void + : mcpSessions.value.recordToolResult(thread.threadId, toolName, payload, output, { + providerSessionId: thread.providerSessionId, + epoch, + }); + }), + ); + }), + }); + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, capturingServer)); +}); + /** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */ const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* ( registration: Effect.Effect, @@ -1300,8 +1364,10 @@ export const toolkitRegistration = , EX, ) => Layer.effectDiscard( withToolAnalytics( - withToolSpans( - withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + withToolResultCapture( + withToolSpans( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ), ), ), ).pipe( @@ -1318,7 +1384,7 @@ const imageToolRegistration = , A, E, R, register: Effect.Effect, handlers: McpToolAccess.HandlersLayer, ) => - Layer.effectDiscard(withToolAnalytics(withToolSpans(register))).pipe( + Layer.effectDiscard(withToolAnalytics(withToolResultCapture(withToolSpans(register)))).pipe( Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), ); @@ -1350,7 +1416,7 @@ export const layerOrchestratorToolkit = toolkitRegistration( export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); -const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); +export const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); const layerWorktreeToolkitRegistration = toolkitRegistration( WorktreeToolkit, diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 33c356af4e7e1..c1d35ace86940 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -416,6 +416,47 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both ), ); +it.effect("captures send_to_user results for providers that drop MCP outputs", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const draft = "### Status\n\nAll checks passed."; + const result = yield* server + .callTool({ name: "send_to_user", arguments: { message: draft } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(result.isError).not.toBe(true); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toEqual( + { sentMessage: draft }, + ); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toBe( + undefined, + ); + + const invalid = yield* server + .callTool({ name: "send_to_user", arguments: { message: "" } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + Effect.flip, + ); + expect(invalid).toMatchObject({ _tag: "InvalidParams" }); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: "" })).toEqual({ + isError: true, + }); + }).pipe( + Effect.provide( + McpHttpServer.layerMessageToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + ), + ), + ), +); + it.effect("records only failed calls of tools that hand off no work", () => { // Recording runs detached from the tool response, so the first event is awaited. const recorded = Deferred.makeUnsafe<{ event: string; properties: object }>(); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5cbb4975e5e57..9924d6c831833 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -13,7 +13,12 @@ import { ThreadId, } from "@t3tools/contracts"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { + compactDynamicToolOutput, + htmlRenderFromToolItem, + previewRecordingIdFromToolItem, + sentMessageFromToolItem, +} from "@t3tools/shared/toolOutput"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -989,6 +994,329 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined); }).pipe(Effect.provide(layerSession)), ); + + it.effect( + "recovers T3 MCP tool results across omitted outputs, replays, errors, and turn boundaries", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let promptIndex = 0; + let turn1Epoch = 0; + const instanceId = ProviderInstanceId.make("antigravity-mcp-result-test"); + const threadId = ThreadId.make("thread-antigravity-mcp-result"); + const statusUpdate = "### Current Status\n\nAll checks are passing."; + const inProgressText = "Streamed while running."; + const lateText = "Confirmed on a later completion."; + const lateErrorText = "Late explicit error."; + const unfinishedText = "Still running when turn ended."; + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptIndex += 1; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update, + }), + ); + const startTool = ( + toolCallId: string, + toolName: string, + rawInput: Record, + ) => + send({ + sessionUpdate: "tool_call", + toolCallId, + title: `Run mcp_t3-code_${toolName}`, + kind: "other", + status: "in_progress", + rawInput, + }); + const updateTool = ( + toolCallId: string, + status: "in_progress" | "completed" | "failed", + rawOutput?: unknown, + ) => + send({ + sessionUpdate: "tool_call_update", + toolCallId, + status, + ...(rawOutput === undefined ? {} : { rawOutput }), + }); + const recordSend = (message: string) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ); + + if (promptIndex === 2) { + // A Turn 1 handler finishing after Turn 1 closed must be rejected by epoch. + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: unfinishedText }, + { sentMessage: unfinishedText }, + { epoch: turn1Epoch }, + ); + yield* startTool("turn2-leaked-check", "send_to_user", { + message: unfinishedText, + }); + yield* updateTool("turn2-leaked-check", "completed", "Summary of turn 2"); + return { stopReason: "end_turn" as const }; + } + + turn1Epoch = yield* mcpSessions.toolResultEpoch(threadId); + + // agy 1.5.x adds toolSummary and omits output on completion, then may replay. + yield* startTool("send-empty", "send_to_user", { + message: statusUpdate, + toolSummary: "Send status update", + }); + yield* recordSend(statusUpdate); + yield* updateTool("send-empty", "completed"); + yield* updateTool("send-empty", "in_progress"); + yield* updateTool("send-empty", "completed", "Summary replay"); + + // Streaming output during in_progress still drains on completion. + yield* startTool("send-streaming", "send_to_user", { message: inProgressText }); + yield* recordSend(inProgressText); + yield* updateTool("send-streaming", "in_progress", { + sentMessage: inProgressText, + }); + yield* updateTool("send-streaming", "completed", { + sentMessage: inProgressText, + }); + yield* startTool("send-streaming-unpublished", "send_to_user", { + message: inProgressText, + }); + yield* updateTool("send-streaming-unpublished", "completed"); + + // Explicit MCP error preserves diagnostic content across summary replays. + yield* startTool("send-errored", "send_to_user", { message: "Denied" }); + yield* updateTool("send-errored", "completed", { + result: { + isError: true, + structuredContent: { sentMessage: "Denied" }, + content: [{ type: "text", text: "Denied by policy" }], + }, + }); + yield* updateTool("send-errored", "completed", "Summary of denied"); + + // Initial miss -> late explicit success or error still drains its new record. + yield* startTool("send-late", "send_to_user", { message: lateText }); + yield* updateTool("send-late", "completed"); + yield* recordSend(lateText); + yield* updateTool("send-late", "completed", { sentMessage: lateText }); + yield* startTool("send-late-unpublished", "send_to_user", { + message: lateText, + }); + yield* updateTool("send-late-unpublished", "completed"); + + yield* startTool("send-late-error", "send_to_user", { message: lateErrorText }); + yield* updateTool("send-late-error", "completed"); + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: lateErrorText }, + { isError: true }, + ); + yield* updateTool("send-late-error", "completed", { + result: { isError: true, content: [{ type: "text", text: "Denied late" }] }, + }); + yield* startTool("send-late-error-sibling", "send_to_user", { + message: lateErrorText, + }); + yield* updateTool("send-late-error-sibling", "completed"); + + // Empty-input completion that misses still recovers once a later completion brings arguments, + // and replacing arguments on the same call ID re-matches against the new arguments. + yield* startTool("send-late-args", "send_to_user", {}); + yield* recordSend("First args"); + yield* updateTool("send-late-args", "completed"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "First args" }, + }); + yield* recordSend("Second args"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "Second args" }, + rawOutput: "Summary of second", + }); + + // Bare failure without reported output must not consume a sibling call's cached result. + yield* startTool("send-bare-fail", "send_to_user", { message: "Shared ready" }); + yield* startTool("send-bare-fail-sibling", "send_to_user", { + message: "Shared ready", + }); + yield* recordSend("Shared ready"); + yield* updateTool("send-bare-fail", "failed"); + yield* updateTool("send-bare-fail-sibling", "completed"); + + // preview_recording_stop recovers its recording id. + yield* startTool("recording-stop", "preview_recording_stop", { + toolSummary: "Stop preview recording", + }); + yield* mcpSessions.recordToolResult( + threadId, + "preview_recording_stop", + {}, + { id: `${threadId}-rec-1` }, + ); + yield* updateTool("recording-stop", "completed"); + + // Unfinished call projected at turn end must not claim or leak to Turn 2. + yield* startTool("send-unfinished", "send_to_user", { + message: unfinishedText, + }); + yield* recordSend(unfinishedText); + + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-mcp-result"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal, + modelSelection, + }), + ); + return Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + }); + const turn1Events = yield* runTurn(1); + const turn2Events = yield* runTurn(2); + const toolIn = (events: ReadonlyArray<(typeof turn1Events)[number]>, nativeId: string) => { + const event = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId, + ); + return event?.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? event.turnItem + : undefined; + }; + const tool = (nativeId: string) => toolIn(turn1Events, nativeId); + + const sendEmptyUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-empty" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.deepEqual( + sendEmptyUpdates.map((update) => sentMessageFromToolItem(update)), + [statusUpdate, statusUpdate], + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming")!), inProgressText); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming-unpublished")!), undefined); + const erroredUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-errored" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.strictEqual(erroredUpdates.length, 2); + for (const update of erroredUpdates) { + assert.strictEqual(compactDynamicToolOutput(update.output)?.isError, true); + assert.include(JSON.stringify(update.output), "Denied by policy"); + assert.strictEqual(sentMessageFromToolItem(update), undefined); + } + assert.strictEqual(sentMessageFromToolItem(tool("send-late")!), lateText); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-unpublished")!), undefined); + const lateErrorSibling = tool("send-late-error-sibling"); + assert.isDefined(lateErrorSibling); + assert.strictEqual(lateErrorSibling.status, "completed"); + assert.strictEqual(lateErrorSibling.output, undefined); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-args")!), "Second args"); + assert.strictEqual( + sentMessageFromToolItem(tool("send-bare-fail-sibling")!), + "Shared ready", + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-unfinished")!), undefined); + assert.strictEqual( + sentMessageFromToolItem(toolIn(turn2Events, "turn2-leaked-check")!), + undefined, + ); + assert.strictEqual( + previewRecordingIdFromToolItem(tool("recording-stop")!), + `${threadId}-rec-1`, + ); + }).pipe(Effect.provide(layerSession)), + ); }); /** diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 91a00fd60742f..33b2ecd4638c5 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -43,7 +43,7 @@ import { TestClock } from "effect/testing"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { htmlRenderFromToolItem, sentMessageFromToolItem } from "@t3tools/shared/toolOutput"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { @@ -1540,16 +1540,26 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("session.interrupt", { interrupted: true }), event("session.execution.interrupted", { sessionID: SESSION }), ]); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); const watch = yield* watchBackgroundTurn(runtime); yield* runtime.startTurn(withLineage(thread)); yield* watch.attached; + // The child's nested T3 MCP results live under the root thread and outlive its turn. + const childResult = { message: "Child note" }; + yield* mcpSessions.recordToolResult(threadId, "send_to_user", childResult, { + sentMessage: childResult.message, + }); yield* runtime.interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId, }); assert.equal((yield* watch.terminal)?.status, "interrupted"); assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - }), + assert.deepEqual(yield* mcpSessions.takeToolResult(threadId, "send_to_user", childResult), { + sentMessage: childResult.message, + }); + }).pipe(Effect.scoped), ); it.effect("stops background subagents on a user Stop", () => @@ -5321,6 +5331,188 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("shows send_to_user messages a Code Mode script sends without returning them", () => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); + const server = "t3-code-thread_opencode2-adapter"; + const messages = ["First mid-turn note", "Second mid-turn note"]; + yield* Effect.forEach(messages, (message) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ), + ); + const tool = { + sessionID: SESSION, + assistantMessageID: "msg_assistant", + id: "call-execute-send", + }; + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.tool.input.started", { ...tool, name: "execute" }), + event("session.tool.called", { ...tool, input: { code: "`; } diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 0f3f8519bddc7..e70be7cb9f1fc 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -755,7 +755,7 @@ describe("AssetAccess", () => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "t3-link-" })); - yield* fs.writeFileString(path.join(root, "payload.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); yield* fs.writeFileString(path.join(root, "real.pdf"), "%PDF-1.4"); const link = path.join(root, "report.pdf"); const issue = issueAssetUrl({ @@ -772,7 +772,7 @@ describe("AssetAccess", () => { return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); }; - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); yield* fs.remove(link); @@ -783,7 +783,7 @@ describe("AssetAccess", () => { }); yield* fs.remove(link); - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect(yield* resolveIssued(issued.relativeUrl)).toBeNull(); }).pipe(Effect.provide(layerTest)), ); @@ -1807,6 +1807,51 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.skipIf(!symlinksSupported)("refuses a favicon link whose target is not an image", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-" }), + ); + const pictures = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-pictures-" }), + ); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "real.svg"), ""); + const resolveIssued = (relativeUrl: string) => { + const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); + }; + for (const link of [path.join(root, "favicon.svg"), path.join(pictures, "custom.svg")]) { + const issue = issueAssetUrl({ + resource: { _tag: "project-favicon", cwd: root }, + ...(link.startsWith(pictures) ? { projectFaviconPath: link } : {}), + }); + + yield* fs.symlink(path.join(root, "page.xhtml"), link); + expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "real.svg"), link); + const issued = yield* issue; + expect(yield* resolveIssued(issued.relativeUrl)).toEqual({ + kind: "file", + path: path.join(root, "real.svg"), + }); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); + // An outside icon's URL names its target, so repointing the link cannot change it. + expect(yield* resolveIssued(issued.relativeUrl)).toEqual( + link.startsWith(pictures) ? { kind: "file", path: path.join(root, "real.svg") } : null, + ); + yield* fs.remove(link); + } + }).pipe(Effect.provide(layerTest)), + ); + it.effect("ignores a client favicon path hint", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 2b8f1029ae3a3..d91975114e6eb 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -287,6 +287,8 @@ const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(functio const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* ( filePath: string, ) { + // Checked again here: a link can be repointed after its URL was issued. + if (!isProjectFaviconPath(filePath)) return null; if (!filePath.toLowerCase().endsWith(".icns")) { return { kind: "file", path: filePath } satisfies ResolvedAsset; } @@ -824,6 +826,10 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i resource: input.resource, }); } + // A favicon link must resolve to an image file. + if (canonicalFaviconPath && !isProjectFaviconPath(canonicalFaviconPath)) { + return yield* new AssetPreviewTypeValidationError({ resource: input.resource }); + } claims = isExternalOverride && canonicalFaviconPath ? { diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.ts index d7fee1a2271df..f78c4acf28d3d 100644 --- a/apps/server/src/device/DeviceHubProxy.test.ts +++ b/apps/server/src/device/DeviceHubProxy.test.ts @@ -44,7 +44,14 @@ const fixture = ( if (fail) return yield* Effect.die(new Error("upstream failed")); return HttpClientResponse.fromWeb( request, - new Response(stream ?? "frame", { headers: { "set-cookie": "upstream=1" } }), + new Response(stream ?? "frame", { + headers: { + "set-cookie": "upstream=1", + "clear-site-data": '"*"', + "content-type": "text/html", + "content-security-policy": "script-src *", + }, + }), ); }), ); @@ -122,6 +129,11 @@ describe("device hub proxy", () => { ); expect(response.status).toBe(200); expect(await response.text()).toBe("frame"); + expect(response.headers.get("set-cookie")).toBeNull(); + expect(response.headers.get("clear-site-data")).toBeNull(); + // Opened as a page, a hub response gets an opaque origin and no script. + expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; sandbox"); + expect(response.headers.get("x-content-type-options")).toBe("nosniff"); expect(requests).toEqual(["http://hub.test/api/devices"]); expect(finalized()).toBe(1); }); diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.ts index 9778cf084b017..b7194d1feeeb7 100644 --- a/apps/server/src/device/DeviceHubProxy.ts +++ b/apps/server/src/device/DeviceHubProxy.ts @@ -164,11 +164,13 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( const headers: Record = {}; for (const [name, value] of Object.entries(response.headers)) { // A cookie from an upstream such as an Expo Simulators session's preview host would land on T3's origin. + // Clear-Site-Data likewise applies to the origin that serves it. if ( name === "content-encoding" || name === "transfer-encoding" || name === "connection" || - name === "set-cookie" + name === "set-cookie" || + name === "clear-site-data" ) { continue; } @@ -176,6 +178,9 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( } // Long-lived MJPEG and AVCC responses must not be buffered by compression. headers["cache-control"] = "no-store, no-transform"; + // Hub responses are data and streams; none renders as a page on this origin. + headers["x-content-type-options"] = "nosniff"; + headers["content-security-policy"] = "default-src 'none'; sandbox"; const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace") ? repeatStillFrame(response.stream) : response.stream; diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index 6e011aef39d26..2f2f6b8f85534 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -20,6 +20,7 @@ import { openMediaFile } from "./assets/MediaFile.ts"; import { injectMcpAppCsp, injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, injectMcpAppThemeBootstrap, MCP_APP_MAX_HTML_BYTES, } from "@t3tools/shared/mcpApp"; @@ -54,7 +55,9 @@ describe("MCP app asset responses", () => { method, ), ); - const expected = injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)); + const expected = injectMcpAppDocumentBootstrap( + injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)), + ); expect(response.status).toBe(200); expect(response.headers.get("content-length")).toBe( String(new TextEncoder().encode(expected).byteLength), @@ -842,7 +845,7 @@ describe("video asset byte ranges", () => { }); describe("assetResponseHeaders", () => { - it("sandboxes SVG assets", () => { + it("sandboxes SVG and other XML assets", () => { expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "X-Content-Type-Options": "nosniff", @@ -850,6 +853,15 @@ describe("assetResponseHeaders", () => { expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty( "Content-Security-Policy", ); + for (const name of ["page.xhtml", "page.XHT", "feed.xml", "sheet.xsl", "feed.rss"]) { + expect(assetResponseHeaders(`/workspace/${name}`)).toHaveProperty( + "Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; sandbox", + ); + } + expect(assetResponseHeaders("/workspace/photo.png")).not.toHaveProperty( + "Content-Security-Policy", + ); }); it("serves inline attachment documents with their declared mime type", () => { expect( diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index acec877a45c55..8a31a99287e38 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -5,7 +5,11 @@ import { EnvironmentHttpApi, } from "@t3tools/contracts"; import { isDevProxiedPath } from "@t3tools/shared/devProxy"; -import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; +import { + injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, + injectMcpAppThemeBootstrap, +} from "@t3tools/shared/mcpApp"; import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender"; import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; import * as ByteSize from "effect/ByteSize"; @@ -77,6 +81,13 @@ const isSafeInlineMediaMimeType = (mimeType: string): boolean => const isSafeInlineDocumentMimeType = (mimeType: string): boolean => mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html"; +// XML types render as documents, so they get the same policy as SVG. +const isScriptableXmlPath = (filePath: string): boolean => + Option.match(Mime.getType(filePath), { + onNone: () => false, + onSome: (mimeType) => /(?:\/xml(?:$|-)|\+xml$)/.test(mimeType), + }); + export function downloadContentDisposition(fileName?: string): string { if (fileName === undefined) { return "attachment"; @@ -134,7 +145,7 @@ export function assetResponseHeaders( "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY, } : {}), - ...(!options?.download && lowerPath.endsWith(".svg") + ...(!options?.download && isScriptableXmlPath(lowerPath) ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY } : {}), }; @@ -189,6 +200,8 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( new TextDecoder().decode(bytes), injectMcpAppThemeBootstrap, injectMcpAppCookieBootstrap, + // Applied last so it is the document's first script. + injectMcpAppDocumentBootstrap, (html) => new TextEncoder().encode(html), ); headers["Content-Length"] = String(body.byteLength); diff --git a/apps/web/src/components/chat/McpAppFrame.browser.test.tsx b/apps/web/src/components/chat/McpAppFrame.browser.test.tsx index ed6c4b9261393..2ea2330f50af7 100644 --- a/apps/web/src/components/chat/McpAppFrame.browser.test.tsx +++ b/apps/web/src/components/chat/McpAppFrame.browser.test.tsx @@ -2,6 +2,8 @@ import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; +import { injectMcpAppDocumentBootstrap } from "@t3tools/shared/mcpApp"; + import "~/index.css"; import { act, fakeTimers, render } from "../../../test/render"; @@ -22,10 +24,29 @@ addEventListener("message", (event) => { parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/initialized" }, "*"); `; +const sizeChanged = (height: number) => + `parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/size-changed", params: { height: ${height} } }, "*");`; +// What the app's frame shows after the app follows a link: another page in the same window. +// Its nested frame keeps `load`, which stops the app, from firing before its message arrives. +const REPLACEMENT_URL = `data:text/html,${encodeURIComponent(``)}`; +// Served as the server serves an app: the document bootstrap is its first script. +const NAVIGATING_APP_HTML = injectMcpAppDocumentBootstrap(``); + +const asset = vi.hoisted(() => ({ html: "" })); +const setup = (html: string) => { + asset.html = html; +}; + vi.mock(import("~/assets/longLivedAssetUrls"), () => ({ useLongLivedAssetUrl: () => ({ _tag: "Success", - url: `data:text/html,${encodeURIComponent(APP_HTML)}`, + url: `data:text/html,${encodeURIComponent(asset.html)}`, expiresAt: Date.now() + 60 * 60_000, }), })); @@ -44,6 +65,7 @@ const nextInitializedFrom = () => describe("McpAppFrame", () => { it("keeps a reopened app when the old document's second teardown finishes late", async () => { + setup(APP_HTML); const firstInitialized = nextInitializedFrom(); await using screen = await render( { expect(screen.getByRole("button", { name: "Show app" }).query()).toBeNull(); await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument(); }); + + it("ignores a page the app's frame navigated to", async () => { + setup(NAVIGATING_APP_HTML); + const element = () => ( + + ); + await using screen = await render(element()); + const frame = screen.getByTitle("Demo app").element() as HTMLIFrameElement; + const row = frame.parentElement!.parentElement!; + // The app resizes only after the host's answer reached it, so the bridge works both ways. + await expect.element(row).toHaveStyle({ height: "321px" }); + + // A tool update hands the row an equal app in a new object, which re-attaches the host. + await screen.rerender(element()); + frame.contentWindow!.postMessage("leave", "*"); + await expect + .element(screen.getByText("The Demo app left its page and was stopped")) + .toBeInTheDocument(); + expect(row.style.height).toBe("321px"); + }); }); diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsx index c0893c2d6f7c3..3d90a688f717c 100644 --- a/apps/web/src/components/chat/McpAppFrame.tsx +++ b/apps/web/src/components/chat/McpAppFrame.tsx @@ -38,6 +38,7 @@ import { useTurnItemDetail } from "~/state/queries"; import { mcpAppEnvironment } from "~/state/mcpApps"; import { useAtomCommand } from "~/state/use-atom-command"; import { observeResize } from "~/lib/observeResize"; +import { attachMcpAppDocumentLink } from "./mcpAppDocumentLink"; import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay"; const commandFailure = (result: { @@ -269,16 +270,15 @@ export function McpAppFrame(props: { } return approved; }; - const target = () => frameRef.current?.contentWindow ?? null; const scope = () => { const { environmentId, threadId, itemId } = readLive().props; return { environmentId, input: { threadId, itemId } }; }; + const documentLink = attachMcpAppDocumentLink(frame, (data) => host.receive(data)); const host = makeMcpAppHost({ app, hostVersion: APP_VERSION, - // Opaque origins require "*"; the window reference scopes delivery to this frame. - post: (message) => target()?.postMessage(message, "*"), + post: documentLink.post, hostContext, callTool: async ({ name, arguments: args }) => { const { environmentId, input } = scope(); @@ -401,12 +401,9 @@ export function McpAppFrame(props: { }, }); hostRef.current = host; - const receive = (event: MessageEvent) => { - if (event.source !== null && event.source === target()) host.receive(event.data); - }; - window.addEventListener("message", receive); + window.addEventListener("message", documentLink.receive); return () => { - window.removeEventListener("message", receive); + window.removeEventListener("message", documentLink.receive); void host.teardown(); hostRef.current = null; frameRef.current = null; diff --git a/apps/web/src/components/chat/mcpAppDocumentLink.ts b/apps/web/src/components/chat/mcpAppDocumentLink.ts new file mode 100644 index 0000000000000..6982dd3e12a80 --- /dev/null +++ b/apps/web/src/components/chat/mcpAppDocumentLink.ts @@ -0,0 +1,67 @@ +import { MCP_APP_DOCUMENT_MESSAGE } from "@t3tools/shared/mcpApp"; + +const MAX_UNCONFIRMED_MESSAGES = 256; + +interface DocumentLink { + link: MessagePort | "window" | null; + nextProbe: number; + deliver: (data: unknown) => void; + readonly unconfirmed: Map; +} + +// Kept per frame, not per host: a host that re-attaches to the same frame must not take the +// frame's next message for a first one. +const documentLinks = new WeakMap(); + +/** + * Ties the bridge to the frame's first document. A frame's window outlives its document, so the + * bridge follows the port that document's bootstrap sends first, not the window. Servers without + * the bootstrap keep the plain window bridge. + */ +export function attachMcpAppDocumentLink( + frame: HTMLIFrameElement, + deliver: (data: unknown) => void, +) { + let state = documentLinks.get(frame); + if (state === undefined) { + state = { link: null, nextProbe: 0, deliver, unconfirmed: new Map() }; + documentLinks.set(frame, state); + } + const current = state; + current.deliver = deliver; + return { + receive: (event: MessageEvent) => { + if (event.source === null || event.source !== frame.contentWindow) return; + if (current.link === null) { + const port = event.data?.t3 === MCP_APP_DOCUMENT_MESSAGE ? (event.ports[0] ?? null) : null; + if (port !== null) { + current.link = port; + port.onmessage = (reply: MessageEvent) => { + const probe: unknown = reply.data?.alive; + if (typeof probe !== "number" || !current.unconfirmed.has(probe)) return; + const data = current.unconfirmed.get(probe); + current.unconfirmed.delete(probe); + current.deliver(data); + }; + return; + } + current.link = "window"; + } + if (current.link === "window") { + current.deliver(event.data); + return; + } + // Only the first document can answer, so a reply proves it sent this message. + if (current.unconfirmed.size >= MAX_UNCONFIRMED_MESSAGES) return; + current.unconfirmed.set(current.nextProbe, event.data); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- A MessagePort takes no target origin. + current.link.postMessage({ alive: current.nextProbe }); + current.nextProbe += 1; + }, + post: (message: unknown) => { + // Opaque origins require "*"; the window reference scopes delivery to this frame. + if (current.link === "window") frame.contentWindow?.postMessage(message, "*"); + else current.link?.postMessage({ message, origin: window.location.origin }); + }, + }; +} diff --git a/apps/web/src/components/files/BinaryViewer.tsx b/apps/web/src/components/files/BinaryViewer.tsx index 63a2f119056c1..c0f057a0d508a 100644 --- a/apps/web/src/components/files/BinaryViewer.tsx +++ b/apps/web/src/components/files/BinaryViewer.tsx @@ -1,9 +1,5 @@ /* oxlint-disable react/no-array-index-key -- Read-only cells retain their database row and column positions. */ -import { - decodeFilePreviewText, - filePreviewKind, - hostPreviewMimeTypeFromExtension, -} from "@t3tools/shared/filePreview"; +import { decodeFilePreviewText, filePreviewKind } from "@t3tools/shared/filePreview"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { ChevronLeftIcon, ChevronRightIcon, FileIcon, FolderIcon } from "lucide-react"; import { msg, T, useGT, useMessages } from "gt-react"; @@ -29,6 +25,7 @@ import { type BinaryWorkerRequest, type BinaryWorkerResult, } from "./binaryPreviewProtocol"; +import { archiveImageUrl } from "./archiveImageUrl"; import { PreviewImage } from "./PreviewImage"; import { readBinaryPreview } from "./readBinaryPreview"; import { previewErrorText, previewFailureText } from "./previewFailureMessages"; @@ -69,15 +66,10 @@ function ArchiveFile(props: { readonly path: string; readonly bytes: Uint8Array< // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Create an object URL for the extracted image and revoke it when the entry changes or unmounts. useEffect(() => { if (kind !== "image") return; - const extension = props.path.slice(props.path.lastIndexOf(".")); - const objectUrl = URL.createObjectURL( - new Blob([props.bytes], { - type: hostPreviewMimeTypeFromExtension(extension) ?? "application/octet-stream", - }), - ); + const image = archiveImageUrl(props.path, props.bytes); // oxlint-disable-next-line react/set-state-in-effect -- Publish a Blob URL only after registering its cleanup. - setUrl(objectUrl); - return () => URL.revokeObjectURL(objectUrl); + setUrl(image.url); + return image.revoke; }, [props.bytes, props.path, kind]); if (kind === "image") return url ? : ; diff --git a/apps/web/src/components/files/archiveImageUrl.test.ts b/apps/web/src/components/files/archiveImageUrl.test.ts new file mode 100644 index 0000000000000..90eb11f347831 --- /dev/null +++ b/apps/web/src/components/files/archiveImageUrl.test.ts @@ -0,0 +1,15 @@ +import { expect, it } from "vite-plus/test"; + +import { archiveImageUrl } from "./archiveImageUrl"; + +it("shows an archived SVG from a data URL", () => { + const svg = new TextEncoder().encode(''); + for (const path of ["art/logo.svg", "LOGO.SVG"]) { + expect(archiveImageUrl(path, svg).url).toBe( + `data:image/svg+xml;base64,${btoa(String.fromCharCode(...svg))}`, + ); + } + const png = archiveImageUrl("art/logo.png", new Uint8Array([137, 80, 78, 71])); + expect(png.url).toMatch(/^blob:/); + png.revoke(); +}); diff --git a/apps/web/src/components/files/archiveImageUrl.ts b/apps/web/src/components/files/archiveImageUrl.ts new file mode 100644 index 0000000000000..bdba586d48f11 --- /dev/null +++ b/apps/web/src/components/files/archiveImageUrl.ts @@ -0,0 +1,20 @@ +import { hostPreviewMimeTypeFromExtension } from "@t3tools/shared/filePreview"; +import * as Base64 from "effect/encoding/Base64"; + +/** + * A URL an `` can show for an image taken out of an archive. SVG uses a data: URL, which + * has an opaque origin wherever it is opened; other types use a blob: URL. + */ +export function archiveImageUrl( + path: string, + bytes: Uint8Array, +): { readonly url: string; readonly revoke: () => void } { + const mimeType = + hostPreviewMimeTypeFromExtension(path.slice(path.lastIndexOf("."))) ?? + "application/octet-stream"; + if (mimeType === "image/svg+xml") { + return { url: `data:${mimeType};base64,${Base64.encode(bytes)}`, revoke: () => undefined }; + } + const url = URL.createObjectURL(new Blob([bytes], { type: mimeType })); + return { url, revoke: () => URL.revokeObjectURL(url) }; +} diff --git a/packages/shared/src/mcpApp.ts b/packages/shared/src/mcpApp.ts index 7c3afd221365d..4f25f4ba83317 100644 --- a/packages/shared/src/mcpApp.ts +++ b/packages/shared/src/mcpApp.ts @@ -251,6 +251,23 @@ export function injectMcpAppCookieBootstrap(html: string): string { return `${prefix}${bootstrap}${html.slice(prefix.length)}`; } +export const MCP_APP_DOCUMENT_MESSAGE = "t3-mcp-app-document"; + +/** + * Binds the host bridge to this document rather than to the frame's window, which outlives it. + * The document's first script hands the host a private port: the host answers only over it, and + * acts on a message only once this document confirms it is alive. + */ +export function injectMcpAppDocumentBootstrap(html: string): string { + const bootstrap = ``; + // Preserve captured CSP ahead of executable code, including this bootstrap. + const prefix = + /^(?:\uFEFF?\s*]*>\s*)?(?:)?/i.exec( + html, + )![0]; + return `${prefix}${bootstrap}${html.slice(prefix.length)}`; +} + export function mcpAppAllowAttribute(permissions: McpAppPermissions | undefined): string { const features: Array = []; if (permissions?.camera) features.push("camera"); From ae3352e0512bbd2aa609f7176e1e547f670265f4 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 17:40:58 -0600 Subject: [PATCH 085/221] fix(server): checkpoints work when a Git path ends in a space (#41725) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriver.test.ts | 45 ++++++++++++++++++++++++ apps/server/src/vcs/GitVcsDriver.ts | 8 ++--- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 78a436a1424e4..d2eed8bad23a7 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -2098,6 +2098,51 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "checkpoint capture keeps whitespace at the end of Git paths", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-edge-space-capture-", + }); + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const git = (cwd: string, args: ReadonlyArray) => + driver.execute({ + operation: "test", + cwd, + args: ["-c", "user.name=Test", "-c", "user.email=test@test.com", ...args], + }); + const library = path.join(parent, "library"); + yield* fileSystem.makeDirectory(library); + yield* git(library, ["init"]); + yield* git(library, ["commit", "--allow-empty", "-m", "initial"]); + const checkpointRef = CheckpointRef.make("refs/t3/checkpoints/edge-space"); + // The newline name takes the per-path fallback; the other takes the one-spawn answer. + for (const name of ["repo ", "multi\nline "]) { + const cwd = path.join(parent, name); + yield* fileSystem.makeDirectory(cwd); + yield* git(cwd, ["init", `--separate-git-dir=${path.join(parent, `${name.trim()} git `)}`]); + yield* git(cwd, ["-c", "protocol.file.allow=always", "submodule", "add", library, "lib"]); + yield* git(cwd, ["commit", "-m", "initial"]); + yield* fileSystem.writeFileString(path.join(cwd, "dirty.txt"), "pending\n"); + yield* fileSystem.writeFileString(path.join(cwd, "lib", "dirty.txt"), "nested\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + assert.strictEqual( + (yield* git(cwd, ["show", `${checkpointRef}:dirty.txt`])).stdout, + "pending\n", + ); + assert.strictEqual( + (yield* git(path.join(cwd, "lib"), ["show", `${checkpointRef}:dirty.txt`])).stdout, + "nested\n", + ); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("restores empty checkpoints without changing paths outside the workspace", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 56b4b44d0156e..bba371104af14 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -992,7 +992,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( cwd, args: ["rev-parse", "--git-common-dir"], }); - const gitCommonDir = result.stdout.trim(); + const gitCommonDir = result.stdout.replace(/\n$/, ""); if (path.isAbsolute(gitCommonDir)) return gitCommonDir; const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); return path.resolve(physicalCwd, gitCommonDir); @@ -1025,9 +1025,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const [gitCommonDir = "", indexPath = "", topLevel = "", prefix = "", head = ""] = lines; if (headChecked && lines.length === (headExists ? 6 : 5) && lines.at(-1) === "") { return { - gitCommonDir: gitCommonDir.trim(), - indexPath: indexPath.trim(), - topLevel: topLevel.trim(), + gitCommonDir, + indexPath, + topLevel, prefix, headExists, head: headExists ? head : undefined, From b654fc27baac7bb831c3d21820c263e8667687a7 Mon Sep 17 00:00:00 2001 From: daTuzzo <123642701+daTuzzo@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:41:11 +0200 Subject: [PATCH 086/221] fix(server): automatic port selection checks the address the server binds (#41730) Co-authored-by: Julius Marminge --- apps/server/src/cli/automaticPort.test.ts | 6 +++-- apps/server/src/cli/automaticPort.ts | 10 ++++--- apps/server/src/cli/config.test.ts | 17 ++++++++---- apps/server/src/cli/config.ts | 33 ++++++++++++----------- packages/shared/src/Net.test.ts | 23 ++++++++++++++++ packages/shared/src/Net.ts | 23 +++++++++++++--- packages/shared/src/hostClassification.ts | 4 +++ 7 files changed, 86 insertions(+), 30 deletions(-) diff --git a/apps/server/src/cli/automaticPort.test.ts b/apps/server/src/cli/automaticPort.test.ts index 1f7805569744f..b39c94720cbc8 100644 --- a/apps/server/src/cli/automaticPort.test.ts +++ b/apps/server/src/cli/automaticPort.test.ts @@ -34,6 +34,7 @@ interface Scenario { readonly tcpv6ExitCode?: number; readonly wslpathMissing?: boolean; readonly reservedPorts?: ReadonlyArray; + readonly host?: string; } const select = (scenario: Scenario) => { @@ -92,7 +93,7 @@ const select = (scenario: Scenario) => { ); return Effect.gen(function* () { const selectAutomaticPort = yield* AutomaticPort.make; - const port = yield* selectAutomaticPort(3773); + const port = yield* selectAutomaticPort(3773, scenario.host); return { port, commands }; }).pipe(Effect.provide(layer)); }; @@ -149,12 +150,13 @@ describe("automatic port selection", () => { }), ); - it.effect("never queries Windows outside WSL", () => + it.effect("never queries Windows outside WSL or for a specific bind address", () => Effect.gen(function* () { for (const scenario of [ { kernelRelease: "6.8.0-45-generic\n" }, // macOS and Windows have no kernel release file. {}, + { kernelRelease: WSL_KERNEL, windowsPorts: [3773], host: "100.64.0.7" }, ] satisfies ReadonlyArray) { const result = yield* select(scenario); expect(result.port).toBe(3773); diff --git a/apps/server/src/cli/automaticPort.ts b/apps/server/src/cli/automaticPort.ts index 354de65d2519b..70e8bad6c8b05 100644 --- a/apps/server/src/cli/automaticPort.ts +++ b/apps/server/src/cli/automaticPort.ts @@ -1,3 +1,4 @@ +import { listensOnLoopback } from "@t3tools/shared/hostClassification"; import * as NetService from "@t3tools/shared/Net"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -44,14 +45,17 @@ export const make = Effect.gen(function* () { return new Set(listeners.map((listener) => listener.port)); }).pipe(Effect.orElseSucceed(() => null)); - return Effect.fn("automaticPort.select")(function* (preferred: number) { - if (!(yield* isWsl)) return yield* net.findAvailablePort(preferred); + return Effect.fn("automaticPort.select")(function* (preferred: number, host: string | undefined) { + // Windows localhost forwarding reaches only WSL listeners on loopback or a wildcard address. + if (!listensOnLoopback(host) || !(yield* isWsl)) { + return yield* net.findAvailablePort(preferred, host); + } const windows = yield* readWindowsHostListeners; if (windows === null) { yield* Effect.logWarning( "Could not list Windows TCP listeners from WSL; Windows may be unable to reach the selected port. Pass --port to choose one.", ); - return yield* net.findAvailablePort(preferred); + return yield* net.findAvailablePort(preferred, host); } if (!windows.has(preferred) && (yield* net.isPortAvailableOnLoopback(preferred))) { return preferred; diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 9d1ffb5c1298a..bbd13c1132953 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -872,15 +872,16 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { const baseDir = yield* FileSystem.FileSystem.pipe( Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-auto-port-" })), ); - const selected: number[] = []; - const selectAutomaticPort = (preferred: number) => + const selected: Array = []; + const selectAutomaticPort = (preferred: number, host: string | undefined) => Effect.sync(() => { - selected.push(preferred); + selected.push([preferred, host]); return 50_123; }); const resolvePort = (flags: { readonly mode?: Option.Option<"web" | "desktop">; readonly port: Option.Option; + readonly host?: Option.Option; }) => resolveServerConfig({ ...minimalWebFlags(baseDir), ...flags }, Option.none(), { selectAutomaticPort, @@ -895,12 +896,18 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { ); expect(yield* resolvePort({ port: Option.none() })).toBe(50_123); - expect(selected).toEqual([3773]); + expect(yield* resolvePort({ port: Option.none(), host: Option.some("100.64.0.7") })).toBe( + 50_123, + ); + expect(selected).toEqual([ + [3773, undefined], + [3773, "100.64.0.7"], + ]); expect(yield* resolvePort({ port: Option.some(8788) })).toBe(8788); expect( yield* resolvePort({ mode: Option.some("desktop" as const), port: Option.none() }), ).toBe(3773); - expect(selected).toEqual([3773]); + expect(selected).toHaveLength(2); }), ); diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index a62682772bcce..87ff2588c5e34 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -271,6 +271,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct readonly rejectRunningServer?: boolean; readonly selectAutomaticPort?: ( preferred: number, + host: string | undefined, ) => Effect.Effect; }, ) { @@ -310,22 +311,6 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct () => "web", ); - const port = yield* Option.match( - resolveOptionPrecedence( - normalizedFlags.port, - Option.fromUndefinedOr(env.port), - Option.fromUndefinedOr(bootstrap?.port), - ), - { - onSome: (value) => Effect.succeed(value), - onNone: () => { - if (mode === "desktop") { - return Effect.succeed(ServerConfig.DEFAULT_PORT); - } - return selectAutomaticPort(ServerConfig.DEFAULT_PORT); - }, - }, - ); const devUrl = Option.getOrElse( resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)), () => undefined, @@ -451,6 +436,22 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct const host = Option.getOrElse(explicitHost, () => privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined, ); + const port = yield* Option.match( + resolveOptionPrecedence( + normalizedFlags.port, + Option.fromUndefinedOr(env.port), + Option.fromUndefinedOr(bootstrap?.port), + ), + { + onSome: (value) => Effect.succeed(value), + onNone: () => { + if (mode === "desktop") { + return Effect.succeed(ServerConfig.DEFAULT_PORT); + } + return selectAutomaticPort(ServerConfig.DEFAULT_PORT, host); + }, + }, + ); const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel); const otel = yield* OtelEnvironment.load; diff --git a/packages/shared/src/Net.test.ts b/packages/shared/src/Net.test.ts index d4b00f5f957da..ca86a5db4a46f 100644 --- a/packages/shared/src/Net.test.ts +++ b/packages/shared/src/Net.test.ts @@ -1,4 +1,5 @@ import * as NodeNet from "node:net"; +import * as NodeOS from "node:os"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -44,6 +45,10 @@ const openServer = (host?: string): Effect.Effect entries ?? []) + .find((entry) => entry.family === "IPv4" && !entry.internal)?.address; + it.layer(NetService.layer)("NetService", (it) => { describe("Net helpers", () => { it.effect.each(["EAFNOSUPPORT", "EADDRNOTAVAIL"])( @@ -99,9 +104,27 @@ it.layer(NetService.layer)("NetService", (it) => { const resolved = yield* net.findAvailablePort(preferred); assert.ok(resolved > 0); assert.notEqual(resolved, preferred); + assert.notEqual(yield* net.findAvailablePort(preferred, ownIpv4), preferred); }), closeServer, ), ); + + it.effect.skipIf(ownIpv4 === undefined)( + "findAvailablePort keeps a port that only loopback uses for a specific bind address", + () => + Effect.acquireUseRelease( + openServer("127.0.0.1"), + (server) => + Effect.gen(function* () { + const net = yield* NetService.NetService; + const preferred = getPort(server); + + assert.equal(yield* net.findAvailablePort(preferred, ownIpv4), preferred); + assert.notEqual(yield* net.findAvailablePort(preferred, "0.0.0.0"), preferred); + }), + closeServer, + ), + ); }); }); diff --git a/packages/shared/src/Net.ts b/packages/shared/src/Net.ts index 40ef669db4e64..5a8f3214f177c 100644 --- a/packages/shared/src/Net.ts +++ b/packages/shared/src/Net.ts @@ -6,6 +6,8 @@ import * as Context from "effect/Context"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import { listensOnLoopback } from "./hostClassification.ts"; + export class NetError extends Schema.TaggedError()("NetError", { message: Schema.String, cause: Schema.optional(Schema.Defect()), @@ -35,7 +37,7 @@ export interface NetServiceShape { readonly reserveLoopbackPort: (host?: string) => Effect.Effect; - readonly findAvailablePort: (preferred: number) => Effect.Effect; + readonly findAvailablePort: (preferred: number, host?: string) => Effect.Effect; } export class NetService extends Context.Service()( @@ -130,6 +132,19 @@ export const make = () => { ); }); + const isPortAvailableForHost = Effect.fn("Net.isPortAvailableForHost")(function* ( + port: number, + host: string | undefined, + ): Effect.fn.Return { + if (host === undefined || listensOnLoopback(host)) { + return yield* isPortAvailableOnLoopback(port); + } + if (yield* hasListenerOnHost(port, host)) { + return false; + } + return yield* canListenOnHost(port, host); + }); + const reserveLoopbackPort = (host = "127.0.0.1"): Effect.Effect => Effect.callback((resume) => { const probe = NodeNet.createServer(); @@ -167,11 +182,11 @@ export const make = () => { isPortAvailableOnLoopback, hasListenerOnHost, reserveLoopbackPort, - findAvailablePort: Effect.fn("Net.findAvailablePort")(function* (preferred) { - if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) { + findAvailablePort: Effect.fn("Net.findAvailablePort")(function* (preferred, host) { + if (preferred > 0 && (yield* isPortAvailableForHost(preferred, host))) { return preferred; } - return yield* reserveLoopbackPort(); + return yield* reserveLoopbackPort(listensOnLoopback(host) ? undefined : host); }), } satisfies NetServiceShape; }; diff --git a/packages/shared/src/hostClassification.ts b/packages/shared/src/hostClassification.ts index b10b226ec35c7..a9951a869d332 100644 --- a/packages/shared/src/hostClassification.ts +++ b/packages/shared/src/hostClassification.ts @@ -179,5 +179,9 @@ export const isPublicFaviconHost = (host: string): boolean => { export const isWildcardHost = (host: string | undefined): boolean => host === "0.0.0.0" || host === "::" || host === "[::]"; +/** An unset, loopback, or wildcard bind host shares the port that `localhost` clients reach. */ +export const listensOnLoopback = (host: string | undefined): boolean => + host === undefined || host === "" || isWildcardHost(host) || isLocalLoopbackHost(host); + export const formatHostForUrl = (host: string): string => host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; From 8217726c1068751b1951058cf1b185c1091e687a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:42:07 -0800 Subject: [PATCH 087/221] fix(server): cut-off checkpoint captures no longer strand Git LFS temp files (#41697) --- apps/server/src/vcs/GitVcsDriver.test.ts | 181 +++++++++++++++++++++++ apps/server/src/vcs/GitVcsDriver.ts | 68 +++++++++ 2 files changed, 249 insertions(+) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index d2eed8bad23a7..9ef6c1e7a9324 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -369,6 +369,187 @@ it.effect.each(["interrupt", "timeout", "success"] as const)( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.each(["interrupt", "timeout"] as const)( + "checkpoint staging $0 removes the Git LFS temp files its clean filter wrote", + (stop) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + const lfsTmp = path.join(cwd, ".git/lfs/tmp"); + yield* fs.makeDirectory(lfsTmp, { recursive: true }); + const otherOperation = path.join(lfsTmp, "owned-by-another-git-lfs"); + yield* fs.writeFileString(otherOperation, "another git-lfs process is hashing this"); + + const connected = Promise.withResolvers(); + const sockets = new Set(); + const server = yield* Effect.acquireRelease( + Effect.sync(() => + NodeNet.createServer((socket) => { + sockets.add(socket); + connected.resolve(); + }), + ), + (server) => + Effect.sync(() => { + for (const socket of sockets) socket.destroy(); + server.close(); + }), + ); + yield* Effect.promise( + () => + new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }), + ); + const address = server.address(); + assert.isTrue(address !== null && typeof address !== "string"); + if (address === null || typeof address === "string") return; + // Like git-lfs clean: copy the content into /tmp while hashing, and only + // move or remove that copy once hashing finishes. A killed filter strands it. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, Buffer.alloc(1024 * 1024));", + `const s = require('node:net').connect(${address.port}, '127.0.0.1');`, + "s.resume(); process.stdin.resume();", + "s.on('close', () => process.exit(0));", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const fiber = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.promise(() => connected.promise); + const laterOperation = path.join(lfsTmp, "started-during-capture"); + yield* fs.writeFileString(laterOperation, "another git-lfs process started later"); + if (stop === "interrupt") yield* Fiber.interrupt(fiber); + else yield* TestClock.adjust("30 seconds"); + const result = yield* Fiber.await(fiber); + if (stop === "interrupt") + assert.isTrue(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)); + else assert.isTrue(Exit.isSuccess(result) && Exit.isFailure(result.value)); + + assert.sameMembers(yield* fs.readDirectory(lfsTmp), [ + "owned-by-another-git-lfs", + "started-during-capture", + ]); + assert.strictEqual( + yield* fs.readFileString(otherOperation), + "another git-lfs process is hashing this", + ); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint staging moves Git LFS objects its clean filter wrote into LFS storage", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // Like git-lfs clean: hash through /tmp, then move the copy into objects. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "const content = fs.readFileSync(0);", + "const oid = require('node:crypto').createHash('sha256').update(content).digest('hex');", + "fs.mkdirSync(storage + '/tmp', { recursive: true });", + "const dir = storage + '/objects/' + oid.slice(0, 2) + '/' + oid.slice(2, 4);", + "fs.mkdirSync(dir, { recursive: true });", + "fs.writeFileSync(storage + '/tmp/' + process.pid, content);", + "fs.renameSync(storage + '/tmp/' + process.pid, dir + '/' + oid);", + "process.stdout.write('oid sha256:' + oid + '\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + const pointer = yield* git(["show", `${checkpointRef}:weights.npz`]); + const oid = pointer.stdout.trim().slice("oid sha256:".length); + assert.strictEqual( + yield* fs.readFileString( + path.join(cwd, ".git/lfs/objects", oid.slice(0, 2), oid.slice(2, 4), oid), + ), + "large untracked data\n", + ); + assert.isFalse(yield* fs.exists(path.join(cwd, ".git/lfs/tmp"))); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("checkpoint capture fails instead of dropping Git LFS objects it cannot list", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const sandbox = yield* fs.makeTempDirectoryScoped({ prefix: "t3-lfs-checkpoint-" }); + const cwd = path.join(sandbox, "repo"); + yield* fs.makeDirectory(cwd); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + // A file where git-lfs keeps its objects makes the store unreadable without being absent. + const filter = path.join(sandbox, "lfs-clean.cjs"); + yield* fs.writeFileString( + filter, + [ + "const fs = require('node:fs');", + `const storage = require('node:child_process').execSync('git config --default .git/lfs lfs.storage').toString().trim();`, + "fs.readFileSync(0);", + "fs.mkdirSync(storage, { recursive: true });", + "fs.writeFileSync(storage + '/objects', 'not a directory');", + "process.stdout.write('pointer\\n');", + ].join("\n"), + ); + // Not "lfs": a machine-wide git-lfs install sets filter.lfs.process, which wins over clean. + yield* git(["config", "filter.lfs-standin.clean", `"${process.execPath}" "${filter}"`]); + yield* git(["config", "filter.lfs-standin.required", "true"]); + yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "*.npz filter=lfs-standin\n"); + yield* fs.writeFileString(path.join(cwd, "weights.npz"), "large untracked data\n"); + + const result = yield* driver.checkpoints + .captureCheckpoint({ cwd, checkpointRef }) + .pipe(Effect.exit); + + const error = Exit.isFailure(result) ? Cause.findErrorOption(result.cause) : Option.none(); + assert.isTrue( + Option.isSome(error) && + error.value._tag === "VcsCheckpointStorageError" && + error.value.stage === "publish", + ); + const ref = yield* driver.execute({ + operation: "checkpoint-test", + cwd, + args: ["rev-parse", "--verify", "--quiet", checkpointRef], + allowNonZeroExit: true, + }); + assert.strictEqual(ref.exitCode, 1); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect.each(["failure", "interrupt"] as const)( "checkpoint publication $0 preserves existing refs and permits retry", (stop) => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index bba371104af14..551c863510423 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1259,6 +1259,71 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ), ), ); + // git-lfs's clean filter copies each file into /tmp while hashing it and strands + // that copy when killed. Give it storage that is removed with the capture's private objects. + const privateLfs = path.join(privateObjects, "lfs"); + const publishLfsObjects = Effect.gen(function* () { + const source = path.join(privateLfs, "objects"); + const objects = (yield* fileSystem.readDirectory(source, { recursive: true }).pipe( + // Absent when no file went through the filter; any other failure must stop publication. + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + () => Effect.succeed([]), + ), + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ + operation, + cwd: input.cwd, + stage: "publish", + cause, + }), + ), + )).filter((entry) => /^[0-9a-f]{2}[\\/][0-9a-f]{2}[\\/][0-9a-f]{64}$/.test(entry)); + if (objects.length === 0) return; + const configured = yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--get", "lfs.storage"], + allowNonZeroExit: true, + }); + // git-lfs resolves a relative lfs.storage against the common Git directory. + const storage = path.resolve(gitCommonDir, configured.stdout.trim() || "lfs"); + yield* Effect.forEach( + objects, + (entry) => + Effect.gen(function* () { + const from = path.join(source, entry); + const to = path.join(storage, "objects", entry); + if (yield* fileSystem.exists(to)) return; + yield* fileSystem.makeDirectory(path.dirname(to), { recursive: true }); + // Identical oids are interchangeable, so losing a race to another writer is fine. + // lfs.storage may be on another volume, where only a copy can move the object. + const partial = `${to}.${indexId}`; + yield* fileSystem.rename(from, to).pipe( + Effect.catch((cause) => + Effect.flatMap(fileSystem.exists(to), (exists) => + exists + ? Effect.void + : fileSystem.copyFile(from, partial).pipe( + Effect.andThen(fileSystem.rename(partial, to)), + Effect.ensuring( + fileSystem.remove(partial, { force: true }).pipe(Effect.ignore), + ), + Effect.mapError(() => cause), + ), + ), + ), + ); + }), + { concurrency: 16, discard: true }, + ).pipe( + Effect.mapError( + (cause) => + new VcsCheckpointStorageError({ operation, cwd: input.cwd, stage: "publish", cause }), + ), + ); + }); const commitEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: tempIndexPath, GIT_OBJECT_DIRECTORY: privateObjects, @@ -1272,6 +1337,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", GIT_COMMITTER_NAME: "T3 Code", GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + // Any command on the scratch index can run the clean filter, not just add. + ...VcsProcess.gitConfigEnv(hostEnv, "lfs.storage", privateLfs, hostPlatform), }; const cleanupTempIndex = Effect.forEach( @@ -1791,6 +1858,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } + yield* publishLfsObjects; // Git writers have exited; bound publication by fanout directory. yield* fileSystem.readDirectory(privateObjects).pipe( Effect.flatMap((directories) => From 5ab8dc4bfcc6568786a46abec867183e6b8442d4 Mon Sep 17 00:00:00 2001 From: Dibas <81339759+dibas-np@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:28:36 +0545 Subject: [PATCH 088/221] fix(mobile): show every image when Markdown puts one per line (#30280) Co-authored-by: Julius Marminge --- apps/mobile/src/lib/markdownDocument.ts | 35 ++++++++++++++++++++++-- apps/mobile/src/lib/markdownHtml.test.ts | 25 +++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index b44b96fca49b8..c11d00bc9aae0 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -498,13 +498,44 @@ function markdownWithWindowsPathDestinations(markdown: string): string { return applyMarkdownEdits(markdown, edits); } +const isImage = (node: MarkdownNode) => node.type === "image" || node.type === "imageReference"; +const isSpace = (node: MarkdownNode) => + node.type === "break" || (node.type === "text" && node.value.trim() === ""); + +// Native Markdown sizes an image as a block only when it is its paragraph's only child. +function markdownWithImageParagraphs(markdown: string): string { + // Skips the extra parse unless a line ending sits between two images. + if (!/[\])][ \t]*\\?(?:\r\n?|\n)[ \t]*!\[/.test(markdown)) return markdown; + const edits: MarkdownEdit[] = []; + for (const block of parser.parse(markdown).children) { + if ( + block.type !== "paragraph" || + !block.children.every((child) => isImage(child) || isSpace(child)) + ) + continue; + const images = block.children.filter(isImage); + for (const [index, image] of images.slice(1).entries()) { + const start = images[index]!.position?.end.offset; + const end = image.position?.start.offset; + if (start === undefined || end === undefined) continue; + const ending = /\r\n?|\n/.exec(markdown.slice(start, end)); + if (ending) edits.push({ start, end, content: ending[0].repeat(2) }); + } + } + return applyMarkdownEdits(markdown, edits); +} + // HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first. -export function markdownForNativeParsing(markdown: string): string { +function normalizedMarkdown(markdown: string): string { return markdownWithWindowsPathDestinations(markdownWithHtml(markdown)); } +export function markdownForNativeParsing(markdown: string): string { + return markdownWithImageParagraphs(normalizedMarkdown(markdown)); +} + export function parseMarkdownDocument(markdown: string): Root { - return parser.parse(markdownForNativeParsing(markdown)); + return parser.parse(normalizedMarkdown(markdown)); } export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string { diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts index 64c5d02df3532..6cce7f84b475c 100644 --- a/apps/mobile/src/lib/markdownHtml.test.ts +++ b/apps/mobile/src/lib/markdownHtml.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { + markdownForNativeParsing, markdownForNativeRendering, markdownHtmlContent, markdownWithHtml, @@ -303,6 +304,30 @@ describe("file embeds in native thread and file Markdown", () => { } }); + it("gives each image on its own line its own native paragraph", async () => { + const images = + "![before](./before.png)\n![after light](./after-light.png) \\\n![after dark][dark]"; + const source = `Shots:\n\n${images}\n\n![a](./a.svg) ![b](./b.svg)\n![c](./c.svg)\n\nNext\n\n[dark]: ./after-dark.png`; + const paragraphs = ( + await parseMarkdown(markdownForNativeRendering(source, ENRICHED_INLINE_FILE_LINK_REGEX)) + ).children?.map((block) => block.children?.map((child) => child.type).join(" ")); + expect(paragraphs).toEqual([ + "Text", + "Image", + "Image", + "Image", + "Image Text Image", + "Image", + "Text", + ]); + expect(markdownForNativeParsing("![a](./a.png)\r\n![b](./b.png)")).toBe( + "![a](./a.png)\r\n\r\n![b](./b.png)", + ); + expect(markdownForNativeParsing("![a](./a.png)\r![b](./b.png)")).toBe( + "![a](./a.png)\r\r![b](./b.png)", + ); + }); + it("retains standalone audio players and image/video embeds in threads", () => { const source = "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)"; From 0d6fe2141abe62de48d5b836d4ff8b26f37308b5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:44:06 -0800 Subject: [PATCH 089/221] fix(server): mode limits follow the turn a message joins (#41746) Co-authored-by: Claude Fable 5.2 --- .../src/mcp/OrchestratorMcpService.test.ts | 56 ++++- apps/server/src/mcp/OrchestratorMcpService.ts | 56 +++-- .../src/orchestration-v2/Orchestrator.ts | 94 ++++++-- .../ProviderTurnStartService.test.ts | 2 + .../ProviderTurnStartService.ts | 4 + .../SteeringCompletion.integration.test.ts | 221 ++++++++++++++++++ .../scheduledTasks/ScheduledTaskService.ts | 10 +- docs/user/cursor.md | 4 +- packages/contracts/src/orchestrationV2.ts | 4 + .../src/server/adapter.test.ts | 20 +- .../provider-cursor/src/server/adapter.ts | 34 ++- .../src/server/workspaceMcpServers.ts | 4 +- 12 files changed, 456 insertions(+), 53 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 551a84109cfa2..c99f9b0a6e1ad 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3950,6 +3950,8 @@ describe("OrchestratorMcpService provider resolution", () => { boundThread: OrchestrationV2ThreadShell | null, upserted: Ref.Ref, saved: ScheduledTask = tasks[0]!, + /** Stores each keyed create under the id its key derives, as the real service does. */ + created?: Ref.Ref>, ) => OrchestratorMcpService.layer.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), @@ -3984,9 +3986,24 @@ describe("OrchestratorMcpService provider resolution", () => { Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({ - list: () => Effect.succeed({ tasks }), - upsert: () => - Ref.update(upserted, (count) => count + 1).pipe(Effect.as({ task: saved })), + list: () => + created === undefined + ? Effect.succeed({ tasks }) + : Ref.get(created).pipe(Effect.map((stored) => ({ tasks: stored }))), + upsert: (input) => + Ref.update(upserted, (count) => count + 1).pipe( + Effect.andThen( + created === undefined || input.commandId === undefined + ? Effect.void + : Ref.set(created, [ + { + ...saved, + id: ScheduledTaskService.scheduledTaskIdForCommand(input.commandId), + }, + ]), + ), + Effect.as({ task: saved }), + ), }), ), ), @@ -4084,6 +4101,39 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect( + "refuses to replay a creation over a task whose thread now runs above the caller", + () => + Effect.gen(function* () { + const upserted = yield* Ref.make(0); + const created = yield* Ref.make>([]); + const bound = task({ threadId: boundThreadId }); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + service( + [bound], + liveThreadShell(boundThreadId, { runtimeMode: "full-access" }), + upserted, + bound, + created, + ), + ), + ); + const create = (prompt: string) => + mcp.scheduleTask(supervisedClient, { + projectId, + prompt, + schedule: { type: "webhook" }, + freshSession: true, + clientRequestId: "nightly", + }); + yield* create("Check the build"); + const error = yield* create("Something else").pipe(Effect.flip); + assert.equal(error.code, "runtime_mode_escalation_denied"); + assert.equal(yield* Ref.get(upserted), 1); + }), + ); + it.effect("reports a saved task even when its bound thread cannot be read", () => Effect.gen(function* () { const upserted = yield* Ref.make(0); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 8b58504247ba9..825094d4027e0 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2369,6 +2369,21 @@ const make = Effect.gen(function* () { }, ); + const requireScheduledTaskWithinLimits = Effect.fn( + "OrchestratorMcpService.requireScheduledTaskWithinLimits", + )(function* ( + task: ScheduledTask, + limits: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + }, + ) { + for (const modes of yield* scheduledTaskRunModes(task)) { + yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); + yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); + } + }); + /** * A scheduled task the caller may change: one whose runs execute at modes no * broader than the caller's own, so editing its prompt cannot run work above @@ -2392,10 +2407,7 @@ const make = Effect.gen(function* () { if (task === undefined) { return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`); } - for (const modes of yield* scheduledTaskRunModes(task)) { - yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); - } + yield* requireScheduledTaskWithinLimits(task, limits); return task; }); @@ -2423,6 +2435,16 @@ const make = Effect.gen(function* () { .slice(0, 80) .replace(/[\uD800-\uDBFF]$/, ""); const title = input.title ?? (derivedTitle.length > 0 ? derivedTitle : "Scheduled task"); + // Scope the idempotency key by provider session so two callers + // reusing the same clientRequestId cannot collide on one task row. + const commandId = + input.clientRequestId === undefined + ? undefined + : stableCommandId({ + scope, + requestKey: input.clientRequestId, + operation: "schedule-task", + }); const upsertInput: ScheduledTaskUpsertInput = { title, prompt: input.prompt, @@ -2441,18 +2463,22 @@ const make = Effect.gen(function* () { interactionMode: limits.interactionMode, createdBy: "agent", creationSource: "mcp", - // Scope the idempotency key by provider session so two callers - // reusing the same clientRequestId cannot collide on one task row. - ...(input.clientRequestId === undefined - ? {} - : { - commandId: stableCommandId({ - scope, - requestKey: input.clientRequestId, - operation: "schedule-task", - }), - }), + ...(commandId === undefined ? {} : { commandId }), }; + // A replayed key rewrites the task it created, which its user may since have raised or + // rebound: that is an edit of the task as it now stands. + if (commandId !== undefined) { + const replayedId = ScheduledTaskService.scheduledTaskIdForCommand(commandId); + const { tasks } = yield* scheduledTasks + .list() + .pipe( + Effect.mapError((error) => + failure("orchestration_error", `Could not load scheduled task: ${error.message}`), + ), + ); + const replayed = tasks.find((candidate) => candidate.id === replayedId); + if (replayed !== undefined) yield* requireScheduledTaskWithinLimits(replayed, limits); + } const { task } = yield* scheduledTasks .upsert(upsertInput) .pipe( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8547084085e6b..7dc93dc5c196e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6018,6 +6018,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); + // A turn keeps the modes it started with, so a thread lowered since can hold a broader one. + // A turn that recorded none is taken as unrestricted. + const turnStartedModes = ( + attempts: ReadonlyArray, + run: OrchestrationV2Run | undefined, + ) => + attempts.find((attempt) => attempt.id === run?.activeAttemptId)?.startedModes ?? { + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + }; + + // A parked steer is delivered later by the server, without the caller's limit, into a turn + // whose modes are not recorded yet. Only a caller allowed any turn may park or rewrite one. + const limitForbidsParkedSteer = Effect.gen(function* () { + const limit = narrowToCeiling(yield* DispatchModeLimit, runtimeModeCeiling); + return ( + limit !== undefined && + exceededDispatchModeLimit(limit, { + runtimeMode: "full-access", + interactionMode: "default", + }) !== undefined + ); + }); + const refuseAboveDispatchModeLimit = Effect.fn("orchestrationV2.dispatch.refuseAboveModeLimit")( function* ( command: OrchestrationV2ServerCommand, @@ -6694,6 +6718,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); if (steeringPolicy === "active_steering") { + yield* refuseAboveDispatchModeLimit( + input.command, + input.command.threadId, + turnStartedModes(input.projection.attempts, targetRun), + ); const instanceChanged = input.projection.thread.providerInstanceId !== input.modelSelection.instanceId; // Only a user's steer carries the picker's selection; the adapter applies it to the live turn. @@ -7960,21 +7989,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ))) && !(yield* stopReachedRun(command, command.threadId, target.id)) ) { - const adapter = yield* providerAdapters - .get(target.providerInstanceId) - .pipe(mapDispatchError(command)); - const capabilities = yield* adapter.getCapabilities().pipe(mapDispatchError(command)); - yield* commandPolicy - .decideSteeringExecution({ - commandId: command.commandId, - threadId: command.threadId, - providerInstanceId: target.providerInstanceId, - capabilities, - }) - .pipe(mapDispatchError(command)); - yield* ensureSteeringMessage(command, command); - steerWhenReadyRunId = target.id; - dispatchMode = { type: "queue_after_active" }; + // Such a caller's message waits for its own turn instead. + if (yield* limitForbidsParkedSteer) { + dispatchMode = { type: "queue_after_active" }; + } else { + const adapter = yield* providerAdapters + .get(target.providerInstanceId) + .pipe(mapDispatchError(command)); + const capabilities = yield* adapter.getCapabilities().pipe(mapDispatchError(command)); + yield* commandPolicy + .decideSteeringExecution({ + commandId: command.commandId, + threadId: command.threadId, + providerInstanceId: target.providerInstanceId, + capabilities, + }) + .pipe(mapDispatchError(command)); + yield* ensureSteeringMessage(command, command); + steerWhenReadyRunId = target.id; + dispatchMode = { type: "queue_after_active" }; + } } } if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { @@ -11577,6 +11611,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio runtimeRequest.responseCapability.type === "live" ? runtimeRequest.responseCapability.providerSessionId : null; + if (providerSessionId !== null && (yield* DispatchModeLimit) !== undefined) { + // The answer goes into the turn that asked, which keeps the modes it started with. + const live = yield* projectionStore + .getThreadRecords(command.threadId, ["runs", "attempts"]) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + yield* refuseAboveDispatchModeLimit( + command, + command.threadId, + turnStartedModes( + live.attempts, + live.runs.find((run) => run.id === context.node?.runId), + ), + ); + } const providerSession = context.session; if (providerSessionId !== null && providerSession === undefined) { return yield* new OrchestratorDispatchError({ @@ -12171,6 +12223,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ))) && !(yield* stopReachedRun(command, command.threadId, target.id)) ) { + if (yield* limitForbidsParkedSteer) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "The current turn is not running yet. Try again once it is.", + }); + } yield* ensureSteeringMessage(command, queuedMessage); const adapter = yield* providerAdapters .get(target.providerInstanceId) @@ -12576,10 +12635,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A command cannot steer, so an edit into one keeps it queued where it is. if ( queuedRun.steerWhenReadyRunId !== undefined && - isSlashCommand({ + (isSlashCommand({ text: command.text, attachments: command.attachments ?? queuedMessage.attachments, - }) + }) || + (yield* limitForbidsParkedSteer)) ) { const { steerWhenReadyRunId: _, ...queued } = queuedRun; yield* emitEvent({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index ef9bd2bb32712..bcb75e097a5bb 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -582,6 +582,8 @@ function makeLocalCommandHarness(input: { id: threadId, activeProviderThreadId: providerThreadId, projectId: ProjectId.make("project-native-account-command"), + runtimeMode: "full-access", + interactionMode: "default", branch: input.worktreePath === undefined ? null : "feature/restore", worktreePath: input.worktreePath ?? null, lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 1cb77e387f950..e66506fa31f8c 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1959,6 +1959,10 @@ export const layer: Layer.Layer< : { nativeThreadId: runningProviderThread.nativeThreadRef.nativeId }), status: "running", startedAt: now, + startedModes: { + runtimeMode: projection.thread.runtimeMode, + interactionMode: projection.thread.interactionMode, + }, }; const runningRootNode: OrchestrationV2ExecutionNode = { ...rootNode, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 4a665211ef68b..7798a7e00e267 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -14,6 +14,7 @@ import { ProviderInstanceId, ProviderThreadId, ProviderTurnId, + RuntimeRequestId, PROVIDER_SEND_TURN_MAX_INPUT_CHARS, ScheduledTaskId, ThreadId, @@ -34,6 +35,7 @@ import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import { DispatchModeLimit } from "./DispatchModeLimit.ts"; import * as EffectWorker from "./EffectWorker.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; import * as EventSink from "./EventSink.ts"; @@ -512,6 +514,8 @@ const composerSelection = { options: [...runSelection.options, { id: "fastMode", value: false }], }; +const supervised = { runtimeMode: "approval-required", interactionMode: "default" } as const; + const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* ( name: string, canRestart = false, @@ -1940,6 +1944,223 @@ it.effect("queues a steer until the turn ends when the provider cannot steer it" }), ); +it.effect( + "refuses a limited caller's steer into a turn started before its thread was lowered", + () => + Effect.gen(function* () { + const { steered, layer, startFirstTurn } = + yield* nextTurnSelectionHarness("steer-above-limit"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + // Codex keeps its session, and its running turn the full-access policy it started with. + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + const steer = { + type: "message.dispatch", + commandId: CommandId.make("steer"), + threadId, + messageId: MessageId.make("message:steer"), + text: "follow up", + attachments: [], + dispatchMode: { type: "start_immediately" }, + deliveryIntent: "steer", + createdBy: "agent", + creationSource: "mcp", + } as const; + const refused = yield* orchestrator + .dispatch(steer) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + assert.ok(refused._tag === "OrchestratorThreadAboveModeLimitError"); + assert.equal(refused.runtimeMode, "full-access"); + yield* worker.drain(); + assert.deepEqual(steered, []); + + // The refusal records nothing, and a caller without the limit still reaches the turn. + yield* orchestrator.dispatch(steer); + yield* worker.drain(); + assert.lengthOf(steered, 1); + + // The turn's own record decides: one that started within the limit takes the steer. + const attempt = (yield* orchestrator.getThreadProjection(threadId)).attempts[0]!; + assert.deepEqual(attempt.startedModes, { + runtimeMode: "full-access", + interactionMode: "default", + }); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("started-supervised"), + type: "run-attempt.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...attempt, startedModes: supervised }, + }, + ], + }); + yield* orchestrator + .dispatch({ + ...steer, + commandId: CommandId.make("steer-within"), + messageId: MessageId.make("message:steer-within"), + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + yield* worker.drain(); + assert.lengthOf(steered, 2); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("queues a limited caller's steer into a turn that is not running yet", () => + Effect.gen(function* () { + const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness("steer-not-ready"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = yield* startFirstTurn; + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("turn-not-ready"), + type: "provider-turn.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + const steer = (name: string) => + ({ + type: "message.dispatch", + commandId: CommandId.make(name), + threadId, + messageId: MessageId.make(`message:${name}`), + text: "follow up", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "mcp", + }) as const; + const queuedBy = Effect.fn("queuedBy")(function* (name: string) { + return (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make(`message:${name}`), + )!; + }); + // Every MCP caller carries a limit; one at full access parks its steer like the owner. + yield* orchestrator.dispatch(steer("parked")).pipe( + Effect.provideService(DispatchModeLimit, { + runtimeMode: "full-access", + interactionMode: "default", + }), + ); + const parked = yield* queuedBy("parked"); + assert.equal(parked.steerWhenReadyRunId, started[0]!.runId); + + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + // A parked steer is delivered by the server itself, which carries no caller limit. + yield* orchestrator + .dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("edit-parked"), + threadId, + runId: parked.id, + text: "rewritten", + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + assert.isUndefined((yield* queuedBy("parked")).steerWhenReadyRunId); + + yield* orchestrator + .dispatch(steer("steer")) + .pipe(Effect.provideService(DispatchModeLimit, supervised)); + const queued = yield* queuedBy("steer"); + assert.isUndefined(queued.steerWhenReadyRunId); + + yield* orchestrator + .dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queued.id, + targetRunId: started[0]!.runId, + }) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + const kept = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === queued.id, + )!; + assert.equal(kept.status, "queued"); + assert.isUndefined(kept.steerWhenReadyRunId); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("refuses a limited caller's answer to a turn started above its limit", () => + Effect.gen(function* () { + const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness("answer-above"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = yield* startFirstTurn; + const now = yield* DateTime.now; + const requestId = RuntimeRequestId.make("request:question"); + const session = (yield* orchestrator.getThreadProjection(threadId)).providerSessions[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("question"), + type: "runtime-request.updated", + threadId, + occurredAt: now, + payload: { + id: requestId, + nodeId: started[0]!.rootNodeId, + providerTurnId: null, + nativeRequestRef: null, + kind: "command", + status: "pending", + responseCapability: { type: "live", providerSessionId: session.id }, + createdAt: now, + resolvedAt: null, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("lower"), + threadId, + runtimeMode: "approval-required", + }); + const respond = { + type: "runtime-request.respond", + commandId: CommandId.make("respond"), + threadId, + requestId, + decision: "accept", + } as const; + const refused = yield* orchestrator + .dispatch(respond) + .pipe(Effect.provideService(DispatchModeLimit, supervised), Effect.flip); + assert.ok(refused._tag === "OrchestratorThreadAboveModeLimitError"); + assert.equal(refused.runtimeMode, "full-access"); + + yield* orchestrator.dispatch(respond); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).runtimeRequests[0]?.status, + "resolved", + ); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #39404 a later agent message steers ahead of one queued behind /compact it.effect("delivers agent messages queued behind /compact before a later one steers", () => Effect.gen(function* () { diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 3db6f783f649a..488852884f69e 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -81,6 +81,10 @@ import { describeFailedWebhookFilter, findFailedWebhookFilter } from "./webhookF import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerification.ts"; export const WEBHOOK_ROUTE_PREFIX = "/api/hooks"; + +/** The task a create carrying this idempotency key writes, and rewrites when the key is replayed. */ +export const scheduledTaskIdForCommand = (commandId: CommandId) => + ScheduledTaskId.make(`scheduled-task:${commandId}`); const isScheduledTaskError = Schema.is(ScheduledTaskError); const isOrchestratorDispatchError = Schema.is(OrchestratorDispatchError); const PROMPT_TOO_LONG = "The filled-in prompt is too long."; @@ -1480,9 +1484,9 @@ export const layer = Layer.effect( : null; const id = input.id ?? - ScheduledTaskId.make( - input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`, - ); + (input.commandId + ? scheduledTaskIdForCommand(input.commandId) + : ScheduledTaskId.make(`scheduled-task:${uuid}`)); // Look up by the *resolved* id so idempotent creates (commandId replays) // keep their run history, and so real load failures propagate instead // of silently resetting an existing row. diff --git a/docs/user/cursor.md b/docs/user/cursor.md index f10ca24fb596f..f78ccf343d0cb 100644 --- a/docs/user/cursor.md +++ b/docs/user/cursor.md @@ -17,7 +17,9 @@ not expose yet. Custom Cursor MCP servers and plugins are not configured in T3 Code. They load from the environment machine's Cursor config when the agent opens: project `.cursor/mcp.json`, user `~/.cursor/mcp.json`, -and installed plugins under `~/.cursor/plugins`. Plugin tools +and installed plugins under `~/.cursor/plugins`. A project's own Cursor config, including its +`.cursor/mcp.json`, loads only in **Full access**; in the other +[permission modes](./permission-modes.md) a checkout cannot start MCP servers. Plugin tools can appear without a login; OAuth MCP servers still need credentials. Run `agent mcp login ` with the cwd set to the T3 project root (tokens land in `~/.cursor/projects//mcp-auth.json`). Cursor desktop Connections auth does not write diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8843d8cacf805..dfde87c009f66 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -897,6 +897,10 @@ export const OrchestrationV2RunAttempt = Schema.Struct({ ]), startedAt: Schema.NullOr(Schema.DateTimeUtc), completedAt: Schema.NullOr(Schema.DateTimeUtc), + /** The thread's modes when this attempt's turn started. A later change reaches only the next turn. */ + startedModes: Schema.optional( + Schema.Struct({ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode }), + ), }); export type OrchestrationV2RunAttempt = typeof OrchestrationV2RunAttempt.Type; diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 4e687ed2b9c9e..90db987cf2c99 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -3275,7 +3275,7 @@ describe("CursorAdapterV2", () => { const workspace = path.join(scratch, "workspace"); const home = path.join(scratch, "home"); const loadServers = () => - cursorWorkspaceMcpServers(cwd, { MCP_TYPE: "stdio" }).pipe( + cursorWorkspaceMcpServers(cwd, { MCP_TYPE: "stdio" }, { includeProject: true }).pipe( Effect.provideService(HostProcess.HomeDirectory, home), Effect.provideService(HostProcess.Environment, {}), ); @@ -3398,13 +3398,13 @@ describe("CursorAdapterV2", () => { Effect.provideService(HostProcess.Environment, {}), ); const now = yield* DateTime.now; - const sendTurn = (ordinal: number) => + const sendTurn = (ordinal: number, turnPolicy = runtimePolicy) => runtime .startTurn({ threadId, providerThread, modelSelection, - runtimePolicy, + runtimePolicy: turnPolicy, runId: RunId.make(`cursor-mcp-run-${ordinal}`), runOrdinal: ordinal, providerTurnOrdinal: ordinal, @@ -3479,6 +3479,20 @@ describe("CursorAdapterV2", () => { ); yield* sendTurn(3); assert.deepEqual(sentWith[2], t3Servers); + // A restricted turn starts no command the checkout names; the user's own file still applies. + yield* fileSystem.writeFileString( + path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), + "[]", + ); + for (const [index, runtimeMode] of ( + ["approval-required", "auto-accept-edits", "auto"] as const + ).entries()) { + yield* sendTurn(4 + index, { ...runtimePolicy, runtimeMode }); + assert.deepEqual(sentWith[3 + index], { + repro: { command: "node", args: [`${home}/shadowed.mjs`], cwd: projectRoot }, + ...t3Servers, + }); + } yield* fileSystem.writeFileString( path.join(workspace, ".cursor", "mcp.json"), JSON.stringify({ mcpServers: { plain: { command: "node", args: ["server.mjs"] } } }), diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index c758e46a7b3dc..042adcc9c3e9f 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -309,6 +309,17 @@ const CURSOR_AGENT_SETTING_SOURCES = [ "plugins", ] as const satisfies ReadonlyArray; +/** Whether the checkout's own Cursor config (settings, hooks, MCP servers) may load: only unrestricted turns. */ +function cursorLoadsProjectConfig( + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + platform: NodeJS.Platform, +): boolean { + const policy = cursorRuntimeAgentPolicy(runtimePolicy, platform); + return ( + runtimePolicy.runtimeMode === "full-access" && !policy.autoReview && !policy.sandboxEnabled + ); +} + export function makeCursorAgentOptions(input: { readonly apiKey?: string; readonly modelSelection: ModelSelection; @@ -332,12 +343,9 @@ export function makeCursorAgentOptions(input: { ? {} : { dirs: [...input.runtimePolicy.workspace.extraRoots] }), autoReview: policy.autoReview, - settingSources: - input.runtimePolicy.runtimeMode === "full-access" && - !policy.autoReview && - !policy.sandboxEnabled - ? [...CURSOR_AGENT_SETTING_SOURCES] - : CURSOR_AGENT_SETTING_SOURCES.filter((source) => source !== "project"), + settingSources: cursorLoadsProjectConfig(input.runtimePolicy, input.platform) + ? [...CURSOR_AGENT_SETTING_SOURCES] + : CURSOR_AGENT_SETTING_SOURCES.filter((source) => source !== "project"), sandboxOptions: { enabled: policy.sandboxEnabled, }, @@ -2731,10 +2739,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( } }; - const resolveWorkspaceMcpServers = (cwd: string | null) => - cwd === null + const resolveWorkspaceMcpServers = ( + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + ) => { + const { cwd } = runtimePolicy; + return cwd === null ? Effect.succeed({}) - : cursorWorkspaceMcpServers(cwd, adapterOptions.environment).pipe( + : cursorWorkspaceMcpServers(cwd, adapterOptions.environment, { + includeProject: cursorLoadsProjectConfig(runtimePolicy, platform), + }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -2746,6 +2759,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as({})), ), ); + }; const openAgent = Effect.fnUntraced(function* (openInput: { readonly operation: "create" | "resume"; @@ -3030,7 +3044,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( // A send-time set replaces the create-time set, so the workspace servers go only here and are // read again each turn from mcp.json and mcp-disabled.json; both merge with settingSources. const turnMcpServers = { - ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy.cwd)), + ...(yield* resolveWorkspaceMcpServers(turnInput.runtimePolicy)), ...mcpServers, }; let starting = true; diff --git a/packages/provider-cursor/src/server/workspaceMcpServers.ts b/packages/provider-cursor/src/server/workspaceMcpServers.ts index f3e53b508e3b3..6cdfb98f5116a 100644 --- a/packages/provider-cursor/src/server/workspaceMcpServers.ts +++ b/packages/provider-cursor/src/server/workspaceMcpServers.ts @@ -83,6 +83,8 @@ function cursorProjectSlug(projectRoot: string): string { export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")(function* ( cwd: string, environment: NodeJS.ProcessEnv, + // The project file is the checkout's own; a restricted turn must not start its commands. + options: { readonly includeProject: boolean }, ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -144,7 +146,7 @@ export const cursorWorkspaceMcpServers = Effect.fn("cursorWorkspaceMcpServers")( const seen = new Set(); const servers: Record = {}; for (const file of [ - path.join(projectRoot, ".cursor", "mcp.json"), + ...(options.includeProject ? [path.join(projectRoot, ".cursor", "mcp.json")] : []), path.join(userHome, ".cursor", "mcp.json"), ]) { const contents = yield* readJsonc(file); From 7dd35d324db68c092ab5dec0fa7ea7659470c6b3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:45:25 -0800 Subject: [PATCH 090/221] fix(server): link codes and guest links require the access they hand out (#41742) Getting a link code through a linked environment now requires the scopes of the access level requested, and creating a guest link requires orchestration:read, in addition to access:write. The link dialog offers linking through another environment only when the session holds them. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.test.ts | 70 +++++++++++++++++++ .../server/src/peer/PeerClientPairing.test.ts | 32 --------- .../settings/LinkedEnvironmentsSettings.tsx | 14 +++- docs/internals/04_environment-auth.md | 11 ++- docs/internals/06_t3-connect.md | 4 +- docs/user/remote-access.md | 3 +- .../contracts/src/clientRpcPermissions.ts | 11 +++ 7 files changed, 107 insertions(+), 38 deletions(-) diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 750ff136ac07d..15ddfb90b08a5 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -355,6 +355,76 @@ it.effect("pairs a client with a linked environment only for one that may hand o }).pipe(Effect.scoped), ); +it.effect("hands out a link code or a guest link only within what the session itself holds", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.peerLinksPairLink | typeof WS_METHODS.guestShareCreate + > => tag !== WS_METHODS.peerLinksPairLink && tag !== WS_METHODS.guestShareCreate, + ), + ); + let handled = 0; + const environmentId = EnvironmentId.make("environment-box"); + const threadId = ThreadId.make("thread-1"); + const handlers = Layer.mergeAll( + group.toLayerHandler(WS_METHODS.peerLinksPairLink, () => + Effect.sync(() => { + handled++; + return { + type: "unsupported" as const, + reason: "link_access" as const, + environmentId, + label: "Box", + urls: [], + }; + }), + ), + group.toLayerHandler(WS_METHODS.guestShareCreate, () => + Effect.sync(() => handled++).pipe(Effect.andThen(Effect.die("no share in this test"))), + ), + ); + const clientWith = (scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handlers, RpcAuthorization.layer(scopes))), + ); + + // Managing access alone is not running agents or reading threads. + const manager = yield* clientWith([AuthAccessWriteScope]); + expect( + yield* manager[WS_METHODS.peerLinksPairLink]({ environmentId, access: "read-only" }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + expect( + yield* manager[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + + const supervisor = yield* clientWith([ + AuthAccessWriteScope, + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + ]); + expect( + yield* supervisor[WS_METHODS.peerLinksPairLink]({ + environmentId, + access: "full-access", + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthSettingsWriteScope }); + expect(handled).toBe(0); + + expect( + (yield* supervisor[WS_METHODS.peerLinksPairLink]({ environmentId, access: "auto" })).type, + ).toBe("unsupported"); + expect(handled).toBe(1); + yield* supervisor[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.exit); + expect(handled).toBe(2); + }).pipe(Effect.scoped), +); + it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)( "enforces read permission on stream %s", (method) => diff --git a/apps/server/src/peer/PeerClientPairing.test.ts b/apps/server/src/peer/PeerClientPairing.test.ts index 17a5df1cb75ff..8dacc53f7f07e 100644 --- a/apps/server/src/peer/PeerClientPairing.test.ts +++ b/apps/server/src/peer/PeerClientPairing.test.ts @@ -257,38 +257,6 @@ it.effect("pairs no client while Linked environments is off on either side", () ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); -it.effect("a full-access link gets a pairing code that links another environment to the box", () => - Effect.scoped( - Effect.gen(function* () { - const b = yield* serveBox(); - const a = yield* makeLaptop; - yield* linkTo(a.links, b, "full-access"); - const phone = yield* a.client([AuthAccessWriteScope]); - - const result = yield* a.pairing.requestForLink( - { environmentId: box.environmentId, access: "approval-required" }, - phone, - ); - if (result.type !== "credential") return yield* Effect.die(result); - expect(result).toMatchObject({ environmentId: box.environmentId, urls: [b.url] }); - - // A third environment links with it, at the access the code was minted for. - const desk = yield* Layer.build( - layerLinkingEnvironment(descriptorOf("environment-desk", "Desk")), - ); - const linked = yield* Context.get(desk, PeerLinks.PeerLinks).link({ - url: b.url, - pairingCode: result.credential, - access: "approval-required", - }); - expect(linked).toMatchObject({ - environmentId: box.environmentId, - access: "approval-required", - }); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); - it.effect("a linked environment from before link pairing is never asked for one", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 5ab6debec7255..71afddaa33b32 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -329,8 +329,20 @@ export function LinkEnvironmentDialog({ const throughCandidate = prefilledThrough ?? (targetId === null || canMint ? null : (routes.get(targetId) ?? null)); const via = useEnvironment(throughCandidate?.viaEnvironmentId ?? null); + // The environment holding the link refuses a level this client's session there does not hold. + const mayPairThrough = useAtomValue( + peerLinkEnvironment.pairLink.permissionAtom( + throughCandidate?.viaEnvironmentId ?? null, + throughCandidate === null + ? undefined + : { environmentId: throughCandidate.environmentId, access }, + ), + ); const through = - throughCandidate !== null && via !== null && !throughFailed.has(throughCandidate.environmentId) + throughCandidate !== null && + via !== null && + mayPairThrough && + !throughFailed.has(throughCandidate.environmentId) ? throughCandidate : null; const linkBack = useLinkBackOffers(environmentId, targetId === null ? [] : [targetId], open); diff --git a/docs/internals/04_environment-auth.md b/docs/internals/04_environment-auth.md index 53c9f60d8f7c6..8b80c65860d60 100644 --- a/docs/internals/04_environment-auth.md +++ b/docs/internals/04_environment-auth.md @@ -8,8 +8,12 @@ model. ## Scoped sessions and delegation - **Narrowing only.** Pairing delegates a set of scopes. Exchanging a bootstrap credential can - narrow a grant, never widen it. Creating another pairing link requires both `access:write` and - every scope being delegated. Client labels and device metadata have no authorization role. + narrow a grant, never widen it. Client labels and device metadata have no authorization role. +- **`access:write` hands out what the session holds and revokes anything.** Every route that + returns a credential to the caller requires `access:write` and every scope that credential + carries: a pairing link, an MCP sign-in approval, a link code from a linked environment, and a + guest link (which reads a thread). Revoking is not capped by the caller's scopes. Admitting a + T3 Connect device is not delegation; see [T3 Connect](./06_t3-connect.md). - **Why the default grant includes management scopes.** `terminal:operate` and `orchestration:operate` already grant OS-user execution (which can invoke `t3 auth session issue`), so withholding access or relay management from the default grant would not be a real boundary. @@ -48,7 +52,8 @@ model. - **Peer-link client pairing.** Only a full-access peer link may mint a one-time client pairing on the linked environment (since full-access agents can already run `t3 auth pairing create`). The linked side enforces this itself, and the operation stays a human-triggered RPC/HTTP route rather - than an MCP tool. + than an MCP tool. The same route mints a code that links another environment at a chosen access + level, and the linking side's RPC requires the caller to hold that level's scopes. ### Reusable dev credential diff --git a/docs/internals/06_t3-connect.md b/docs/internals/06_t3-connect.md index 2962721830a86..dc60a5468b849 100644 --- a/docs/internals/06_t3-connect.md +++ b/docs/internals/06_t3-connect.md @@ -28,7 +28,9 @@ Deployment and Clerk configuration live in the [Connect setup runbook](../operat compromised relay signing key. Enabling `requireConnectDeviceApproval` shifts trust from the relay to approved DPoP key thumbprints: untrusted keys mint credentials that cannot be spent until someone with `access:write` approves the key, and revoking a key revokes all of its sessions and - pending credentials. + pending credentials. Approving admits a device already signed in to the owner's cloud account + and returns no credential to the approver, so `access:write` alone is enough, as it is for + turning the setting off. - **Anti-hijack and anti-SSRF rules.** Managed tunnels expose only the server's own loopback HTTP origin (ignoring caller-supplied origins). The relay refuses to relink an active environment ID under a different key until unlinked, resolves endpoints only from its own managed allocations, diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 051445f03eb07..bdcd2281ccd08 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -488,7 +488,8 @@ it needs no pairing code. A machine this app is not connected to, shown only because another environment links to it, can still be linked without a code when that link has full access: drop the plus on it and the environment holding the link gets the pairing code -from it. Your session on that environment must manage access there. The result +from it. Your session on that environment must manage access there and already +have the access you pick. The result is a separate link with the access you pick, listed and revocable on the linked machine like any other. Links still do not chain. diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index b23b4650b20a9..eb61fff1c0abd 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -11,7 +11,9 @@ import { AuthSourceControlWriteScope, AuthTerminalOperateScope, type AuthEnvironmentScope, + mcpClientScopes, } from "./auth.ts"; +import { PeerLinkLinkPairingInput } from "./peerLink.ts"; import { ORCHESTRATION_V2_WS_METHODS } from "./orchestrationV2.ts"; import { WS_METHODS } from "./rpc.ts"; @@ -106,6 +108,7 @@ export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; const decodePrepareThread = Schema.decodeUnknownSync(GitPreparePullRequestThreadInput); const decodeStackedAction = Schema.decodeUnknownSync(GitRunStackedActionInput); +const decodeLinkPairing = Schema.decodeUnknownSync(PeerLinkLinkPairingInput); export function clientRpcRequiredScopes( method: string, @@ -124,6 +127,14 @@ export function clientRpcRequiredScopes( ) return [AuthSourceControlWriteScope, AuthOrchestrationReadScope]; } + // Handing out access takes holding it: the caller gets back a credential it can spend itself. + if (method === WS_METHODS.peerLinksPairLink && input !== undefined) { + const held = mcpClientScopes(decodeLinkPairing(input).access); + return [AuthAccessWriteScope, ...held]; + } + if (method === WS_METHODS.guestShareCreate) { + return [AuthAccessWriteScope, AuthOrchestrationReadScope]; + } return Object.hasOwn(CLIENT_GUARDED_RPC_SCOPES, method) ? [CLIENT_GUARDED_RPC_SCOPES[method as ClientGuardedRpcTag]] : []; From 2dd323463a300d82663eaa5df3e9b85b78d3eb7a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 15:48:05 -0800 Subject: [PATCH 091/221] fix(server): API request bodies have a 1 MiB default limit and tag scans stay linear (#41747) Co-authored-by: Claude Fable 5.2 --- apps/server/src/auth/McpOAuth.test.ts | 22 +++++++++++++ apps/server/src/cloud/http.test.ts | 12 +++++++ apps/server/src/http.ts | 7 ++++ apps/server/src/server.ts | 1 + .../src/pullRequestMarkdown.test.ts | 21 ++++++++++++ .../client-runtime/src/pullRequestMarkdown.ts | 32 +++++++++++++++++-- packages/shared/src/htmlRender.test.ts | 21 ++++++++++-- packages/shared/src/htmlRender.ts | 12 ++++--- 8 files changed, 119 insertions(+), 9 deletions(-) diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index f66d0b1c6e81c..c21b707bad889 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -27,6 +27,7 @@ import * as CloudLink from "../cloud/CloudLink.ts"; import * as ServerConfig from "../config.ts"; import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as Sqlite from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; @@ -75,6 +76,7 @@ const makeLayerRoutes = ( ), ), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ).pipe( Layer.provideMerge(layerEnvironmentAuth), @@ -216,6 +218,26 @@ it.effect("derives discovery metadata from the origin the client reached", () => ), ); +it.effect("answers 413 to a body over the API limit", () => + withRoutes((handler) => + Effect.gen(function* () { + const body = "x".repeat(ServerHttp.API_MAX_BODY_BYTES + 1); + for (const [path, contentType] of [ + ["/api/auth/browser-session", "application/json"], + ["/oauth/token", "application/x-www-form-urlencoded"], + ["/oauth/mcp/register", "application/json"], + ]) { + const init = { method: "POST", headers: { "content-type": contentType! } }; + expect((yield* handler(at(path!, { ...init, body }))).status, path).toBe(413); + // A chunked body declares no length, so the reader itself has to stop. + const chunked = new Blob([body]).stream(); + const streamed = at(path!, { ...init, body: chunked, duplex: "half" } as RequestInit); + expect((yield* handler(streamed)).status, `${path} chunked`).toBe(413); + } + }), + ), +); + it.effect("registers loopback and https clients and never redirects for an unverified client", () => withRoutes((handler) => Effect.gen(function* () { diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 5115a27e63012..852be24a22200 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -31,6 +31,7 @@ import * as AuthHttp from "../auth/http.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts"; import * as CliTokenManager from "./CliTokenManager.ts"; @@ -78,6 +79,7 @@ const layerConfig = Layer.effect( const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe( Layer.provide([AuthHttp.layer, ConnectHttp.layer]), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), Layer.provide(CloudLink.layer), Layer.provide(ServerSettings.ServerSettingsService.layerTest()), Layer.provide(EnvironmentKeys.layer), @@ -303,4 +305,14 @@ describe("link proof over a non-loopback transport", () => { expect(response.status).toBe(401); }), ); + + it.effect("answers 413 to a relay proof body over the API limit", () => + Effect.gen(function* () { + const { post } = yield* linkProofClient; + const payload = { proof: "x".repeat(ServerHttp.API_MAX_BODY_BYTES) }; + for (const path of ["/api/t3-connect/health", "/api/t3-connect/mint-credential"]) { + expect((yield* post(path, payload)).status, path).toBe(413); + } + }), + ); }); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 8a31a99287e38..493356998393a 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -33,6 +33,7 @@ import { HttpServerRequest, HttpServerRespondable, } from "effect/http"; +import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import { OtlpTracer, OtlpSerialization } from "effect/observability"; @@ -284,6 +285,12 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers }); }); +// The default body limit for API routes. Routes that take more set their own limit. +export const API_MAX_BODY_BYTES = 1024 * 1024; +export const layerApiBodyLimit = HttpRouter.middleware( + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(API_MAX_BODY_BYTES)), +).layer; + export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compression(), { global: true, }); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 26cea18609b93..b3c21d9918860 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -900,6 +900,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(ServerHttp.layerServerEnvironmentHttpApi), Layer.provide(WebhookRoute.layer.pipe(Layer.provide(RelayDeliveryProof.layer))), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index 7d9d162d76a05..a397241775db6 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -190,6 +190,15 @@ describe("pull request body segmentation", () => { ]); }); + it.each([ + ["a whitespace run inside a line", `a${" ".repeat(1_000_000)}b`], + ["a run of unclosed video tags", `${"
(promise: Promise, millis: number): Promise { @@ -471,20 +476,21 @@ async function captureElement(element: Element): Promise { pickedAt: new Date().toISOString(), }; try { - const context = await withCaptureTimeout( - Promise.resolve(getElementContext(element)), + const context: unknown = await withCaptureTimeout( + Promise.resolve(pageWorld.elementContext(element)), ELEMENT_CONTEXT_TIMEOUT_MS, ); - if (context) { - const stack = (context.stack ?? []).map(toStackFrame); + if (typeof context === "object" && context !== null) { + const frames = pageField(context, "stack"); + const stack = Array.isArray(frames) ? frames.map(toStackFrame) : []; return { ...base, - selector: context.selector, - htmlPreview: context.htmlPreview ?? "", - componentName: context.componentName, + selector: pageString(context, "selector"), + htmlPreview: pageString(context, "htmlPreview") ?? "", + componentName: pageString(context, "componentName"), source: stack[0] ?? null, stack, - styles: context.styles ?? "", + styles: pageString(context, "styles") ?? "", }; } } catch {} diff --git a/apps/desktop/src/preview/WebviewPreferences.test.ts b/apps/desktop/src/preview/WebviewPreferences.test.ts index 572a290e2b669..ed3df8bb1f9c7 100644 --- a/apps/desktop/src/preview/WebviewPreferences.test.ts +++ b/apps/desktop/src/preview/WebviewPreferences.test.ts @@ -25,6 +25,10 @@ describe("PREVIEW_WEBVIEW_PREFERENCES", () => { } }); + it("keeps the page out of the picker preload's JavaScript world", () => { + expect(parsed["contextIsolation"]).toBe("true"); + }); + it("keeps the renderer sandbox enabled (so the page cannot reach Node APIs)", () => { expect(parsed["sandbox"]).toBe("true"); }); diff --git a/apps/desktop/src/preview/WebviewPreferences.ts b/apps/desktop/src/preview/WebviewPreferences.ts index 4dc9d9aa6b732..cb1ddb11bd1ea 100644 --- a/apps/desktop/src/preview/WebviewPreferences.ts +++ b/apps/desktop/src/preview/WebviewPreferences.ts @@ -1,3 +1,3 @@ -/** sandbox:true is required with contextIsolation:false or the shared page global would expose Node and IPC. */ +/** The picker preload runs in its own JavaScript world; PageWorld.ts holds what must run in the page's. */ export const PREVIEW_WEBVIEW_PREFERENCES = - "contextIsolation=false,sandbox=true,nodeIntegration=false"; + "contextIsolation=true,sandbox=true,nodeIntegration=false"; diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 3d882399a6173..28a2cde19d0cc 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -76,6 +76,7 @@ function makeFakeBrowserWindow() { const webContents = { id: 1, session: { + setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn(), }, @@ -1536,7 +1537,7 @@ describe("DesktopWindow", () => { }, { primaryPasteEnabled: true, expected: [PASSKEY_BRIDGE_ARGUMENT] }, ])( - "passes the primary-paste setting to preview guests (enabled: $primaryPasteEnabled)", + "isolates preview guests and passes them the primary-paste setting (enabled: $primaryPasteEnabled)", ({ primaryPasteEnabled, expected }) => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1562,6 +1563,7 @@ describe("DesktopWindow", () => { }); assert.deepEqual(webPreferences.additionalArguments, expected); + assert.isTrue(webPreferences.contextIsolation); }).pipe(Effect.provide(layer)); }), ); @@ -1615,6 +1617,63 @@ describe("DesktopWindow", () => { }), ); + it.effect("opens only web links from popups and declines external-protocol navigations", () => + Effect.gen(function* () { + const fakeWindow = makeFakeBrowserWindow(); + const openedExternalUrls: unknown[] = []; + const layer = layerTest({ + window: fakeWindow.window, + createCount: yield* Ref.make(0), + mainWindow: yield* Ref.make>(Option.none()), + openedExternalUrls, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const openHandler = vi.mocked(fakeWindow.window.webContents.setWindowOpenHandler).mock + .lastCall?.[0]; + if (!openHandler) { + return yield* Effect.die("window open handler was not registered"); + } + for (const url of [ + "vscode://file/home/user/project/readme.md", + "vscode://vscode-remote/ssh-remote+remote.example/home/user/project", + "zed://ssh/remote.example/home/user/project", + "jetbrains://gateway/ssh/environment?h=remote.example", + "grokbot://app/v1/prompt?text=hi", + "https://example.com/docs", + ]) { + assert.deepEqual( + openHandler({ url } as Electron.HandlerDetails), + { action: "deny" }, + url, + ); + } + yield* Effect.promise(() => Promise.resolve()); + + assert.deepEqual(openedExternalUrls, ["https://example.com/docs"]); + + const answerPermission = vi.mocked( + fakeWindow.window.webContents.session.setPermissionRequestHandler, + ).mock.lastCall?.[0]; + if (!answerPermission) { + return yield* Effect.die("permission request handler was not registered"); + } + const answers = (["openExternal", "media"] as const).map((permission) => { + const callback = vi.fn(); + answerPermission(fakeWindow.window.webContents, permission, callback, { + isMainFrame: false, + requestingUrl: "http://127.0.0.1:3773/api/assets/token/page.html", + }); + return callback.mock.lastCall?.[0]; + }); + assert.deepEqual(answers, [false, true]); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("offers to copy the bare address when right-clicking a mailto link", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index c99fbb52c49e2..ebf64c7540507 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -633,7 +633,7 @@ export const make = Effect.gen(function* () { webPreferences.sandbox = true; webPreferences.nodeIntegration = false; webPreferences.nodeIntegrationInSubFrames = false; - webPreferences.contextIsolation = false; + webPreferences.contextIsolation = true; webPreferences.disableHtmlFullscreenWindowResize = true; if (previewPasskeys.bridgeEnabled) { webPreferences.additionalArguments = [ @@ -773,12 +773,19 @@ export const make = Effect.gen(function* () { void runPromise(previewManager.prepareWebview(contents)); }); + // Popups from every frame in this window arrive here without a caller, so only web links + // pass. The app opens editors and other applications over IPC. window.webContents.setWindowOpenHandler(({ url }) => { - if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) { + if (Option.isSome(ElectronShell.parseWebExternalUrl(url))) { void runPromise(electronShell.openExternal(url)); } return { action: "deny" }; }); + // Chromium asks this before handing a navigation to an OS protocol handler, and grants it + // when nothing answers. External links are opened through ElectronShell only. + window.webContents.session.setPermissionRequestHandler((_contents, permission, callback) => + callback(permission !== "openExternal"), + ); window.webContents.on("will-navigate", (event, url) => { if ( isSameOriginRendererNavigation({ diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 42063f99b63a0..4866dd32d08f9 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -2,6 +2,7 @@ import "vite-plus/test/config"; import * as NodeOS from "node:os"; import { defaultInclude, defineConfig } from "vite-plus"; +import { Rolldown } from "vite-plus/pack"; import { isDesktopRuntimeExternalDependency } from "../../scripts/lib/desktop-external-packages.ts"; import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; @@ -26,6 +27,28 @@ const publicConfigDefine = { ), }; +const PAGE_WORLD_MODULE = /[\\/]src[\\/]preview[\\/]PageWorld\.ts$/; + +/** + * The preview preload passes `installPageWorld` to `contextBridge.executeInMainWorld`, which runs + * the function's source text in the page. Inline the module's imports into the function body so + * that text is complete on its own. + */ +const pageWorldFunction = (): Rolldown.Plugin => ({ + name: "t3code:preview-page-world", + async load(id) { + if (!PAGE_WORLD_MODULE.test(id)) return null; + const bundle = await Rolldown.rolldown({ input: id, platform: "browser" }); + try { + const { output } = await bundle.generate({ format: "iife", name: "pageWorld" }); + for (const file of await bundle.watchFiles) this.addWatchFile(file); + return `export function installPageWorld(host) {\n${output[0].code}\nreturn pageWorld.installPageWorld(host);\n}\n`; + } finally { + await bundle.close(); + } + }, +}); + export default defineConfig({ run: { tasks: { @@ -136,11 +159,9 @@ export default defineConfig({ sourcemap: true, outExtensions: () => ({ js: ".cjs" }), entry: ["src/preview-pick-preload.ts"], + plugins: [pageWorldFunction()], deps: { - alwaysBundle: (id) => - id === "react-grab" || - id.startsWith("react-grab/") || - id === "@t3tools/shared/keybindingMatching", + alwaysBundle: (id) => id === "@t3tools/shared/keybindingMatching", }, }, { diff --git a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx index a072ecc107e26..645d53d630c74 100644 --- a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx @@ -96,6 +96,7 @@ vi.mock(import("../localApi"), async (original) => ({ shell: { openExternal: state.openExternal }, }) as never, })); +vi.mock(import("../env"), async (original) => ({ ...(await original()), isElectron: true })); vi.mock(import("@t3tools/client-runtime/change-request-links"), async (original) => ({ ...(await original()), resolvePullRequestPreviewTarget: () => null, @@ -323,3 +324,19 @@ it("preserves keyboard activation of a file-options button", async () => { await userEvent.click(button); await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("mouse")); }); + +it("opens an editor link over the desktop bridge on a click and on a middle-click", async () => { + using _setup = setup(); + const href = "vscode://file/work/docs/readme.md:3"; + await using screen = await renderMarkdown(`[Open in editor](${href})`); + for (const [type, button] of [ + ["click", 0], + ["auxclick", 1], + ] as const) { + const event = new MouseEvent(type, { bubbles: true, cancelable: true, button }); + await act(async () => screen.anchor().dispatchEvent(event)); + expect(event.defaultPrevented).toBe(true); + expect(state.openExternal).toHaveBeenLastCalledWith(href); + } + expect(state.openExternal).toHaveBeenCalledTimes(2); +}); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index f29acac070e42..f41cc0375bee2 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -1427,7 +1427,8 @@ const CHAT_MARKDOWN_COMPONENTS = { }) !== "app" ) { // Open desktop Alt-clicks before Chromium downloads them so link routers can read the held key. - if (isElectron && event.altKey) { + // Editor links also go over IPC: the desktop popup handler only passes web links. + if (isElectron && (event.altKey || isLocalEditorFileHref(href))) { event.preventDefault(); event.stopPropagation(); void readLocalApi() @@ -1453,6 +1454,19 @@ const CHAT_MARKDOWN_COMPONENTS = { void readLocalApi()?.shell.openExternal(href); }); }} + onAuxClick={(event) => { + // A middle-click raises no click event, and the desktop popup handler only passes web links. + if (!isElectron || event.button !== 1 || !href || !isLocalEditorFileHref(href)) return; + event.preventDefault(); + void readLocalApi() + ?.shell.openExternal(href) + .catch((cause) => + reportMarkdownActionFailure( + { operation: "open-link-external", target: href }, + cause, + ), + ); + }} onKeyDown={(event) => { if (href && faviconHost) openContextMenuFromKeyboard(event); }} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 962cfd089dd2b..45f55bde2b2d8 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -675,7 +675,7 @@ export interface DesktopPreviewRecordingInputEvent { export interface DesktopPreviewWebviewConfig { partition: string; - /** Sandboxed with contextIsolation off so the picker preload can read the React DevTools hook. */ + /** Sandboxed and context-isolated; the picker preload reaches React through a function it runs in the page. */ webPreferences: string; /** Absolute file:// preload URL; null requires disabling element picking. */ preloadUrl: string | null; From 78cffe29ec3adc3d1c0acde2f4425c616973114f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:07:52 -0800 Subject: [PATCH 099/221] fix: a merge or review stays on the commit you opened the pull request on (#41761) Co-authored-by: Claude Fable 5.2 --- .../pull-requests/PullRequestControls.tsx | 8 +- .../PullRequestMergeControls.tsx | 13 ++- .../pull-requests/PullRequestReviewSheet.tsx | 14 ++- .../pull-requests/PullRequestRouteScreen.tsx | 8 +- .../guide/PullRequestGuideScreen.tsx | 1 + .../pullRequest/PullRequestService.test.ts | 11 ++- .../src/pullRequest/PullRequestService.ts | 85 +++++++++++-------- .../chat/ThreadDetailsPrRow.browser.test.tsx | 40 ++++++--- .../components/chat/ThreadDetailsPrRow.tsx | 10 ++- .../pullRequest/PullRequestComposer.tsx | 6 ++ ...stDetailPanel.permissions.browser.test.tsx | 51 ++++++++++- .../pullRequest/PullRequestDetailPanel.tsx | 47 ++++++++++ .../PullRequestReviewForm.browser.test.tsx | 8 +- .../pullRequest/PullRequestReviewForm.tsx | 7 ++ .../PullRequestStackMenu.browser.test.tsx | 21 ++++- .../pullRequest/PullRequestStackMenu.tsx | 6 +- .../pullRequestDetail.logic.test.ts | 14 +++ .../pullRequest/pullRequestDetail.logic.ts | 21 +++++ .../usePullRequestActions.browser.test.tsx | 6 ++ .../pullRequest/usePullRequestActions.ts | 8 ++ apps/web/src/i18n/translations/de.json | 2 + apps/web/src/i18n/translations/en.json | 2 + apps/web/src/i18n/translations/es.json | 2 + apps/web/src/i18n/translations/fr.json | 2 + apps/web/src/i18n/translations/ja.json | 2 + apps/web/src/i18n/translations/ko.json | 2 + apps/web/src/i18n/translations/pt-BR.json | 2 + apps/web/src/i18n/translations/ru.json | 2 + apps/web/src/i18n/translations/sv.json | 2 + apps/web/src/i18n/translations/zh.json | 2 + docs/user/source-control.md | 5 ++ .../src/state/pullRequests.test.ts | 33 +++++++ .../client-runtime/src/state/pullRequests.ts | 9 +- packages/contracts/src/pullRequest.ts | 2 + .../src/server/PullRequestProvider.ts | 2 + .../src/server/ForgejoPullRequestProvider.ts | 2 +- .../src/server/GitCafePullRequestProvider.ts | 2 +- .../src/server/GitHubPullRequestApi.ts | 2 + .../src/server/gitHubPullRequestJson.test.ts | 2 + .../src/server/gitHubPullRequestJson.ts | 4 + 40 files changed, 396 insertions(+), 72 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx index 99ad80b80074e..11e92266cc327 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx @@ -119,6 +119,8 @@ export function PullRequestActionToolbar(props: { readonly pr: PullRequestDetail | null; readonly params: PullRequestParams; readonly filePath?: string; + /** The head of the diff on screen, when the screen shows one. */ + readonly reviewedHeadSha?: string | undefined; /** The screen's actions menu; the vertical bar shows it here with the toolbar's tools. */ readonly menu: AppBarMenu; readonly onOpenFiles?: () => void; @@ -152,7 +154,11 @@ export function PullRequestActionToolbar(props: { const chooseThread = agent.chooseThread; const agentActions = agent.actions.filter((action) => action.task !== "ask"); const open = (mode: "review" | "comment") => - navigation.navigate("PullRequestReview", { ...props.params, mode }); + navigation.navigate("PullRequestReview", { + ...props.params, + mode, + reviewedHeadSha: props.reviewedHeadSha ?? props.pr?.headSha, + }); const primaryPress = () => (pendingReview ? open("review") : agent.start("ask")); const threadMenuItems = agent.threadActions("ask"); const openFiles = diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx index 42894c06b3785..0fcc79c3eb7ac 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx @@ -158,7 +158,10 @@ export function PullRequestMergeControls(props: { permissions.canWrite && canPerformPullRequestAction(pr, autoAction); - const perform = async (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => { + const perform = async ( + action: "merge" | "enable-auto-merge" | "disable-auto-merge", + shownHeadSha: string | undefined, + ) => { if ( pending.current || (action !== "disable-auto-merge" && !method) || @@ -172,6 +175,10 @@ export function PullRequestMergeControls(props: { input: { ...target.input, action, + // A merge lands the head on screen and refuses one that moved; a stack pins its other layers. + ...(action !== "disable-auto-merge" && shownHeadSha + ? { expectedHeadSha: shownHeadSha } + : {}), ...(action === "merge" && method && stack.stack && scope ? { stackNumber: stack.stack.number, @@ -218,6 +225,8 @@ export function PullRequestMergeControls(props: { } }; const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => { + // The overview refreshes on focus, so the alert merges the head it was opened on. + const shownHeadSha = pr.headSha; const title = action === "merge" ? scope && scope.layers.length > 1 @@ -274,7 +283,7 @@ export function PullRequestMergeControls(props: { : action === "enable-auto-merge" ? gt("Enable auto-merge") : gt("Disable auto-merge"), - onPress: () => void perform(action), + onPress: () => void perform(action, shownHeadSha), }, ]); }; diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx index ec45e5f3a33ca..8bf3c0290b45d 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx @@ -70,7 +70,13 @@ const VERDICTS = [ export function PullRequestReviewSheet({ route, -}: StaticScreenProps) { +}: StaticScreenProps< + PullRequestParams & { + readonly mode: "review" | "comment"; + /** The head the opening screen showed; this sheet's own read can run ahead of it. */ + readonly reviewedHeadSha?: string | undefined; + } +>) { const params = route.params; const gt = useGT(); const m = useMessages(); @@ -97,6 +103,7 @@ export function PullRequestReviewSheet({ onChangeValue: setBody, support: result.data?.capabilities ?? null, }); + const reviewedHeadSha = params.reviewedHeadSha ?? result.data?.headSha; const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha); const [requestedVerdict, setRequestedVerdict] = useState("comment"); const offered = VERDICTS.filter((option) => permissions.verdicts.includes(option.value)); @@ -130,6 +137,7 @@ export function PullRequestReviewSheet({ ...target, input: { ...target.input, + ...(reviewedHeadSha ? { expectedHeadSha: reviewedHeadSha } : {}), verdict: verdict.value, body, comments: submitted.comments.map( @@ -150,8 +158,8 @@ export function PullRequestReviewSheet({ - navigation.navigate("PullRequestReview", { ...params, mode: "review" }), + navigation.navigate("PullRequestReview", { + ...params, + mode: "review", + reviewedHeadSha: pr?.headSha, + }), }, ] : []), @@ -1271,6 +1275,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { navigation.navigate("PullRequestReview", { ...route.params, mode: "review", + reviewedHeadSha: diffHead.sha ?? undefined, }), }, ] @@ -1503,6 +1508,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { navigation.navigate("PullRequestFiles", route.params)} diff --git a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx index 852ba3932323e..97e35e7739f8e 100644 --- a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx +++ b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx @@ -283,6 +283,7 @@ export function PullRequestGuideStopScreen({ route }: StaticScreenProps +it.effect("refuses a merge or review whose head moved past expectedHeadSha and pins the host", () => Effect.gen(function* () { const head = "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567"; const pinned: Array = []; + const reviewed: Array = []; const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ @@ -1566,10 +1567,18 @@ it.effect("refuses a merge whose head moved past expectedHeadSha and pins the ho getChangeRequest: () => Effect.succeed({ ...hostedChangeRequest("Body"), headSha: head }), getChangeRequestSummary: () => Effect.succeed(changeRequest(1, "2026-09-03T00:00:00Z")), runAction: (input) => Effect.sync(() => void pinned.push(input.expectedHeadSha)), + submitReview: (input) => Effect.sync(() => void reviewed.push(input.expectedHeadSha)), }), ], }); const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const approval = { ...reference, verdict: "approve" as const, body: "", comments: [] }; + const unseen = yield* Effect.flip( + service.submitReview({ ...approval, expectedHeadSha: "0a1b2c4" }), + ); + assert.include(unseen.message, head); + yield* service.submitReview({ ...approval, expectedHeadSha: "0a1b2c3d4" }); + assert.deepStrictEqual(reviewed, [head]); const refused = yield* Effect.flip( service.runAction({ ...reference, action: "merge", expectedHeadSha: "0a1b2c4" }), ); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 690b7c4153f98..b7e56e2062096 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -2315,32 +2315,7 @@ export const make = Effect.gen(function* () { ), ) : Effect.succeed(false); - // Hosts that cannot pin a merge to a commit still refuse a head that already moved. - const expected = input.expectedHeadSha; - const headPinned: Effect.Effect = - expected === undefined - ? Effect.undefined - : project.api - .getChangeRequest({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - number: input.number, - }) - .pipe( - Effect.mapError(toPullRequestError("runAction")), - Effect.flatMap((current) => - typeof current.headSha === "string" && isHeadSha(current.headSha, expected) - ? Effect.succeed(current.headSha) - : Effect.fail( - new PullRequestOperationError({ - operation: "runAction", - detail: `The head is now ${current.headSha ?? "unknown"}, not ${expected}. Review the new commits first.`, - }), - ), - ), - ); - return headPinned.pipe( + return pinnedHead(project, input, "runAction").pipe( Effect.flatMap((expectedHeadSha) => Effect.map(mergeSettings, (removeAgentCreditsOnMerge) => ({ expectedHeadSha, @@ -2407,6 +2382,37 @@ export const make = Effect.gen(function* () { }), ); + // Hosts that cannot pin a write to a commit still refuse a head that already moved. + const pinnedHead = ( + project: SupportedProject, + input: { readonly number: number; readonly expectedHeadSha?: string | undefined }, + operation: string, + ): Effect.Effect => { + const expected = input.expectedHeadSha; + return expected === undefined + ? Effect.undefined + : project.api + .getChangeRequest({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + }) + .pipe( + Effect.mapError(toPullRequestError(operation)), + Effect.flatMap((current) => + typeof current.headSha === "string" && isHeadSha(current.headSha, expected) + ? Effect.succeed(current.headSha) + : Effect.fail( + new PullRequestOperationError({ + operation, + detail: `The head is now ${current.headSha ?? "unknown"}, not ${expected}. Review the new commits first.`, + }), + ), + ), + ); + }; + const comment: PullRequestService["Service"]["comment"] = (input) => (input.body.trim().length === 0 ? Effect.fail( @@ -2566,17 +2572,22 @@ export const make = Effect.gen(function* () { "You need write access on this repository to comment on a line of a change request.", ); } - return project.api - .submitReview({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - number: input.number, - verdict: input.verdict, - body: input.body, - comments: input.comments, - }) - .pipe(Effect.mapError(toPullRequestError("submitReview"))); + return pinnedHead(project, input, "submitReview").pipe( + Effect.flatMap((expectedHeadSha) => + project.api + .submitReview({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + verdict: input.verdict, + body: input.body, + comments: input.comments, + ...(expectedHeadSha === undefined ? {} : { expectedHeadSha }), + }) + .pipe(Effect.mapError(toPullRequestError("submitReview"))), + ), + ); }), ); }), diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index b17067affb96f..666bbccd13684 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -17,6 +17,7 @@ import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ issuesSupported: false, isDraft: false, + headSha: "shown-head", status: "success" as PullRequestCheck["status"], extraStatus: null as PullRequestCheck["status"] | null, mergeMethods: ["merge"] as Array<"merge" | "squash" | "rebase">, @@ -59,6 +60,7 @@ const queryData = () => ({ title: "Test PR", state: "open", isDraft: state.isDraft, + headSha: state.headSha, mergeability: "mergeable", headBranch: "feature", baseBranch: "main", @@ -178,19 +180,21 @@ it("merges with the last selected merge method", async () => { const { container } = screen; state.mergeMethods = ["merge", "squash"]; useUiStateStore.getState().setPullRequestMergeMethod("squash"); - await act(async () => { - await screen.rerender( - , - ); - }); + const rerender = () => + act(async () => { + await screen.rerender( + , + ); + }); + await rerender(); const clickMerge = async (scope: ParentNode) => await act(async () => { [...scope.querySelectorAll("button")] @@ -200,10 +204,17 @@ it("merges with the last selected merge method", async () => { await clickMerge(container); const dialog = document.querySelector('[role="alertdialog"]')!; expect(dialog.textContent).toContain("using squash"); + // A push that a background refresh picks up while the confirmation is open. + state.headSha = "pushed-head"; + await rerender(); await clickMerge(dialog); expect(state.perform).toHaveBeenCalledWith( expect.objectContaining({ - input: expect.objectContaining({ action: "merge", mergeMethod: "squash" }), + input: expect.objectContaining({ + action: "merge", + mergeMethod: "squash", + expectedHeadSha: "shown-head", + }), }), ); }); @@ -260,6 +271,7 @@ async function setup() { state.updateToast.mockReset(); state.issuesSupported = false; + state.headSha = "shown-head"; state.isDraft = false; state.status = "success"; state.extraStatus = null; diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index 3b7836b32293d..dd3e93ca9a578 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -166,14 +166,19 @@ export function ThreadDetailsPrRow({ checks: detail?.checks ?? [], }); + const [armedMergeHead, setArmedMergeHead] = useState(); const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId, reference, + // The row shows no diff, so a merge lands the head it had when the confirmation opened. + headSha: armedMergeHead ?? detail?.headSha, terminology, onSuccess: () => { checksQuery.refresh(); onActed?.(); }, + // A refused merge usually means the row is stale, so show what the host has now. + onFailure: () => detailQuery.refresh(), }); const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail }); const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod); @@ -449,7 +454,10 @@ export function ThreadDetailsPrRow({ method: mergeMethodKey, }, ), - onClick: () => setConfirmingMerge(true), + onClick: () => { + setArmedMergeHead(detail?.headSha); + setConfirmingMerge(true); + }, } : null; diff --git a/apps/web/src/components/pullRequest/PullRequestComposer.tsx b/apps/web/src/components/pullRequest/PullRequestComposer.tsx index e59580d43bddd..e6dd58e82b824 100644 --- a/apps/web/src/components/pullRequest/PullRequestComposer.tsx +++ b/apps/web/src/components/pullRequest/PullRequestComposer.tsx @@ -22,6 +22,7 @@ export function PullRequestComposer({ environmentId, reference, detail, + shownHeadSha, actionPending, onCommentAction, onCommented, @@ -31,6 +32,8 @@ export function PullRequestComposer({ environmentId: EnvironmentId; reference: PullRequestRef; detail: PullRequestDetailView; + /** The head the reader was shown, which a background refresh of `detail` can run ahead of. */ + shownHeadSha: string | undefined; actionPending: boolean; onCommentAction: ( body: string, @@ -180,6 +183,7 @@ export function PullRequestComposer({ active={open && mode === "review"} environmentId={environmentId} reference={reference} + headSha={shownHeadSha} completionScope={pullRequestCompletionScope(detail, environmentId, reference)} term={term} verdicts={verdicts} @@ -193,6 +197,8 @@ export function PullRequestComposer({ setOpen(false); onReviewSubmitted(); }} + // A refusal usually means new commits, so show what the host has now. + onRefused={onReviewSubmitted} /> ) : null} diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx index 74a755927854e..e7a4733ae9410 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx @@ -7,12 +7,13 @@ import { type PullRequestDetailView, } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import appCss from "~/index.css?inline"; import { DraftId, useComposerDraftStore } from "~/composerDraftStore"; import { act, fakeTimers, render } from "../../../test/render"; -const { permissions, reads, shown } = vi.hoisted(() => ({ +const { command, permissions, reads, shown } = vi.hoisted(() => ({ + command: vi.fn(), permissions: { checkout: true, operate: true }, reads: { diff: [] as unknown[] }, shown: { detail: null as PullRequestDetailView | null }, @@ -70,7 +71,7 @@ vi.mock(import("~/state/pullRequests"), async (original) => { }); vi.mock(import("~/state/use-atom-command"), async (original) => ({ ...(await original()), - useAtomCommand: (() => vi.fn()) as never, + useAtomCommand: (() => command) as never, })); import { createWorkspaceFocusController, workspaceAreaProps } from "~/lib/workspaceFocus"; @@ -153,6 +154,7 @@ function setup() { permissions.operate = true; reads.diff = []; shown.detail = detail; + command.mockReset(); useComposerDraftStore.setState({ draftsByThreadKey: {} }); } @@ -183,6 +185,49 @@ it("can still add conflict resolution to an existing composer without checkout s expect(draft?.prompt).toContain(detail.url); }); +it("keeps a merge and a review on the head the reader was shown until they load new commits", async () => { + setup(); + command.mockResolvedValue({ _tag: "Success", value: undefined }); + const at = (headSha: string): PullRequestDetailView => ({ + ...detail, + headSha, + mergeability: "mergeable", + mergeCapabilities: { merge: false, squash: true, rebase: false }, + capabilities: { + ...detail.capabilities, + actions: ["merge"], + mergeMethods: ["squash"], + review: { ...detail.capabilities.review, verdicts: ["approve"] }, + }, + viewerPermissions: { ...detail.viewerPermissions, actions: ["merge"], verdicts: ["approve"] }, + }); + const sent = (key: "action" | "verdict") => + command.mock.calls.flatMap(([call]) => + call?.input?.[key] === undefined ? [] : [call.input.expectedHeadSha], + ); + const merge = async () => { + await screen.getByRole("button", { name: "Squash and merge" }).click(); + await screen.getByRole("button", { name: "Confirm merge?" }).click(); + }; + shown.detail = at("shown-head"); + await using screen = await render(panel()); + await expect.element(screen.getByRole("button", { name: "Squash and merge" })).toBeVisible(); + // A background refresh brings a push the reader has not looked at. + shown.detail = at("pushed-head"); + await screen.rerender(panel()); + await expect.element(screen.getByText(/still applies to shown-h/)).toBeVisible(); + await merge(); + await screen.getByRole("button", { name: "Review pull request" }).click(); + // The composer popup is portalled outside the rendered tree. + await page.getByRole("button", { name: "Submit review" }).click(); + await vi.waitFor(() => expect(sent("verdict")).toEqual(["shown-head"])); + expect(sent("action")).toEqual(["shown-head"]); + + await screen.getByRole("button", { name: "Load new commits" }).click(); + await merge(); + await vi.waitFor(() => expect(sent("action")).toEqual(["shown-head", "pushed-head"])); +}); + it("reads the first diff page once the pointer rests on the Code tab", async () => { setup(); await using screen = await render(panel()); diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1e14ab19d9012..110aac26cde5c 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -36,6 +36,7 @@ import { GitCommitHorizontalIcon, MessageSquareIcon, PanelRightIcon, + TriangleAlertIcon, } from "lucide-react"; import { lazy, @@ -83,6 +84,7 @@ import { vcsEnvironment } from "~/state/vcs"; import { RelativeTime } from "~/components/RelativeTime"; import { useUiStateStore } from "~/uiStateStore"; +import { Alert, AlertAction, AlertDescription } from "../ui/alert"; import { Button } from "../ui/button"; import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip"; @@ -139,6 +141,8 @@ import { pullRequestHandoffLabels, PULL_REQUEST_MERGE_METHOD_LABELS, checkoutFailureDescription, + mergeHeadPin, + seenPullRequestHead, readableFailure, resolvePullRequestReferenceHost, resolvePullRequestPrimaryControl, @@ -709,6 +713,20 @@ export function PullRequestDetailPanel({ nativeStackQuery.refresh(); }; const [refreshToken, setRefreshToken] = useState(0); + const seenHeadKey = `${environmentId}:${pullRequestKey}`; + const [storedSeenHead, setSeenHead] = useState | null>( + null, + ); + // A stored answer paints first, so only a settled read counts as shown. + const seenHead = seenPullRequestHead( + storedSeenHead, + seenHeadKey, + detailQuery.isPending ? undefined : detail?.headSha, + ); + if (seenHead !== storedSeenHead) setSeenHead(seenHead); + const shownHeadSha = seenHead.sha ?? detail?.headSha; + const unseenHeadSha = + detail?.state === "open" && detail.headSha !== shownHeadSha ? detail.headSha : undefined; const [activityRevision, setActivityRevision] = useState<{ readonly key: string; readonly updatedAt: string; @@ -867,6 +885,7 @@ export function PullRequestDetailPanel({ input: { ...reference, action, + ...mergeHeadPin(action, shownHeadSha), ...(method ? { mergeMethod: method } : {}), ...(updateMethod ? { updateMethod } : {}), }, @@ -884,6 +903,8 @@ export function PullRequestDetailPanel({ title: actionFailureLabels(changeRequestTermKind(terminology))[action], description: readableFailure(failure, hint), }); + // A refused merge usually means new commits, so show what the host has now. + if (action === "merge" || action === "enable-auto-merge") refreshDetail(); onActed?.(action, "failed"); return false; } @@ -1603,6 +1624,7 @@ export function PullRequestDetailPanel({ onRetry={nativeStackQuery.error ? nativeStackQuery.refresh : undefined} reference={reference} environmentId={environmentId} + shownHeadSha={shownHeadSha} onSelect={onSelectPullRequest} mergeMethod={selectedMergeMethod} stale={!nativeStackQuery.isFresh} @@ -1896,6 +1918,30 @@ export function PullRequestDetailPanel({ + {unseenHeadSha !== undefined && shownHeadSha !== undefined ? ( +
+ + + + {gt("New commits were pushed. A merge or review still applies to {sha}.", { + sha: shownHeadSha.slice(0, 7), + })} + + + + + +
+ ) : null} {detail ? ( , ); await screen.getByRole("button", { name: "Submit review" }).click(); @@ -52,7 +54,11 @@ it("submits only the line comments still in the draft when dictation finishes", await act(() => mocks.queue.mock.calls[0]![0]("Dictated summary")); expect(mocks.submit).toHaveBeenCalledWith( expect.objectContaining({ - input: expect.objectContaining({ body: "Dictated summary", comments: [] }), + input: expect.objectContaining({ + body: "Dictated summary", + comments: [], + expectedHeadSha: "reviewed-head", + }), }), ); }); diff --git a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx index d581c6c9e2f06..6cedcd7a1d492 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewForm.tsx @@ -63,6 +63,7 @@ export function PullRequestReviewForm({ environmentId, active, reference, + headSha, completionScope, term, verdicts, @@ -71,11 +72,14 @@ export function PullRequestReviewForm({ pending, onPendingChange, onSubmitted, + onRefused, }: { environmentId: EnvironmentId; /** False while the form stays mounted but hidden; dictation is cancelled then. */ active: boolean; reference: PullRequestRef; + /** The head on screen, which the review is pinned to. */ + headSha: string | undefined; completionScope: PullRequestCompletionScope | null; term: ChangeRequestTermKind; verdicts: ReadonlyArray; @@ -84,6 +88,7 @@ export function PullRequestReviewForm({ pending: boolean; onPendingChange: (pending: boolean) => void; onSubmitted: () => void; + onRefused: () => void; }) { const gt = useGT(); const resolve = useMessages(); @@ -125,6 +130,7 @@ export function PullRequestReviewForm({ environmentId, input: { ...reference, + ...(headSha === undefined ? {} : { expectedHeadSha: headSha }), verdict: verdict.value, body: submittedBody, comments: submittedComments, @@ -140,6 +146,7 @@ export function PullRequestReviewForm({ m(msg("The host refused the review. Your draft is still here to try again.")), ), }); + onRefused(); return; } // Preserve comments and summary edits made during submission. diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx index 2aed048ba9662..2d75923260bf5 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx @@ -3,17 +3,19 @@ import { EnvironmentId, ProjectId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; -const state = vi.hoisted(() => ({ detail: "" })); +const state = vi.hoisted(() => ({ detail: "", sent: [] as unknown[] })); vi.mock(import("~/state/use-atom-command"), async () => { const { PullRequestOperationError } = await import("@t3tools/contracts"); const { Cause } = await import("effect"); const { AsyncResult } = await import("effect/reactivity"); return { - useAtomCommand: (() => async () => - AsyncResult.failure( + useAtomCommand: (() => async (call: { readonly input: unknown }) => { + state.sent.push(call.input); + return AsyncResult.failure( Cause.fail(new PullRequestOperationError({ operation: "runAction", detail: state.detail })), - )) as never, + ); + }) as never, }; }); @@ -24,6 +26,7 @@ import { PullRequestStackMenu } from "./PullRequestStackMenu"; function setup(detail: string) { state.detail = detail; + state.sent = []; } const HEAD_MOVED = "The stack head moved. Refresh the stack before trying again."; @@ -58,6 +61,7 @@ it.each([ layers: [{ number: 2, headBranch: "feature", headSha: "abc123", state: "open" }], }} canMerge + shownHeadSha="shown" stale={false} canRebase mergeMethod="squash" @@ -73,4 +77,13 @@ it.each([ } await page.getByRole("dialog").getByRole("button", { name: row.label, exact: true }).click(); await expect.element(page.getByText(row.description, { exact: true })).toBeInTheDocument(); + // The stack's own read can be ahead of the head the reader was shown; a merge lands only that one. + expect(state.sent).toEqual([ + expect.objectContaining( + row.label === "Merge stack" + ? { expectedHeadSha: "shown", expectedStackHeads: [{ number: 2, headSha: "abc123" }] } + : { action: "update-branch" }, + ), + ]); + if (row.label !== "Merge stack") expect(state.sent[0]).not.toHaveProperty("expectedHeadSha"); }); diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx index e2300578f4b76..1a1eb33c42254 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx @@ -30,7 +30,7 @@ import { PullRequestStackLayers } from "./PullRequestStackLayers"; import { PullRequestStackHeader } from "./PullRequestStackHeader"; import { PullRequestStackLayerContent } from "./PullRequestStackLayerContent"; import { PullRequestGlyph } from "./pullRequestIcons"; -import { readableFailure } from "./pullRequestDetail.logic"; +import { mergeHeadPin, readableFailure } from "./pullRequestDetail.logic"; import { changeRequestTermKind } from "./changeRequestTerm"; @@ -40,6 +40,7 @@ export function PullRequestStackMenu({ stack, reference, environmentId, + shownHeadSha, stale, canMerge, canRebase, @@ -56,6 +57,8 @@ export function PullRequestStackMenu({ stack: PullRequestStack; reference: PullRequestRef; environmentId: EnvironmentId; + /** The head of `reference` the reader was shown; the stack read can run ahead of it. */ + shownHeadSha: string | undefined; stale: boolean; canMerge: boolean; canRebase: boolean; @@ -115,6 +118,7 @@ export function PullRequestStackMenu({ number: target.number, stackNumber: stack.number, expectedStackHeads: actionHeads, + ...mergeHeadPin(action, shownHeadSha), action, ...(action === "merge" ? { mergeMethod } : { updateMethod: "rebase" }), }, diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 3d0ae22b15017..a71bc0d2db367 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -60,6 +60,7 @@ import { pullRequestLinkSubject, writePullRequestDetailSnapshot, readableFailure, + seenPullRequestHead, } from "./pullRequestDetail.logic"; import type { ReviewCommentContext } from "~/reviewCommentContext"; @@ -2058,6 +2059,19 @@ describe("single-PR merge compatibility during stack discovery", () => { ); }); +describe("seenPullRequestHead", () => { + it("takes the first settled head and keeps it until another pull request is shown", () => { + // A stored answer paints before the read settles, and is not what the reader ends up seeing. + const loading = seenPullRequestHead(null, "pr-1", undefined); + expect(loading).toEqual({ key: "pr-1", sha: undefined }); + const seen = seenPullRequestHead(loading, "pr-1", "a"); + expect(seen).toEqual({ key: "pr-1", sha: "a" }); + expect(seenPullRequestHead(seen, "pr-1", "b")).toBe(seen); + expect(seenPullRequestHead(seen, "pr-1", undefined)).toBe(seen); + expect(seenPullRequestHead(seen, "pr-2", "c")).toEqual({ key: "pr-2", sha: "c" }); + }); +}); + describe("readableFailure", () => { it("replaces a host tool's bare failure with the hint, for every host", () => { for (const message of [ diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index d98ec3ff114ec..ad9285f6fc322 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -1543,6 +1543,27 @@ const TOOL_NOISE = [ const FAILURE_DETAIL_MAX_LENGTH = 320; +/** + * The head a reader was first shown. A background refresh does not move it, so a merge or review + * keeps applying to the commits they read until they load the newer ones. + */ +export function seenPullRequestHead( + seen: { readonly key: string; readonly sha: string | undefined } | null, + key: string, + settledHead: string | undefined, +) { + return seen !== null && seen.key === key && (seen.sha !== undefined || settledHead === undefined) + ? seen + : { key, sha: settledHead }; +} + +/** A merge lands the head the reader was shown, so it refuses a head that moved since. */ +export function mergeHeadPin(action: PullRequestAction, headSha: string | undefined) { + return (action === "merge" || action === "enable-auto-merge") && headSha !== undefined + ? { expectedHeadSha: headSha } + : {}; +} + export function readableFailure(failure: unknown, hint: string): string { const raw = failure instanceof Error ? failure.message : typeof failure === "string" ? failure : ""; diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx index 79089c0a858c6..4b62dd0ae3266 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx @@ -35,6 +35,7 @@ function MergeButton({ reference }: { reference: PullRequestRef }) { const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId: EnvironmentId.make("environment"), reference, + headSha: `head-${reference.number}`, terminology: sourceControlClients.get(undefined).changeRequest, }); return ( @@ -81,6 +82,11 @@ it("keeps pending merges with their pull request when navigating between threads await expect.element(button).toBeEnabled(); await userEvent.click(button); expect(state.runAction).toHaveBeenCalledTimes(2); + // Each merge is pinned to the head its own row showed. + expect(state.runAction.mock.calls.map(([call]) => call.input.expectedHeadSha)).toEqual([ + "head-1", + "head-2", + ]); await screen.rerender(); await expect.element(button).toHaveTextContent("Merging..."); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index f7885e098d3c3..3c016af497c0f 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -44,6 +44,7 @@ import { offHeadPullRequestCheckoutToast } from "./pullRequestCheckoutToast"; import { checkoutFailureDescription, appendHandoff, + mergeHeadPin, readableFailure, } from "./pullRequestDetail.logic"; import { pullRequestEntryKey, type EnvironmentPullRequestEntry } from "./pullRequestList.logic"; @@ -187,12 +188,17 @@ const actionFailureHints = (term: ChangeRequestTermKind): Record void; terminology: ChangeRequestTerminology; onSuccess?: (action: PullRequestAction, reply: PullRequestSummary | undefined) => void; /** Resolve repository settings on click to avoid per-row reads. */ @@ -227,6 +233,7 @@ export function usePullRequestActionRunner({ input: { ...reference, action, + ...mergeHeadPin(action, headSha), ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}), }, }); @@ -241,6 +248,7 @@ export function usePullRequestActionRunner({ actionFailureHints(changeRequestTermKind(terminology))[action], ), }); + onFailure?.(action); return; } toastManager.add({ diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 3fe4a8bfabb00..761473fabb358 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -6836,6 +6836,8 @@ "45674081908ac8aa": "Checkout-Befehl kopiert", "d2970574ef7860d0": "{term, select, mr {Branch des Merge Requests kopieren} cr {Branch der Änderungsanfrage kopieren} other {Branch des Pull Requests kopieren}}", "45c92416a82cf22c": "Branch-Name kopiert", + "43a18c0bc37988f4": "Neue Commits wurden gepusht. Ein Merge oder Review gilt weiterhin für {sha}.", + "c930a7ffa49054f0": "Neue Commits laden", "63e533a9db74e8dc": "Checks", "4f7ca990d538a8bc": "Kommentare nicht verfügbar", "95601ce075194611": "{count, plural, one {{formatted} Kommentar} other {{formatted} Kommentare}}", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index f03dc33bf1fb8..2764010f88414 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -6843,6 +6843,8 @@ "45674081908ac8aa": "Checkout command copied", "d2970574ef7860d0": "Copy {term, select, mr {merge request} cr {change request} other {pull request}} branch", "45c92416a82cf22c": "Branch name copied", + "43a18c0bc37988f4": "New commits were pushed. A merge or review still applies to {sha}.", + "c930a7ffa49054f0": "Load new commits", "63e533a9db74e8dc": "Checks", "4f7ca990d538a8bc": "Comments unavailable", "95601ce075194611": "{count, plural, one {{formatted} comment} other {{formatted} comments}}", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index a701345663865..f7bd7ecb09588 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -6836,6 +6836,8 @@ "45674081908ac8aa": "Comando de checkout copiado", "d2970574ef7860d0": "Copiar la rama de la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}", "45c92416a82cf22c": "Nombre de la rama copiado", + "43a18c0bc37988f4": "Se enviaron nuevos commits. Una fusión o revisión sigue aplicándose a {sha}.", + "c930a7ffa49054f0": "Cargar nuevos commits", "63e533a9db74e8dc": "Comprobaciones", "4f7ca990d538a8bc": "Comentarios no disponibles", "95601ce075194611": "{count, plural, one {{formatted} comentario} other {{formatted} comentarios}}", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index df68cc6cb7438..209553a0cda86 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -6837,6 +6837,8 @@ "45674081908ac8aa": "Commande de checkout copiée", "d2970574ef7860d0": "Copier la branche de la {term, select, mr {merge request} cr {demande de modification} other {pull request}}", "45c92416a82cf22c": "Nom de la branche copié", + "43a18c0bc37988f4": "De nouveaux commits ont été poussés. Une fusion ou une revue s’applique toujours à {sha}.", + "c930a7ffa49054f0": "Charger les nouveaux commits", "63e533a9db74e8dc": "Vérifications", "4f7ca990d538a8bc": "Commentaires indisponibles", "95601ce075194611": "{count, plural, one {{formatted} commentaire} other {{formatted} commentaires}}", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 3752913600c78..c9e97b9e3f263 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -6806,6 +6806,8 @@ "45674081908ac8aa": "チェックアウトコマンドをコピーしました", "d2970574ef7860d0": "{term, select, mr {マージリクエストのブランチをコピー} cr {変更リクエストのブランチをコピー} other {プルリクエストのブランチをコピー}}", "45c92416a82cf22c": "ブランチ名をコピーしました", + "43a18c0bc37988f4": "新しいコミットがプッシュされました。マージやレビューは引き続き {sha} に適用されます。", + "c930a7ffa49054f0": "新しいコミットを読み込む", "63e533a9db74e8dc": "チェック", "4f7ca990d538a8bc": "コメントを利用できません", "95601ce075194611": "{count, plural, other {{formatted} 件のコメント}}", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index c327226d81e4c..7d528f7527d27 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -6810,6 +6810,8 @@ "45674081908ac8aa": "체크아웃 명령 복사됨", "d2970574ef7860d0": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} 브랜치 복사", "45c92416a82cf22c": "브랜치 이름 복사됨", + "43a18c0bc37988f4": "새 커밋이 푸시되었습니다. 병합이나 리뷰는 여전히 {sha}에 적용됩니다.", + "c930a7ffa49054f0": "새 커밋 불러오기", "63e533a9db74e8dc": "검사", "4f7ca990d538a8bc": "댓글을 사용할 수 없음", "95601ce075194611": "{count, plural, other {댓글 {formatted}개}}", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 36d5130814b0a..33e0262600d4a 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -6836,6 +6836,8 @@ "45674081908ac8aa": "Comando de checkout copiado", "d2970574ef7860d0": "Copiar o branch {term, select, mr {do merge request} cr {da solicitação de alteração} other {do pull request}}", "45c92416a82cf22c": "Nome do branch copiado", + "43a18c0bc37988f4": "Novos commits foram enviados. Um merge ou uma revisão ainda se aplica a {sha}.", + "c930a7ffa49054f0": "Carregar novos commits", "63e533a9db74e8dc": "Verificações", "4f7ca990d538a8bc": "Comentários indisponíveis", "95601ce075194611": "{count, plural, one {{formatted} comentário} other {{formatted} comentários}}", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 34d4295aa74d4..a93a2ce219ea2 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -6836,6 +6836,8 @@ "45674081908ac8aa": "Команда checkout скопирована", "d2970574ef7860d0": "{term, select, mr {Копировать ветку мерж-реквеста} cr {Копировать ветку запроса на изменение} other {Копировать ветку пул-реквеста}}", "45c92416a82cf22c": "Имя ветки скопировано", + "43a18c0bc37988f4": "Отправлены новые коммиты. Слияние или ревью по-прежнему относится к {sha}.", + "c930a7ffa49054f0": "Загрузить новые коммиты", "63e533a9db74e8dc": "Проверки", "4f7ca990d538a8bc": "Комментарии недоступны", "95601ce075194611": "{count, plural, one {{formatted} комментарий} few {{formatted} комментария} many {{formatted} комментариев} other {{formatted} комментария}}", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 8b26904ba4a54..2b15a6570f9ab 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -6842,6 +6842,8 @@ "45674081908ac8aa": "Utcheckningskommandot kopierades", "d2970574ef7860d0": "Kopiera grenen för {term, select, mr {merge requesten} cr {ändringsbegäran} other {pull requesten}}", "45c92416a82cf22c": "Grennamnet kopierades", + "43a18c0bc37988f4": "Nya commits har pushats. En merge eller granskning gäller fortfarande {sha}.", + "c930a7ffa49054f0": "Läs in nya commits", "63e533a9db74e8dc": "Kontroller", "4f7ca990d538a8bc": "Kommentarer är inte tillgängliga", "95601ce075194611": "{count, plural, one {{formatted} kommentar} other {{formatted} kommentarer}}", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cc9e902308327..fc0cbe1297c4f 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -6849,6 +6849,8 @@ "45674081908ac8aa": "已复制检出工作副本的命令", "d2970574ef7860d0": "复制 {term, select, mr {MR} cr {change request} other {PR}} 分支", "45c92416a82cf22c": "已复制分支名称", + "43a18c0bc37988f4": "有新的提交被推送。合并或评审仍针对 {sha}。", + "c930a7ffa49054f0": "加载新提交", "63e533a9db74e8dc": "检查", "4f7ca990d538a8bc": "评论不可用", "95601ce075194611": "{count, plural, other {{formatted} 条评论}}", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 16d8c34547a17..b014ba3357d43 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -234,6 +234,11 @@ Where you can edit a description, you can also tick its checkboxes from the Summ (the Overview tab on mobile). GitLab calls these merge requests. +A merge or review applies to the commits you opened the pull request on. When someone pushes +meanwhile, the web and desktop apps offer **Load new commits**; until you do, a merge or review is refused and your +review draft is kept. Merging from a thread's pull request row, or from the list, lands the head that +row had when you confirmed. + Save a filter setup with **Views → Save current view** on the Pull Requests page. For example, choose **Reviewing** (**Your review** on mobile) and save it as "PRs Requesting My Review". Choose a saved view to restore its search, filters, sort order, and server/project scope. After changing filters, use **Update saved view** to diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts index daa8f041a2e1f..3044463eb0e2b 100644 --- a/packages/client-runtime/src/state/pullRequests.test.ts +++ b/packages/client-runtime/src/state/pullRequests.test.ts @@ -1064,6 +1064,39 @@ it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)( }), ); +it.effect("pins a quick merge to the head it judged mergeable unless the caller showed one", () => + Effect.gen(function* () { + const pinned: Array = []; + const client = { + [WS_METHODS.pullRequestsDetail]: () => + Effect.succeed({ + state: "open", + isDraft: false, + headSha: "checked-head", + capabilities: { actions: ["merge"] }, + viewerPermissions: { actions: ["merge"] }, + }), + [WS_METHODS.pullRequestsRunAction]: (input: { expectedHeadSha?: string }) => + Effect.sync(() => void pinned.push(input.expectedHeadSha)), + } as unknown as WsRpcProtocolClient; + const { atoms, registry } = yield* makeTestRuntime(client); + const input = { + projectId: ProjectId.make("project-1"), + repository: "acme/web", + number: 1, + action: "merge" as const, + resolveMergeMethod: () => "squash" as const, + }; + for (const shown of [{}, { expectedHeadSha: "shown-head" }]) { + yield* atoms.runAction.run(registry, { + environmentId: TARGET.environmentId, + input: { ...input, ...shown }, + }); + } + expect(pinned).toEqual(["checked-head", "shown-head"]); + }), +); + it.effect("keeps a close batch ordered and continues after a refused close", () => Effect.gen(function* () { const calls: number[] = []; diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.ts index 6ca8705a5735a..01fb80d817645 100644 --- a/packages/client-runtime/src/state/pullRequests.ts +++ b/packages/client-runtime/src/state/pullRequests.ts @@ -1132,7 +1132,14 @@ export function createPullRequestEnvironmentAtoms( detail: cause instanceof Error ? cause.message : "Could not choose a merge method.", }), }); - preparedInput = { ...actionInput, mergeMethod }; + // Without a head the caller showed, pin to the one this read judged mergeable. + preparedInput = { + ...actionInput, + mergeMethod, + ...(actionInput.expectedHeadSha === undefined && detail.headSha !== undefined + ? { expectedHeadSha: detail.headSha } + : {}), + }; } return yield* routedRequest(WS_METHODS.pullRequestsRunAction, { ...preparedInput, diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 0771055de4de4..3318ae3cdcb58 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -916,6 +916,8 @@ export type PullRequestReviewCommentDraft = typeof PullRequestReviewCommentDraft export const PullRequestSubmitReviewInput = Schema.Struct({ ...PullRequestRef.fields, + /** Reviews refuse when the head commit is no longer this one. */ + expectedHeadSha: Schema.optional(TrimmedNonEmptyString), verdict: PullRequestReviewVerdict, body: Schema.String.check(Schema.isMaxLength(65_536)), comments: Schema.Array(PullRequestReviewCommentDraft), diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index fffa0feb4014b..ec6ae07b5d5d6 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -615,6 +615,8 @@ export interface PullRequestProviderApi { readonly verdict: PullRequestReviewVerdict; readonly body: string; readonly comments: ReadonlyArray; + /** Hosts that can pin a review to a head commit do; the caller has already checked it. */ + readonly expectedHeadSha?: string; }, ) => Effect.Effect; diff --git a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts index e6c8a47a922ee..ae96a89eb805b 100644 --- a/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts @@ -622,7 +622,7 @@ export const make = Effect.gen(function* () { ? "REQUEST_CHANGES" : "COMMENT", body: input.body, - commit_id: pr.head.sha, + commit_id: input.expectedHeadSha ?? pr.head.sha, comments: input.comments.map((comment) => { const position = comment.position; const old = diff --git a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts index 37108af262b7a..5dbc797ff4386 100644 --- a/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts +++ b/packages/source-control-gitcafe/src/server/GitCafePullRequestProvider.ts @@ -1349,7 +1349,7 @@ export const make = Effect.gen(function* () { body: { verdict: input.verdict === "request-changes" ? "request_changes" : input.verdict, ...(input.body.length === 0 ? {} : { body: input.body }), - commitOid: pull.headOid, + commitOid: input.expectedHeadSha ?? pull.headOid, expectedVersion: pull.version, requestId: yield* randomUuidV4, }, diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 0f6b76dd5040c..0ae73bcde3891 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -811,6 +811,7 @@ export class GitHubPullRequestApi extends Context.Service< readonly verdict: PullRequestReviewVerdict; readonly body: string; readonly comments: ReadonlyArray; + readonly expectedHeadSha?: string; }) => Effect.Effect; readonly replyToReviewThread: (input: { @@ -3119,6 +3120,7 @@ export const make = Effect.gen(function* () { verdict: input.verdict, body: input.body, comments: input.comments, + expectedHeadSha: input.expectedHeadSha, }), }) .pipe(Effect.asVoid); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index e049943a3978f..cd26dcf2d4a5b 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -1644,6 +1644,7 @@ describe("review submission payload", () => { const payload = buildReviewSubmission({ verdict: "request-changes", body: "Two things.", + expectedHeadSha: "0a1b2c3d4e5f", comments: [ { path: "src/a.ts", @@ -1658,6 +1659,7 @@ describe("review submission payload", () => { ], }); expect(payload).toEqual({ + commit_id: "0a1b2c3d4e5f", event: "REQUEST_CHANGES", body: "Two things.", comments: [ diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 9eed567a6a4da..08ba8fd8b241f 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -285,6 +285,8 @@ export function isSubjectOfPullRequest(result: PullRequestSubject.Result): boole } const ReviewSubmissionSchema = Schema.Struct({ + /** Without it GitHub records the review against whatever the head is when it arrives. */ + commit_id: Schema.optional(Schema.String), event: Schema.Literals(["COMMENT", "APPROVE", "REQUEST_CHANGES"]), body: Schema.String, comments: Schema.Array( @@ -325,8 +327,10 @@ export function buildReviewSubmission(input: { readonly verdict: PullRequestReviewVerdict; readonly body: string; readonly comments: ReadonlyArray; + readonly expectedHeadSha?: string | undefined; }): typeof ReviewSubmissionSchema.Type { return { + ...(input.expectedHeadSha === undefined ? {} : { commit_id: input.expectedHeadSha }), event: REVIEW_EVENTS[input.verdict], body: input.body, comments: input.comments.map((comment) => { From 46f360d8dde801b78e9788c2ea3084bdc7b933a0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:12:07 -0800 Subject: [PATCH 100/221] fix(client): a link to a newly linked machine's thread opens without a reload (#41722) --- .../src/features/threads/ThreadFeed.tsx | 22 +++++- apps/mobile/src/state/linkedThread.ts | 16 ++-- apps/mobile/src/state/peerLinks.ts | 27 +++++-- .../src/components/chat/LinkedThreadPage.tsx | 4 +- .../components/chat/MarkdownThreadLink.tsx | 1 + apps/web/src/state/linkedThreadView.ts | 5 +- apps/web/src/state/peerLinks.ts | 13 +++- .../src/state/peerLinks.test.ts | 76 +++++++++++++++++++ .../client-runtime/src/state/peerLinks.ts | 17 +++++ 9 files changed, 160 insertions(+), 21 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index e2d5c141a479d..c24b70c575139 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -84,7 +84,12 @@ import { } from "@t3tools/contracts"; import type { ToolCallVisibility } from "@t3tools/contracts/settings"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; -import { hasThreadLinks, hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks"; +import { + hasThreadLinks, + hostedThreadLink, + parseThreadLinkHref, + threadLinkRefs, +} from "@t3tools/shared/threadLinks"; import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks"; import { parseComposerContextHref, @@ -339,6 +344,11 @@ import { } from "./threadFeedEndFollow"; import { useMessageTimeFormatter } from "./useMessageTimeFormatter"; +const linkedThreadEnvironmentIds = (markdown: string, environmentId: EnvironmentId) => + hasThreadLinks(markdown) + ? threadLinkRefs(markdown, environmentId).map((ref) => ref.environmentId) + : []; + const WIDE_MARKDOWN_BLOCK_OPTIONS = { // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width. includeBlockquotes: Platform.OS === "ios", @@ -1311,7 +1321,10 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { const liveMarkdown = useLiveThreadLinkLabels( props.markdown, props.environmentId, - useLinkedEnvironments(hasThreadLinks(props.markdown) ? props.environmentId : null), + useLinkedEnvironments( + hasThreadLinks(props.markdown) ? props.environmentId : null, + linkedThreadEnvironmentIds(props.markdown, props.environmentId), + ), ); const [quoteSelection, setQuoteSelection] = useState<{ markdown: string; @@ -2746,7 +2759,10 @@ function UserMessageContent(props: UserMessageContentProps) { const liveText = useLiveThreadLinkLabels( props.text, props.environmentId, - useLinkedEnvironments(hasThreadLinks(props.text) ? props.environmentId : null), + useLinkedEnvironments( + hasThreadLinks(props.text) ? props.environmentId : null, + linkedThreadEnvironmentIds(props.text, props.environmentId), + ), ); const threadIcons = useThreadChipIcons(props.environmentId, liveText, props.context?.records); const text = replaceComposerContextReferences(liveText, (ref) => { diff --git a/apps/mobile/src/state/linkedThread.ts b/apps/mobile/src/state/linkedThread.ts index ff4c75b9ac1ac..8a0adc790940e 100644 --- a/apps/mobile/src/state/linkedThread.ts +++ b/apps/mobile/src/state/linkedThread.ts @@ -27,16 +27,14 @@ export function useLinkedThreadReach( const own = presentationById.get(id); return own && { connected: own.connection.phase === "connected" }; }; - const links = useLinkedEnvironments( - subagents.some( - (subagent) => - subagent.childThreadId === null && - subagent.remoteChild !== undefined && - ownConnection(subagent.remoteChild.environmentId)?.connected !== true, - ) - ? environmentId - : null, + const remote = subagents.flatMap((subagent) => + subagent.childThreadId === null && + subagent.remoteChild !== undefined && + ownConnection(subagent.remoteChild.environmentId)?.connected !== true + ? [subagent.remoteChild.environmentId] + : [], ); + const links = useLinkedEnvironments(remote.length > 0 ? environmentId : null, remote); return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) }; } diff --git a/apps/mobile/src/state/peerLinks.ts b/apps/mobile/src/state/peerLinks.ts index 40a13f2150234..ae403a4e72068 100644 --- a/apps/mobile/src/state/peerLinks.ts +++ b/apps/mobile/src/state/peerLinks.ts @@ -1,4 +1,4 @@ -import { useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { linkableMachines, linkedEnvironmentNames, @@ -6,7 +6,7 @@ import { } from "@t3tools/client-runtime/link-request"; import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks"; import type { EnvironmentId } from "@t3tools/contracts"; -import { useEffect, useEffectEvent, useMemo } from "react"; +import { useContext, useEffect, useEffectEvent, useMemo } from "react"; import { connectionAtomRuntime } from "../connection/runtime"; import { useEnvironments } from "./environments"; @@ -19,19 +19,36 @@ export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtom /** * The machines `environmentId` links to, by name, while it offers links, and none otherwise. * Its agents can read threads there, and so can a client allowed to read threads on it. + * A `wanted` machine this app is not connected to and the names lack makes them reread. */ export function useLinkedEnvironments( environmentId: EnvironmentId | null, + wanted: ReadonlyArray = [], ): ReadonlyMap { const { environments } = useEnvironments(); const offered = offersLinkedEnvironments( environments.find((environment) => environment.environmentId === environmentId)?.serverConfig, ); + const queried = offered ? environmentId : null; const links = useEnvironmentQuery( - offered && environmentId !== null - ? peerLinkEnvironment.names({ environmentId, input: {} }) - : null, + queried === null ? null : peerLinkEnvironment.names({ environmentId: queried, input: {} }), ); + const connected = new Set( + environments + .filter((environment) => environment.connection.phase === "connected") + .map((environment) => environment.environmentId), + ); + const missing = [...new Set(wanted)].filter((id) => id !== environmentId && !connected.has(id)); + const refreshKey = + queried === null || missing.length === 0 ? "" : [queried, ...[...missing].sort()].join(" "); + const registry = useContext(RegistryContext); + const refreshLacking = useEffectEvent(() => { + if (queried !== null) peerLinkEnvironment.refreshNamesLacking(registry, queried, missing); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links made outside this app are not pushed, so meeting an unknown machine asks the server again + useEffect(() => { + if (refreshKey !== "") refreshLacking(); + }, [refreshKey]); return useMemo( () => linkedEnvironmentNames({ links: offered ? (links.data?.links ?? []) : [], environments }), [environments, links.data, offered], diff --git a/apps/web/src/components/chat/LinkedThreadPage.tsx b/apps/web/src/components/chat/LinkedThreadPage.tsx index 08d216a212650..0749f199083ee 100644 --- a/apps/web/src/components/chat/LinkedThreadPage.tsx +++ b/apps/web/src/components/chat/LinkedThreadPage.tsx @@ -26,7 +26,9 @@ export function LinkedThreadPage(props: { const gt = useGT(); const own = useEnvironment(environmentId); const connected = own?.connection.phase === "connected"; - const linkedLabel = useLinkedEnvironments(connected ? null : viaEnvironmentId).get(environmentId); + const linkedLabel = useLinkedEnvironments(connected ? null : viaEnvironmentId, environmentId).get( + environmentId, + ); if (connected) { return ( { const offered = useAtomValue( environmentId === null ? offersNoLinksAtom : offersLinkedEnvironmentsAtom(environmentId), @@ -56,6 +58,13 @@ export function useLinkedEnvironments( ? peerLinkEnvironment.names({ environmentId, input: {} }) : null, ); + const registry = useContext(RegistryContext); + const queried = offered ? environmentId : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links made outside this client are not pushed, so meeting an unknown machine asks the server again + useEffect(() => { + if (queried === null || wanted === undefined) return; + peerLinkEnvironment.refreshNamesLacking(registry, queried, [wanted]); + }, [registry, queried, wanted]); return linkedEnvironmentNames({ links: offered ? (links.data?.links ?? []) : [], environments: identities, diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index dd39162df8a4c..ce4d267aaef18 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -18,9 +18,16 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { TestClock } from "effect/testing"; +import { + AVAILABLE_CONNECTION_STATE, + PrimaryConnectionTarget, + type PreparedConnection, + type SupervisorConnectionState, +} from "../connection/model.ts"; import { EnvironmentRegistry } from "../connection/registry.ts"; import { EnvironmentSupervisor } from "../connection/supervisor.ts"; import type { LinkedThreadView } from "../linkedThread.ts"; +import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type { RpcSession } from "../rpc/session.ts"; import { v2MessageRow, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts"; @@ -191,3 +198,72 @@ describe("linkThroughRoutes", () => { ]); }); }); + +describe("refreshNamesLacking", () => { + // regression: #41707 a link made outside this client stayed unknown while the names were read + it.effect("rereads fresh names that lack a wanted machine, once per miss", () => + Effect.gen(function* () { + const target = new PrimaryConnectionTarget({ + environmentId: id("via"), + label: "Via", + httpBaseUrl: "https://via.example.test", + wsBaseUrl: "wss://via.example.test", + }); + let stored = [{ environmentId: id("known"), label: "Known" }]; + let reads = 0; + const client = { + [WS_METHODS.peerLinksNames]: () => + Effect.sync(() => { + reads += 1; + return { links: stored }; + }), + } as unknown as WsRpcProtocolClient; + const session = { client } as unknown as RpcSession; + const supervisor = EnvironmentSupervisor.of({ + target, + state: yield* SubscriptionRef.make({ + ...AVAILABLE_CONNECTION_STATE, + phase: "connected", + }), + session: yield* SubscriptionRef.make(Option.some(session)), + prepared: yield* SubscriptionRef.make(Option.none()), + } as unknown as EnvironmentSupervisor["Service"]); + const environment = EnvironmentRegistry.of({ + run: (_id, effect) => Effect.provideService(effect, EnvironmentSupervisor, supervisor), + followStream: (_id, stream) => + Stream.provideService(stream, EnvironmentSupervisor, supervisor), + } as EnvironmentRegistry["Service"]); + const links = createPeerLinkEnvironmentAtoms( + Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)), + ); + const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) => + Effect.sync(() => registry.dispose()), + ); + const names = links.names({ environmentId: target.environmentId, input: {} }); + registry.mount(names); + const settled = () => + AtomRegistry.toStream(registry, names).pipe( + Stream.filter((result) => AsyncResult.isSuccess(result) && !result.waiting), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + yield* settled(); + expect(reads).toBe(1); + + links.refreshNamesLacking(registry, target.environmentId, [id("known")]); + expect(reads).toBe(1); + + // Linked from the CLI or another client inside the names' stale time: the server has it, + // this client was not told. + stored = [...stored, { environmentId: id("new"), label: "New" }]; + links.refreshNamesLacking(registry, target.environmentId, [id("new")]); + // A second reader meeting the same machine joins the read under way. + links.refreshNamesLacking(registry, target.environmentId, [id("new")]); + const reread = yield* settled(); + expect(reads).toBe(2); + expect( + AsyncResult.isSuccess(reread) && reread.value.links.map((link) => link.environmentId), + ).toEqual([id("known"), id("new")]); + }).pipe(Effect.scoped), + ); +}); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index a7af1ac15b4c9..3be676d3e5dc2 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -101,6 +101,23 @@ export function createPeerLinkEnvironmentAtoms( return { list, names, + /** + * Rereads `environmentId`'s link names when they lack one of `wanted`, however fresh they + * are. Links made elsewhere (the CLI, another client, a batch) are not pushed, so a reader + * that meets a machine the names lack asks once more; a read under way already answers it. + */ + refreshNamesLacking: ( + registry: AtomRegistry.AtomRegistry, + environmentId: EnvironmentId, + wanted: ReadonlyArray, + ) => { + const atom = names({ environmentId, input: {} }); + const result = registry.get(atom); + if (!AsyncResult.isSuccess(result) || result.waiting) return; + const known = new Set(result.value.links.map((link) => link.environmentId)); + if (wanted.every((id) => known.has(id))) return; + registry.refresh(atom); + }, link: createEnvironmentRpcCommand(runtime, { label: "environment-data:peer-links:link", tag: WS_METHODS.peerLinksLink, From eecb58c6d60cbf168b4402c47896374555b2dc6d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:12:40 -0800 Subject: [PATCH 101/221] fix: approvals and hosted pairing show what is being approved (#41769) Co-authored-by: Claude Fable 5.2 --- .../Adapters/CodexAdapterV2.test.ts | 114 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 91 +++++++++++--- apps/server/src/serverSettings.test.ts | 4 + apps/server/src/serverSettings.ts | 6 +- apps/web/src/components/ChatView.tsx | 9 +- .../auth/PairingRouteSurface.browser.test.tsx | 36 ++++++ .../components/auth/PairingRouteSurface.tsx | 67 ++++++---- apps/web/src/components/chat/ChatComposer.tsx | 7 +- .../components/chat/runtimeModeConfig.test.ts | 33 +++++ .../src/components/chat/runtimeModeConfig.ts | 25 ++++ apps/web/src/i18n/translations/de.json | 6 +- apps/web/src/i18n/translations/en.json | 6 +- apps/web/src/i18n/translations/es.json | 6 +- apps/web/src/i18n/translations/fr.json | 6 +- apps/web/src/i18n/translations/ja.json | 6 +- apps/web/src/i18n/translations/ko.json | 6 +- apps/web/src/i18n/translations/pt-BR.json | 6 +- apps/web/src/i18n/translations/ru.json | 6 +- apps/web/src/i18n/translations/sv.json | 6 +- apps/web/src/i18n/translations/zh.json | 6 +- docs/user/remote-access.md | 3 +- 21 files changed, 399 insertions(+), 56 deletions(-) create mode 100644 apps/web/src/components/auth/PairingRouteSurface.browser.test.tsx create mode 100644 apps/web/src/components/chat/runtimeModeConfig.test.ts diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index a07c3d6fe47c6..390d1f334739e 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -13151,6 +13151,120 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("shows what an approval grants apart from the reason the model gave", () => + Effect.gen(function* () { + const reason = "Needed to build the project."; + const permissions = { + fileSystem: { + write: ["/w/out"], + entries: [ + { access: "write", path: { type: "path", path: "/w/out" } }, + { access: "write", path: { type: "special", value: { kind: "root" } } }, + { access: "read", path: { type: "glob_pattern", pattern: "/w/docs/**/*.md" } }, + { access: "write", path: { type: "special", value: { kind: "unknown", path: "" } } }, + ], + }, + network: { enabled: true }, + } satisfies CodexSchema.PermissionsRequestApprovalParams["permissions"]; + const request = ( + id: number, + method: string, + params: Record, + result: Record, + ): Array => [ + { + type: "emit_inbound", + label: method, + frame: { + id, + method, + params: { threadId: nativeThreadId, turnId: nativeTurnId, startedAtMs: 2, ...params }, + }, + }, + { type: "expect_outbound", label: method, frame: { id, result } }, + ]; + const manyFiles = Array.from({ length: 21 }, (_, index) => ({ + ...addA, + path: `/w/${String(index).padStart(2, "0")}.ts`, + })); + const { harness, answerNext } = yield* startApprovalTurn("approval-scope", [ + ...request( + 0, + "item/permissions/requestApproval", + { itemId: "permissions", cwd: "/w", reason, permissions }, + { permissions, scope: "turn" }, + ), + ...request( + 1, + "item/commandExecution/requestApproval", + { + itemId: "command", + cwd: "/w/app", + reason, + command: "pnpm install", + networkApprovalContext: { host: "example.com", protocol: "https" }, + }, + { decision: "accept" }, + ), + fileChange("started", nativeTurnId, "patch", manyFiles), + ...request( + 2, + "item/fileChange/requestApproval", + { itemId: "patch", reason, grantRoot: "/w" }, + { decision: "accept" }, + ), + fileChange("completed", nativeTurnId, "patch", manyFiles), + ...request( + 3, + "execCommandApproval", + { + callId: "legacy", + conversationId: nativeThreadId, + command: ["pnpm", "run", "build"], + cwd: "/w/app", + parsedCmd: [], + reason, + }, + { decision: "approved" }, + ), + turnCompleted(nativeTurnId), + ]); + const requests = [ + yield* answerNext, + yield* answerNext, + yield* answerNext, + yield* answerNext, + ]; + yield* harness.firstTerminal; + + assert.deepEqual( + requests.map((pending) => { + const item = approvalItem(harness.events, pending); + return [item?.prompt, item?.reason]; + }), + [ + [ + "write /w/out\nwrite / (entire filesystem)\nread /w/docs/**/*.md\nwrite unknown path\nnetwork", + reason, + ], + ["pnpm install\ncwd /w/app\nnetwork https example.com", reason], + [[...manyFiles.map((file) => `add ${file.path}`), "write /w"].join("\n"), reason], + ["pnpm run build\ncwd /w/app", reason], + ], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("classifies permission requests that only list sandbox entries", () => Effect.gen(function* () { const permissionRequest = ( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 6ec6d44ef0b6b..c7a7343d515fe 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -209,25 +209,74 @@ function codexMultiFilePatch( .join(""); } +// The prompt states the operation being approved; Codex's `reason` goes to the item's `reason`. function codexFileChangeApprovalPrompt(input: { - readonly reason?: string | null; readonly grantRoot?: string | null; readonly fileChanges?: CodexFileChangeKinds; }): string | undefined { - const reason = input.reason?.trim(); - if (reason) return reason; const entries = Object.entries(input.fileChanges ?? {}).toSorted(([left], [right]) => left.localeCompare(right), ); - if (entries.length > 0) { - const described = entries.slice(0, 20).map(([path, change]) => { - const movePath = change.type === "update" ? change.move_path : undefined; - return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; - }); - const remaining = entries.length - described.length; - return remaining > 0 ? `${described.join("\n")}\n+${remaining} more` : described.join("\n"); + // The card scrolls, so every path is listed. + const described = entries.map(([path, change]) => { + const movePath = change.type === "update" ? change.move_path : undefined; + return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; + }); + const grantRoot = input.grantRoot?.trim(); + return [...described, ...(grantRoot ? [`write ${grantRoot}`] : [])].join("\n") || undefined; +} + +function codexCommandApprovalPrompt( + input: Pick< + CodexSchema.CommandExecutionRequestApprovalParams, + "command" | "cwd" | "networkApprovalContext" + >, +): string | undefined { + const network = input.networkApprovalContext; + return ( + [ + ...(input.command?.trim() ? [input.command] : []), + ...(input.cwd?.trim() ? [`cwd ${input.cwd}`] : []), + ...(network ? [`network ${network.protocol} ${network.host}`] : []), + ].join("\n") || undefined + ); +} + +function codexFileSystemPathLabel( + path: CodexSchema.PermissionsRequestApprovalParams__FileSystemPath, +): string { + if (path.type === "path") return path.path; + if (path.type === "glob_pattern") return path.pattern; + const special = path.value; + switch (special.kind) { + case "root": + return "/ (entire filesystem)"; + case "slash_tmp": + return "/tmp"; + case "tmpdir": + return "temporary directory"; + case "minimal": + return "minimal system paths"; + case "project_roots": + return ["project roots", special.subpath].filter(Boolean).join("/"); + case "unknown": + return [special.path, special.subpath].filter(Boolean).join("/") || "unknown path"; } - return input.grantRoot?.trim() || undefined; +} + +function codexPermissionsApprovalPrompt( + permissions: CodexSchema.PermissionsRequestApprovalParams["permissions"], +): string | undefined { + // Codex may list a path both in the legacy `read`/`write` lists and in `entries`. + const lines = new Set(); + for (const access of ["read", "write"] as const) { + for (const path of permissions.fileSystem?.[access] ?? []) lines.add(`${access} ${path}`); + } + for (const entry of permissions.fileSystem?.entries ?? []) { + lines.add(`${entry.access} ${codexFileSystemPathLabel(entry.path)}`); + } + if (permissions.network?.enabled) lines.add("network"); + return [...lines].join("\n") || undefined; } export function normalizeCodexThreadLoadModelSelection(selection: ModelSelection): ModelSelection { @@ -4852,10 +4901,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readonly nativeRequestId: string; readonly requestKind: ProviderRequestKind; readonly prompt?: string | null; + readonly reason?: string | null | undefined; readonly appName?: string; readonly options?: ReadonlyArray; }) { const createdAt = yield* DateTime.now; + const reason = trimText(input.reason); const { owner, subagent } = approvalOwnerCodexTurn(input.context); const parentNodeId = subagent?.subagentNodeId ?? @@ -4935,6 +4986,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(input.prompt === null || input.prompt === undefined ? {} : { prompt: input.prompt }), + ...(reason === undefined ? {} : { reason }), ...(input.appName === undefined ? {} : { appName: input.appName }), ...(input.options === undefined ? {} : { options: input.options }), }; @@ -6117,9 +6169,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.itemId, nativeRequestId, requestKind: "command", - ...((payload.reason ?? payload.command) === undefined - ? {} - : { prompt: payload.reason ?? payload.command }), + prompt: codexCommandApprovalPrompt(payload) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6192,6 +6243,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...payload, fileChanges: context.fileChangeKindsByItem.get(payload.itemId) ?? {}, }) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6254,7 +6306,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.itemId, nativeRequestId: payload.itemId, requestKind, - ...(payload.reason === undefined ? {} : { prompt: payload.reason }), + prompt: codexPermissionsApprovalPrompt(payload.permissions) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6405,7 +6458,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.callId, nativeRequestId, requestKind: "command", - prompt: payload.reason ?? payload.command.join(" "), + prompt: + codexCommandApprovalPrompt({ + command: payload.command.join(" "), + cwd: payload.cwd, + }) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6474,6 +6532,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeRequestId: payload.callId, requestKind: "file-change", prompt: codexFileChangeApprovalPrompt(payload) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 5d46c916c3990..e8efe5d2f91bc 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -2425,6 +2425,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" assert.isFalse(settings.projectSettingsFolded); assert.isFalse(settings.continueThreadsAfterServerUpdate); assert.equal(settings.usageHistoryRetentionDays, "unlimited"); + assert.isTrue(settings.requireConnectDeviceApproval); + assert.isFalse(settings.enablePreviewTunnel); + assert.isFalse(settings.enableAgentBrowserAccess); + assert.equal(settings.defaultRuntimeMode, "approval-required"); assert.deepEqual(settings.projectSettingsOverrides, {}); assert.equal(yield* fileSystem.readFileString(serverConfig.settingsPath), broken); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 14a64a1aa783c..822254afcca14 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -426,11 +426,15 @@ function decodeSettingsFile( const settings: ServerSettings = Exit.isSuccess(decoded) && failure === undefined ? decoded.value - : // The file may hold an opt-out we can no longer read; never resume threads on a guess. + : // The file may hold choices we can no longer read, so opt-in behaviour stays off. { ...managed.defaults, continueThreadsAfterServerUpdate: false, usageHistoryRetentionDays: "unlimited", + requireConnectDeviceApproval: true, + enablePreviewTunnel: false, + enableAgentBrowserAccess: false, + defaultRuntimeMode: "approval-required", }; return { settings, legacy: Exit.isSuccess(legacy) ? legacy.value : undefined, failure }; } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d56564f907b4b..c409788e8707c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2,6 +2,7 @@ import { m } from "../i18n/messages"; import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { useGT, useMessages } from "gt-react"; import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; +import { draftSupportedRuntimeModes } from "./chat/runtimeModeConfig"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; @@ -4035,9 +4036,11 @@ export default function ChatView(props: ChatViewProps) { ), diff --git a/apps/web/src/components/auth/PairingRouteSurface.browser.test.tsx b/apps/web/src/components/auth/PairingRouteSurface.browser.test.tsx new file mode 100644 index 0000000000000..d740f77d8c3dc --- /dev/null +++ b/apps/web/src/components/auth/PairingRouteSurface.browser.test.tsx @@ -0,0 +1,36 @@ +import { AsyncResult } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; + +const state = vi.hoisted(() => ({ connect: vi.fn() })); + +vi.mock("../../connection/onboarding", () => ({ connectPairing: {} })); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.connect })); +vi.mock("../../environments/primary", () => ({ + peekPairingTokenFromUrl: () => null, + stripPairingTokenFromUrl: () => undefined, + submitServerAuthCredential: () => Promise.resolve(), +})); +vi.mock("../../hostedPairing", () => ({ + readHostedPairingRequest: () => ({ host: "backend.example.com", token: "one-time", label: "" }), +})); + +import { HostedPairingRouteSurface } from "./PairingRouteSurface"; + +it("sends a link's pairing token only after the user confirms the backend", async () => { + state.connect.mockReset(); + state.connect.mockResolvedValue(AsyncResult.success(undefined)); + await using screen = await render(); + + await expect.element(screen.getByText("https://backend.example.com")).toBeVisible(); + expect(state.connect).not.toHaveBeenCalled(); + + await screen.getByRole("button", { name: "Add backend" }).click(); + await vi.waitFor(() => + expect(state.connect).toHaveBeenCalledExactlyOnceWith({ + host: "backend.example.com", + pairingCode: "one-time", + }), + ); +}); diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx index 57a5e79241ac3..f6ec70432ad8b 100644 --- a/apps/web/src/components/auth/PairingRouteSurface.tsx +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -11,6 +11,7 @@ import { submitServerAuthCredential, } from "../../environments/primary"; import { readHostedPairingRequest } from "../../hostedPairing"; +import { resolveRemotePairingTarget } from "@t3tools/shared/remote"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page"; @@ -146,17 +147,31 @@ export function HostedPairingRouteSurface() { reportFailure: false, }); const [request] = useState(readHostedPairingRequest); + // The origin shows the scheme along with the host. + const [origin] = useState(() => { + if (!request) return null; + try { + return new URL( + resolveRemotePairingTarget({ host: request.host, pairingCode: request.token }).httpBaseUrl, + ).origin; + } catch { + return null; + } + }); const gt = useGT(); - const [status, setStatus] = useState<"pairing" | "paired" | "error">( - request ? "pairing" : "error", + const [status, setStatus] = useState<"confirm" | "pairing" | "paired" | "error">( + origin ? "confirm" : "error", ); const [message, setMessage] = useState(() => - request - ? m(msg("Connecting to this backend.")) - : m(msg("This pairing link is missing its backend host or token.")), + origin + ? m(msg("This link adds a backend to this browser. Continue only if you trust it.")) + : request + ? m(msg("This pairing link has an invalid backend host.")) + : m(msg("This pairing link is missing its backend host or token.")), ); const [canRetry, setCanRetry] = useState(false); - const submitAttemptedRef = useRef(false); + // Nothing is sent to the link's host until the user confirms. + // The token stays in the URL until then: the root route picks this page from it. const tokenSubmittedRef = useRef(false); const submitHostedPairingRequest = async () => { @@ -180,6 +195,7 @@ export function HostedPairingRouteSurface() { setMessage(gt("Connecting to this backend.")); setCanRetry(false); tokenSubmittedRef.current = true; + stripPairingTokenFromUrl(); const result = await connectPairingEnvironment({ host: request.host, @@ -206,21 +222,6 @@ export function HostedPairingRouteSurface() { ); }; - const submitOnMount = useEffectEvent(() => { - void submitHostedPairingRequest(); - }); - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- strips the pairing token from the URL and submits the hosted pairing request once on mount - useEffect(() => { - if (submitAttemptedRef.current) { - return; - } - submitAttemptedRef.current = true; - - stripPairingTokenFromUrl(); - submitOnMount(); - }, []); - return ( @@ -239,7 +242,7 @@ export function HostedPairingRouteSurface() { Host:{" "} - {request.host} + {origin ?? request.host} @@ -257,7 +260,23 @@ export function HostedPairingRouteSurface() { ) : null}
- {status === "pairing" ? ( + {status === "confirm" ? ( + <> + + + + ) : status === "pairing" ? ( diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 5b540f48c483e..06330d75b3cca 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -6,6 +6,7 @@ import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; import { BackgroundThreadContext, HiddenThreadContext } from "./backgroundThread"; import { + draftSupportedRuntimeModes, resolveCompatibleRuntimeMode, runtimeModeConfig, resolveRuntimeModeOptions, @@ -1000,7 +1001,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = resolveCompatibleRuntimeMode( runtimeMode, - selectedProviderEntry?.snapshot.supportedRuntimeModes, + draftSupportedRuntimeModes( + selectedProviderEntry?.snapshot.supportedRuntimeModes, + multipleModelSelections, + providerStatuses, + ), ); // Modes above an administrator's ceiling stay listed, disabled with the reason. const compatibleRuntimeModeOptions = resolveRuntimeModeOptions( diff --git a/apps/web/src/components/chat/runtimeModeConfig.test.ts b/apps/web/src/components/chat/runtimeModeConfig.test.ts new file mode 100644 index 0000000000000..580fe7e43a268 --- /dev/null +++ b/apps/web/src/components/chat/runtimeModeConfig.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { draftSupportedRuntimeModes, resolveCompatibleRuntimeMode } from "./runtimeModeConfig"; + +describe("draftSupportedRuntimeModes", () => { + const supervisedOnly = { + instanceId: "fx", + supportedRuntimeModes: ["approval-required"], + } as const; + const noAuto = { + instanceId: "muse", + supportedRuntimeModes: ["approval-required", "full-access"], + } as const; + const everyMode = { instanceId: "codex" }; + const providers = [supervisedOnly, noAuto, everyMode]; + + it.each([ + { label: "one provider that supports it", selections: [supervisedOnly, noAuto] }, + { label: "a provider that reports no modes", selections: [supervisedOnly, everyMode] }, + ])("shows Full access when a multi-model draft includes $label", ({ selections }) => { + const modes = draftSupportedRuntimeModes( + supervisedOnly.supportedRuntimeModes, + selections, + providers, + ); + expect(resolveCompatibleRuntimeMode("full-access", modes).mode).toBe("full-access"); + }); + + it("falls back only when no selected provider can run the mode", () => { + const modes = draftSupportedRuntimeModes(undefined, [supervisedOnly, noAuto], providers); + expect(resolveCompatibleRuntimeMode("auto", modes).mode).toBe("approval-required"); + }); +}); diff --git a/apps/web/src/components/chat/runtimeModeConfig.ts b/apps/web/src/components/chat/runtimeModeConfig.ts index b4f77f2ca5d62..89655258ff935 100644 --- a/apps/web/src/components/chat/runtimeModeConfig.ts +++ b/apps/web/src/components/chat/runtimeModeConfig.ts @@ -51,6 +51,31 @@ export function resolveCompatibleRuntimeMode( return { modes, mode: modes.includes(runtimeMode) ? runtimeMode : (modes[0] ?? runtimeMode) }; } +/** + * The modes a draft's send can run in. A multi-model send gives every thread the draft's mode + * and only that thread's provider narrows it, so the composer offers what any of them supports. + */ +export function draftSupportedRuntimeModes( + activeProviderModes: ReadonlyArray | undefined, + multipleModelSelections: ReadonlyArray<{ readonly instanceId: string }> | null, + providers: ReadonlyArray<{ + readonly instanceId: string; + readonly supportedRuntimeModes?: ReadonlyArray | undefined; + }>, +) { + if (multipleModelSelections === null || multipleModelSelections.length === 0) { + return activeProviderModes; + } + const supported = multipleModelSelections.map( + (selection) => + providers.find((provider) => provider.instanceId === selection.instanceId) + ?.supportedRuntimeModes ?? [], + ); + // A provider that reports no modes supports them all. + if (supported.some((modes) => modes.length === 0)) return undefined; + return runtimeModeOptions.filter((mode) => supported.some((modes) => modes.includes(mode))); +} + export function resolveRuntimeModeOption( mode: RuntimeMode, resolve: MessageResolver = m, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 761473fabb358..36f57764ea37a 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3239,7 +3239,8 @@ "49e3cf16b3ac3e5f": "Zugriff", "9699d255b374e215": "Was es tun darf", "86f5769278f5fa4d": "Über das reine Lesen hinaus kann es Threads starten, Nachrichten senden und Threads stoppen, und keiner davon kann mit mehr als dem gewählten Modus laufen.", - "693a1983e099523a": "Verbindung mit diesem Backend.", + "4f3982f640dfed5b": "Dieser Link fügt diesem Browser ein Backend hinzu. Fahre nur fort, wenn du ihm vertraust.", + "41b32a424841adb7": "Dieser Kopplungslink enthält einen ungültigen Backend-Host.", "ec2a82b05e616aa0": "Diesem Kopplungslink fehlen Backend-Host oder Token.", "630d4f04309bc19a": "Authentifizierung fehlgeschlagen.", "63bc32e8544f4de1": "Diese Umgebung erwartet vertrauenswürdige Kopplungsdaten, bevor die App sich verbinden kann.", @@ -3253,11 +3254,13 @@ "55c59743f7fdd7fa": "Einmaltoken oder Kopplungsgeheimnis einfügen", "ca6a0c94398d763d": "Wird gekoppelt...", "989f56b8297dd684": "Dieses einmalige Kopplungstoken wurde bereits übermittelt. Fordere einen neuen Kopplungslink an.", + "693a1983e099523a": "Verbindung mit diesem Backend.", "db3dcafc90d10405": "{environment} ist in diesem Browser gespeichert.", "47d4ab320c4c394c": "Die Umgebung ist in diesem Browser gespeichert.", "d235c6bfa25870a4": "{error} Falls das Backend dieses Einmaltoken akzeptiert hat, fordere vor einem neuen Versuch einen neuen Kopplungslink an.", "00c1dcaef4762f18": "Backend gekoppelt", "aac4a30e5912c01c": "Kopplung fehlgeschlagen", + "c142c3f3bed15f8d": "Dieses Backend hinzufügen?", "dbb27f4ee8ecfa8e": "Backend wird gekoppelt", "8049e9ba2e8b4867": "Kopplungstoken", "0528294df7656322": [ @@ -3274,6 +3277,7 @@ } ], "ff5f1c260e87ecde": "Prüfe, ob das Backend von diesem Browser aus erreichbar ist, CORS für gehostete Clients unterstützt und über HTTPS ausgeliefert wird, wenn du diese Seite über HTTPS öffnest.", + "984c25ffcae69300": "Backend hinzufügen", "08570ee0982df89d": "Wird gekoppelt...", "3bbae7c96b6cbfc3": "App öffnen", "49cc06e79f21f85a": "{seconds} s", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2764010f88414..22791e2badd65 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Access", "9699d255b374e215": "What it may do", "86f5769278f5fa4d": "Beyond read only, it can start, message and stop threads, and none of them can run with more than the mode you pick.", - "693a1983e099523a": "Connecting to this backend.", + "4f3982f640dfed5b": "This link adds a backend to this browser. Continue only if you trust it.", + "41b32a424841adb7": "This pairing link has an invalid backend host.", "ec2a82b05e616aa0": "This pairing link is missing its backend host or token.", "630d4f04309bc19a": "Authentication failed.", "63bc32e8544f4de1": "This environment expects a trusted pairing credential before the app can connect.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Paste a one-time token or pairing secret", "ca6a0c94398d763d": "Pairing...", "989f56b8297dd684": "This one-time pairing token was already submitted. Request a new pairing link.", + "693a1983e099523a": "Connecting to this backend.", "db3dcafc90d10405": "{environment} is saved in this browser.", "47d4ab320c4c394c": "The environment is saved in this browser.", "d235c6bfa25870a4": "{error} If the backend accepted this one-time token, request a new pairing link before retrying.", "00c1dcaef4762f18": "Backend paired", "aac4a30e5912c01c": "Pairing failed", + "c142c3f3bed15f8d": "Add this backend?", "dbb27f4ee8ecfa8e": "Pairing backend", "8049e9ba2e8b4867": "Pairing token", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Verify the backend is reachable from this browser, supports CORS for hosted clients, and is served over HTTPS when opening this page from HTTPS.", + "984c25ffcae69300": "Add backend", "08570ee0982df89d": "Pairing...", "3bbae7c96b6cbfc3": "Open app", "49cc06e79f21f85a": "{seconds}s", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index f7bd7ecb09588..2c68ad496ac5f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Acceso", "9699d255b374e215": "Lo que puede hacer", "86f5769278f5fa4d": "Además de leer, puede iniciar, enviar mensajes a y detener hilos, y ninguno puede ejecutarse con más permisos que el modo que elijas.", - "693a1983e099523a": "Conectando con este backend.", + "4f3982f640dfed5b": "Este enlace añade un backend a este navegador. Continúa solo si confías en él.", + "41b32a424841adb7": "Este enlace de emparejamiento tiene un host de backend no válido.", "ec2a82b05e616aa0": "A este enlace de emparejamiento le falta el host del backend o el token.", "630d4f04309bc19a": "Falló la autenticación.", "63bc32e8544f4de1": "Este entorno espera una credencial de emparejamiento de confianza antes de que la app pueda conectarse.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Pega un token de un solo uso o un secreto de emparejamiento", "ca6a0c94398d763d": "Emparejando...", "989f56b8297dd684": "Este token de emparejamiento de un solo uso ya se envió. Solicita un enlace de emparejamiento nuevo.", + "693a1983e099523a": "Conectando con este backend.", "db3dcafc90d10405": "{environment} está guardado en este navegador.", "47d4ab320c4c394c": "El entorno está guardado en este navegador.", "d235c6bfa25870a4": "{error} Si el backend aceptó este token de un solo uso, solicita un enlace de emparejamiento nuevo antes de reintentarlo.", "00c1dcaef4762f18": "Backend emparejado", "aac4a30e5912c01c": "Falló el emparejamiento", + "c142c3f3bed15f8d": "¿Añadir este backend?", "dbb27f4ee8ecfa8e": "Backend de emparejamiento", "8049e9ba2e8b4867": "Token de emparejamiento", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Comprueba que se puede acceder al backend desde este navegador, que admite CORS para clientes alojados y que se sirve por HTTPS cuando abres esta página desde HTTPS.", + "984c25ffcae69300": "Añadir backend", "08570ee0982df89d": "Emparejando...", "3bbae7c96b6cbfc3": "Abrir app", "49cc06e79f21f85a": "{seconds} s", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 209553a0cda86..cb4db84726d56 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Accès", "9699d255b374e215": "Ce qu’il peut faire", "86f5769278f5fa4d": "Au-delà de la lecture seule, il peut démarrer, arrêter des fils et leur envoyer des messages, et aucun ne peut s’exécuter avec plus que le mode que vous choisissez.", - "693a1983e099523a": "Connexion à ce backend.", + "4f3982f640dfed5b": "Ce lien ajoute un backend à ce navigateur. Ne continuez que si vous lui faites confiance.", + "41b32a424841adb7": "L’hôte du backend de ce lien d’appairage n’est pas valide.", "ec2a82b05e616aa0": "Il manque l’hôte du backend ou le jeton dans ce lien d’appairage.", "630d4f04309bc19a": "Échec de l’authentification.", "63bc32e8544f4de1": "Cet environnement attend un identifiant d’appairage de confiance avant que l’app puisse se connecter.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Collez un jeton à usage unique ou un secret d’appairage", "ca6a0c94398d763d": "Appairage...", "989f56b8297dd684": "Ce jeton d’appairage à usage unique a déjà été envoyé. Demandez un nouveau lien d’appairage.", + "693a1983e099523a": "Connexion à ce backend.", "db3dcafc90d10405": "{environment} est enregistré dans ce navigateur.", "47d4ab320c4c394c": "L’environnement est enregistré dans ce navigateur.", "d235c6bfa25870a4": "{error} Si le backend a accepté ce jeton à usage unique, demandez un nouveau lien d’appairage avant de réessayer.", "00c1dcaef4762f18": "Backend appairé", "aac4a30e5912c01c": "Échec de l’appairage", + "c142c3f3bed15f8d": "Ajouter ce backend ?", "dbb27f4ee8ecfa8e": "Backend d’appairage", "8049e9ba2e8b4867": "Jeton d’appairage", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Vérifiez que le backend est joignable depuis ce navigateur, qu’il prend en charge CORS pour les clients hébergés et qu’il est servi en HTTPS si cette page est ouverte en HTTPS.", + "984c25ffcae69300": "Ajouter le backend", "08570ee0982df89d": "Appairage...", "3bbae7c96b6cbfc3": "Ouvrir l’app", "49cc06e79f21f85a": "{seconds} s", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c9e97b9e3f263..01c10337742d3 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3236,7 +3236,8 @@ "49e3cf16b3ac3e5f": "アクセス", "9699d255b374e215": "許可する操作", "86f5769278f5fa4d": "読み取り専用に加えて、スレッドの開始、メッセージ送信、停止ができます。どのスレッドも、選択したモードを超える権限では実行できません。", - "693a1983e099523a": "このバックエンドに接続しています。", + "4f3982f640dfed5b": "このリンクはこのブラウザにバックエンドを追加します。信頼できる場合のみ続行してください。", + "41b32a424841adb7": "このペアリングリンクのバックエンドホストが無効です。", "ec2a82b05e616aa0": "このペアリングリンクにはバックエンドのホストまたはトークンがありません。", "630d4f04309bc19a": "認証に失敗しました。", "63bc32e8544f4de1": "この環境では、アプリが接続する前に信頼されたペアリング資格情報が必要です。", @@ -3250,11 +3251,13 @@ "55c59743f7fdd7fa": "ワンタイムトークンまたはペアリングシークレットを貼り付け", "ca6a0c94398d763d": "ペアリングしています...", "989f56b8297dd684": "このワンタイムペアリングトークンはすでに送信されています。新しいペアリングリンクをリクエストしてください。", + "693a1983e099523a": "このバックエンドに接続しています。", "db3dcafc90d10405": "{environment} はこのブラウザーに保存されています。", "47d4ab320c4c394c": "環境はこのブラウザーに保存されています。", "d235c6bfa25870a4": "{error} バックエンドがこのワンタイムトークンを受け付けた場合は、再試行する前に新しいペアリングリンクをリクエストしてください。", "00c1dcaef4762f18": "バックエンドとペアリングしました", "aac4a30e5912c01c": "ペアリングに失敗しました", + "c142c3f3bed15f8d": "このバックエンドを追加しますか?", "dbb27f4ee8ecfa8e": "ペアリング先のバックエンド", "8049e9ba2e8b4867": "ペアリングトークン", "0528294df7656322": [ @@ -3271,6 +3274,7 @@ } ], "ff5f1c260e87ecde": "バックエンドがこのブラウザーから到達可能で、ホスト型クライアント向けに CORS をサポートしていること、また HTTPS のページから開く場合は HTTPS で提供されていることを確認してください。", + "984c25ffcae69300": "バックエンドを追加", "08570ee0982df89d": "ペアリングしています...", "3bbae7c96b6cbfc3": "アプリを開く", "49cc06e79f21f85a": "{seconds}秒", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 7d528f7527d27..eb4cf8b1c5273 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3237,7 +3237,8 @@ "49e3cf16b3ac3e5f": "액세스", "9699d255b374e215": "허용할 작업", "86f5769278f5fa4d": "읽기 전용 외에 스레드를 시작하고, 메시지를 보내고, 중지할 수 있으며, 어떤 스레드도 선택한 모드보다 높은 권한으로 실행할 수 없습니다.", - "693a1983e099523a": "이 백엔드에 연결하는 중입니다.", + "4f3982f640dfed5b": "이 링크는 이 브라우저에 백엔드를 추가합니다. 신뢰하는 경우에만 계속하세요.", + "41b32a424841adb7": "이 페어링 링크의 백엔드 호스트가 올바르지 않습니다.", "ec2a82b05e616aa0": "이 페어링 링크에 백엔드 호스트 또는 토큰이 없습니다.", "630d4f04309bc19a": "인증에 실패했습니다.", "63bc32e8544f4de1": "앱이 연결하려면 이 환경에 신뢰할 수 있는 페어링 자격 증명이 필요합니다.", @@ -3251,11 +3252,13 @@ "55c59743f7fdd7fa": "일회용 토큰 또는 페어링 시크릿 붙여 넣기", "ca6a0c94398d763d": "페어링하는 중...", "989f56b8297dd684": "이 일회용 페어링 토큰은 이미 제출되었습니다. 새 페어링 링크를 요청하세요.", + "693a1983e099523a": "이 백엔드에 연결하는 중입니다.", "db3dcafc90d10405": "{environment}이(가) 이 브라우저에 저장되었습니다.", "47d4ab320c4c394c": "환경이 이 브라우저에 저장되었습니다.", "d235c6bfa25870a4": "{error} 백엔드가 이 일회용 토큰을 수락했다면 다시 시도하기 전에 새 페어링 링크를 요청하세요.", "00c1dcaef4762f18": "백엔드 페어링됨", "aac4a30e5912c01c": "페어링 실패", + "c142c3f3bed15f8d": "이 백엔드를 추가할까요?", "dbb27f4ee8ecfa8e": "백엔드 페어링 중", "8049e9ba2e8b4867": "페어링 토큰", "0528294df7656322": [ @@ -3272,6 +3275,7 @@ } ], "ff5f1c260e87ecde": "이 브라우저에서 백엔드에 접근할 수 있는지, 호스팅된 클라이언트용 CORS를 지원하는지, HTTPS 페이지에서 열 때 HTTPS로 제공되는지 확인하세요.", + "984c25ffcae69300": "백엔드 추가", "08570ee0982df89d": "페어링하는 중...", "3bbae7c96b6cbfc3": "앱 열기", "49cc06e79f21f85a": "{seconds}초", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 33e0262600d4a..06eea3c29b995 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Acesso", "9699d255b374e215": "O que ele pode fazer", "86f5769278f5fa4d": "Além da leitura, ele pode iniciar, enviar mensagens e parar threads, e nenhuma delas pode rodar com mais do que o modo que você escolher.", - "693a1983e099523a": "Conectando a este backend.", + "4f3982f640dfed5b": "Este link adiciona um backend a este navegador. Continue somente se você confia nele.", + "41b32a424841adb7": "Este link de pareamento tem um host de backend inválido.", "ec2a82b05e616aa0": "Falta o host do backend ou o token neste link de pareamento.", "630d4f04309bc19a": "Falha na autenticação.", "63bc32e8544f4de1": "Este ambiente exige uma credencial de pareamento confiável antes que o app possa se conectar.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Cole um token de uso único ou um segredo de pareamento", "ca6a0c94398d763d": "Pareando...", "989f56b8297dd684": "Este token de pareamento de uso único já foi enviado. Solicite um novo link de pareamento.", + "693a1983e099523a": "Conectando a este backend.", "db3dcafc90d10405": "{environment} está salvo neste navegador.", "47d4ab320c4c394c": "O ambiente está salvo neste navegador.", "d235c6bfa25870a4": "{error} Se o backend aceitou este token de uso único, solicite um novo link de pareamento antes de tentar novamente.", "00c1dcaef4762f18": "Backend pareado", "aac4a30e5912c01c": "Falha no pareamento", + "c142c3f3bed15f8d": "Adicionar este backend?", "dbb27f4ee8ecfa8e": "Pareando o backend", "8049e9ba2e8b4867": "Token de pareamento", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Verifique se o backend está acessível a partir deste navegador, se permite CORS para clientes hospedados e se é servido por HTTPS quando esta página é aberta via HTTPS.", + "984c25ffcae69300": "Adicionar backend", "08570ee0982df89d": "Pareando...", "3bbae7c96b6cbfc3": "Abrir app", "49cc06e79f21f85a": "{seconds}s", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index a93a2ce219ea2..44148970bd468 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Доступ", "9699d255b374e215": "Что ему разрешено", "86f5769278f5fa4d": "Помимо чтения, он может запускать треды, отправлять в них сообщения и останавливать их, и ни один не будет работать с режимом выше выбранного.", - "693a1983e099523a": "Подключение к этому бэкенду.", + "4f3982f640dfed5b": "Эта ссылка добавляет бэкенд в этот браузер. Продолжайте, только если доверяете ему.", + "41b32a424841adb7": "В ссылке для сопряжения указан недопустимый хост бэкенда.", "ec2a82b05e616aa0": "В ссылке для сопряжения нет хоста бэкенда или токена.", "630d4f04309bc19a": "Ошибка аутентификации.", "63bc32e8544f4de1": "Этому окружению нужны доверенные учётные данные сопряжения, прежде чем приложение сможет подключиться.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Вставьте одноразовый токен или секрет сопряжения", "ca6a0c94398d763d": "Сопряжение...", "989f56b8297dd684": "Этот одноразовый токен сопряжения уже отправлен. Запросите новую ссылку для сопряжения.", + "693a1983e099523a": "Подключение к этому бэкенду.", "db3dcafc90d10405": "{environment} сохранено в этом браузере.", "47d4ab320c4c394c": "Окружение сохранено в этом браузере.", "d235c6bfa25870a4": "{error} Если бэкенд принял этот одноразовый токен, запросите новую ссылку для сопряжения перед повтором.", "00c1dcaef4762f18": "Сопряжение с бэкендом выполнено", "aac4a30e5912c01c": "Ошибка сопряжения", + "c142c3f3bed15f8d": "Добавить этот бэкенд?", "dbb27f4ee8ecfa8e": "Бэкенд сопряжения", "8049e9ba2e8b4867": "Токен сопряжения", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Убедитесь, что бэкенд доступен из этого браузера, поддерживает CORS для размещённых клиентов и работает по HTTPS, если эта страница открыта по HTTPS.", + "984c25ffcae69300": "Добавить бэкенд", "08570ee0982df89d": "Сопряжение...", "3bbae7c96b6cbfc3": "Открыть приложение", "49cc06e79f21f85a": "{seconds} с", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 2b15a6570f9ab..2bb20d01df420 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3238,7 +3238,8 @@ "49e3cf16b3ac3e5f": "Åtkomst", "9699d255b374e215": "Vad den får göra", "86f5769278f5fa4d": "Utöver endast läsning kan den starta, skicka meddelanden till och stoppa trådar, och ingen av dem kan köras med mer än det läge du väljer.", - "693a1983e099523a": "Ansluter till den här backenden.", + "4f3982f640dfed5b": "Den här länken lägger till en backend i den här webbläsaren. Fortsätt bara om du litar på den.", + "41b32a424841adb7": "Den här parkopplingslänken har en ogiltig backend-värd.", "ec2a82b05e616aa0": "Den här parkopplingslänken saknar backend-värd eller token.", "630d4f04309bc19a": "Autentiseringen misslyckades.", "63bc32e8544f4de1": "Den här miljön kräver en betrodd parkopplingsuppgift innan appen kan ansluta.", @@ -3252,11 +3253,13 @@ "55c59743f7fdd7fa": "Klistra in en engångstoken eller en parkopplingshemlighet", "ca6a0c94398d763d": "Parkopplar...", "989f56b8297dd684": "Den här engångstoken för parkoppling har redan skickats. Begär en ny parkopplingslänk.", + "693a1983e099523a": "Ansluter till den här backenden.", "db3dcafc90d10405": "{environment} är sparad i den här webbläsaren.", "47d4ab320c4c394c": "Miljön är sparad i den här webbläsaren.", "d235c6bfa25870a4": "{error} Om backenden godtog den här engångstoken, begär en ny parkopplingslänk innan du försöker igen.", "00c1dcaef4762f18": "Backenden parkopplades", "aac4a30e5912c01c": "Parkopplingen misslyckades", + "c142c3f3bed15f8d": "Lägga till den här backenden?", "dbb27f4ee8ecfa8e": "Parkopplar backend", "8049e9ba2e8b4867": "Parkopplingstoken", "0528294df7656322": [ @@ -3273,6 +3276,7 @@ } ], "ff5f1c260e87ecde": "Kontrollera att backenden kan nås från den här webbläsaren, stöder CORS för webbaserade klienter och betjänas via HTTPS när den här sidan öppnas via HTTPS.", + "984c25ffcae69300": "Lägg till backend", "08570ee0982df89d": "Parkopplar...", "3bbae7c96b6cbfc3": "Öppna app", "49cc06e79f21f85a": "{seconds} s", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index fc0cbe1297c4f..0def42b8dda67 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3242,7 +3242,8 @@ "49e3cf16b3ac3e5f": "访问权限", "9699d255b374e215": "允许它做什么", "86f5769278f5fa4d": "除只读外,它还可以启动会话、向会话发消息和停止会话,且任何会话的权限都不会超过你选择的模式。", - "693a1983e099523a": "正在连接此后端。", + "4f3982f640dfed5b": "此链接会向此浏览器添加一个后端。仅在你信任它时继续。", + "41b32a424841adb7": "此配对链接中的后端主机无效。", "ec2a82b05e616aa0": "此配对链接缺少后端主机或 token。", "630d4f04309bc19a": "身份验证失败。", "63bc32e8544f4de1": "此环境需要可信的配对凭据,应用才能连接。", @@ -3256,11 +3257,13 @@ "55c59743f7fdd7fa": "粘贴一次性 token 或配对凭据", "ca6a0c94398d763d": "正在配对…", "989f56b8297dd684": "此一次性配对 token 已提交过。请申请新的配对链接。", + "693a1983e099523a": "正在连接此后端。", "db3dcafc90d10405": "{environment} 已保存在此浏览器中。", "47d4ab320c4c394c": "该环境已保存在此浏览器中。", "d235c6bfa25870a4": "{error} 如果后端已接受此一次性 token,请先申请新的配对链接再重试。", "00c1dcaef4762f18": "后端已配对", "aac4a30e5912c01c": "配对失败", + "c142c3f3bed15f8d": "要添加此后端吗?", "dbb27f4ee8ecfa8e": "正在配对后端", "8049e9ba2e8b4867": "配对 token", "0528294df7656322": [ @@ -3277,6 +3280,7 @@ } ], "ff5f1c260e87ecde": "请确认此浏览器能访问该后端、后端为托管客户端启用了 CORS,并且在通过 HTTPS 打开此页面时后端也使用 HTTPS。", + "984c25ffcae69300": "添加后端", "08570ee0982df89d": "正在配对…", "3bbae7c96b6cbfc3": "打开应用", "49cc06e79f21f85a": "{seconds} 秒", diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index bdcd2281ccd08..3518382d2026e 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -235,7 +235,8 @@ If that port is already in use, choose another with [app.t3.codes](https://app.t3.codes) needs an HTTPS endpoint. It connects directly to your server; a hosted pairing link does not make an unreachable backend -reachable or convert HTTP to HTTPS. +reachable or convert HTTP to HTTPS. Opening a hosted pairing link shows the +server address and asks you to confirm before adding it. For a plain HTTP LAN endpoint, use the direct pairing URL in a browser that can open it, or pair from the desktop app. On mobile, an IP address entered without a From 7c95302f7a87cb8462c0fd71f2122aeaadb5c967 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:13:14 -0800 Subject: [PATCH 102/221] ci: release and preview credentials are scoped to the steps and jobs that use them (#41765) Co-authored-by: Claude Fable 5.2 --- .github/actions/record-build-tag/action.yml | 20 +- .github/actions/setup-ci-deps/action.yml | 21 +- .github/scripts/set-mobile-version.cjs | 30 ++ .../scripts/vercel-deployment-output.test.cjs | 2 +- .github/scripts/workflow-credentials.test.cjs | 269 +++++++++++++++++ .github/workflows/ci.yml | 2 +- .../workflows/mobile-eas-preview-build.yml | 198 +++++++++++++ .github/workflows/mobile-eas-preview-fork.yml | 17 +- .github/workflows/mobile-eas-preview.yml | 170 +---------- .../workflows/mobile-eas-production-build.yml | 196 +++++++++++++ .github/workflows/mobile-eas-production.yml | 277 ++++++------------ .github/workflows/release.yml | 17 +- .github/workflows/web-preview.yml | 13 +- docs/operations/03_release.md | 2 +- 14 files changed, 869 insertions(+), 365 deletions(-) create mode 100644 .github/scripts/set-mobile-version.cjs create mode 100644 .github/scripts/workflow-credentials.test.cjs create mode 100644 .github/workflows/mobile-eas-preview-build.yml create mode 100644 .github/workflows/mobile-eas-production-build.yml diff --git a/.github/actions/record-build-tag/action.yml b/.github/actions/record-build-tag/action.yml index 2086d004b295c..a45f83e1263a8 100644 --- a/.github/actions/record-build-tag/action.yml +++ b/.github/actions/record-build-tag/action.yml @@ -8,6 +8,9 @@ inputs: message: description: Annotated tag message; empty makes a lightweight tag default: "" + commit: + description: Commit to tag, 40 hex characters and reachable from the workflow's ref; empty tags HEAD + default: "" replace: description: "true replaces an existing tag; otherwise an existing tag counts as recorded" default: "false" @@ -22,6 +25,7 @@ runs: shell: bash env: TAG: ${{ inputs.tag }} + COMMIT: ${{ inputs.commit }} MESSAGE: ${{ inputs.message }} REPLACE: ${{ inputs.replace }} GH_TOKEN: ${{ inputs.token }} @@ -29,6 +33,18 @@ runs: git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" remote="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + # A named commit is tagged only when it is on the ref this workflow runs for. + if [ -n "$COMMIT" ]; then + if ! [[ "$COMMIT" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::The commit to tag is not a full SHA." + exit 1 + fi + git fetch --quiet "$remote" "$GITHUB_REF" + if ! git merge-base --is-ancestor "$COMMIT" FETCH_HEAD 2>/dev/null; then + echo "::error::$COMMIT is not on $GITHUB_REF." + exit 1 + fi + fi # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). for attempt in 1 2 3; do if refs="$(git ls-remote "$remote" "refs/tags/$TAG")"; then @@ -40,9 +56,9 @@ runs: exit 0 fi if [ -n "$MESSAGE" ]; then - git tag -f -a "$TAG" -m "$MESSAGE" + git tag -f -a "$TAG" -m "$MESSAGE" ${COMMIT:+"$COMMIT"} else - git tag -f "$TAG" + git tag -f "$TAG" ${COMMIT:+"$COMMIT"} fi # An empty lease means the tag must not exist yet. if git push --force-with-lease="refs/tags/$TAG:$old" "$remote" "refs/tags/$TAG"; then diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index cc6dc80511aca..b2236f6a15cf8 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -31,14 +31,16 @@ runs: echo "node=$(jq -r '.engines.node' package.json)" >> "$GITHUB_OUTPUT" echo "pnpm=$(jq -r '.packageManager' package.json)" >> "$GITHUB_OUTPUT" + # Restore only: "Save Vite+" below writes the toolchain before this job + # installs or runs project code. # Pinned because release-desktop.yml signs builds with this action in the job. - - name: Cache Vite+ + - name: Restore Vite+ id: vp_cache if: steps.vp.outputs.version != '' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.vite-plus - key: vite-plus-home-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} + key: vite-plus-home-v3-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} # setup-vp always runs the installer, which fetches vp from npm even when # this exact version is installed. A cache hit already has everything, so @@ -64,6 +66,19 @@ runs: cache: false run-install: false + # vp downloads pnpm on first use, which would otherwise be after the save. + - name: Fetch pnpm + if: steps.vp.outputs.version != '' && steps.vp_cache.outputs.cache-hit != 'true' + shell: bash + run: vp pm cache dir + + - name: Save Vite+ + if: steps.vp.outputs.version != '' && steps.vp_cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.vite-plus + key: ${{ steps.vp_cache.outputs.cache-primary-key }} + # A shared key lets whichever install saves first, often a small filtered # one, become every job's store. Each set of install args gets its own. - name: Resolve pnpm store diff --git a/.github/scripts/set-mobile-version.cjs b/.github/scripts/set-mobile-version.cjs new file mode 100644 index 0000000000000..bb45a524ed357 --- /dev/null +++ b/.github/scripts/set-mobile-version.cjs @@ -0,0 +1,30 @@ +const fs = require("node:fs"); + +const CONFIG_PATH = "apps/mobile/app.config.ts"; +const VERSION_LINE = /^( {2}version: repoEnv\.T3CODE_MOBILE_VERSION \?\? ")[^"]+(".*)$/m; + +// Replaces one string literal, so the result needs no formatter. +function setMobileVersion(source, version) { + if (!/^[0-9]+(\.[0-9]+){1,2}$/.test(version)) { + throw new Error( + `Version override must contain two or three dot-separated integers; received '${version}'.`, + ); + } + if (!VERSION_LINE.test(source)) throw new Error("Could not update app version"); + return source.replace(VERSION_LINE, `$1${version}$2`); +} + +if (require.main === module) { + const { GITHUB_REF_TYPE, GITHUB_REF_NAME } = process.env; + if (GITHUB_REF_TYPE !== "branch") { + throw new Error( + `Version overrides require dispatching this workflow from a branch; received ${GITHUB_REF_TYPE} '${GITHUB_REF_NAME}'.`, + ); + } + fs.writeFileSync( + CONFIG_PATH, + setMobileVersion(fs.readFileSync(CONFIG_PATH, "utf8"), process.argv[2] ?? ""), + ); +} + +module.exports = { setMobileVersion }; diff --git a/.github/scripts/vercel-deployment-output.test.cjs b/.github/scripts/vercel-deployment-output.test.cjs index a249653350f22..b5a3ea7b94471 100644 --- a/.github/scripts/vercel-deployment-output.test.cjs +++ b/.github/scripts/vercel-deployment-output.test.cjs @@ -8,7 +8,7 @@ const { test } = require("node:test"); const release = readFileSync(join(__dirname, "../workflows/release.yml"), "utf8"); const preview = readFileSync(join(__dirname, "../workflows/web-preview.yml"), "utf8"); const stepPattern = - / name: (?:Build staged deployment|Deploy preview)\n shell: bash\n run: \|\n((?: .*\n|\n)+)/g; + / name: (?:Build staged deployment|Deploy preview)\n shell: bash\n(?: env:\n(?: .*\n)+)? run: \|\n((?: .*\n|\n)+)/g; const steps = [ ...Array.from(release.matchAll(stepPattern), (match, index) => [ index === 0 ? "hosted web" : "marketing", diff --git a/.github/scripts/workflow-credentials.test.cjs b/.github/scripts/workflow-credentials.test.cjs new file mode 100644 index 0000000000000..7dc6018654e7e --- /dev/null +++ b/.github/scripts/workflow-credentials.test.cjs @@ -0,0 +1,269 @@ +const assert = require("node:assert/strict"); +const { execFileSync, spawnSync } = require("node:child_process"); +const { mkdtempSync, readFileSync, rmSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { test } = require("node:test"); + +const { setMobileVersion } = require("./set-mobile-version.cjs"); + +const read = (path) => readFileSync(join(__dirname, "..", path), "utf8"); + +function jobs(path) { + const body = read(path).split(/^jobs:\n/m)[1]; + const found = {}; + for (const block of body.split(/^(?= [\w-]+:\n)/m)) { + const name = /^ ([\w-]+):\n/.exec(block)?.[1]; + if (name) found[name] = block; + } + return found; +} + +const steps = (block) => block.split(/^ {4,6}- /m).slice(1); +const runsProjectCode = (block) => + /setup-vp@|setup-ci-deps|eas-local-build|expo-github-action|\b(?:vp|pnpm|npm|npx|eas) /.test( + block, + ); + +test("npm publishing is bound to the environment that admits only main and v* tags", () => { + const publish = jobs("workflows/release.yml").publish_cli; + assert.match(publish, /^ {6}id-token: write$/m); + assert.match(publish, /^ {4}environment: production$/m); +}); + +test("the web preview gives the Vercel token to the deploy step only, after an install without lifecycle scripts", () => { + const deploy = jobs("workflows/web-preview.yml").deploy; + assert.doesNotMatch(deploy.split(/^ {4}steps:\n/m)[0], /secrets\./); + const withSecrets = steps(deploy).filter((step) => step.includes("secrets.")); + assert.equal(withSecrets.length, 1); + assert.match(withSecrets[0], /name: Deploy preview/); + assert.match(deploy, /run-install: \|\n {12}args:\n {14}- --ignore-scripts\n/); +}); + +const mobileWorkflows = [ + "workflows/mobile-eas-preview.yml", + "workflows/mobile-eas-preview-build.yml", + "workflows/mobile-eas-production.yml", + "workflows/mobile-eas-production-build.yml", +]; + +for (const path of mobileWorkflows) { + test(`${path}: no job that installs or builds can push to the repository`, () => { + for (const [name, block] of Object.entries(jobs(path))) { + if (/^ {4}uses: /m.test(block)) continue; + const writes = /contents: write|record-build-tag|create-github-app-token/.test(block); + assert.ok(!(writes && runsProjectCode(block)), `${name} holds a write token and runs code`); + } + }); +} + +test("the build record is pushed by the record job of each build workflow", () => { + for (const path of [ + "workflows/mobile-eas-preview-build.yml", + "workflows/mobile-eas-production-build.yml", + ]) { + const { record, ...builds } = jobs(path); + assert.match(record, /uses: \.\/\.github\/actions\/record-build-tag/); + assert.match(record, /^ {6}contents: write/m); + for (const block of Object.values(builds)) assert.match(block, /^ {6}contents: read$/m); + } +}); + +test("jobs that push run this workflow's own actions", () => { + for (const file of mobileWorkflows) { + for (const [name, block] of Object.entries(jobs(file))) { + if (!/contents: write|create-github-app-token/.test(block)) continue; + const jobSteps = steps(block); + const checkout = jobSteps.findIndex((step) => /^ +ref: .*\b(?:inputs|needs)\./m.test(step)); + if (checkout === -1) continue; + const local = jobSteps.slice(checkout).filter((step) => /^ +uses: \.\//m.test(step)); + assert.equal(local.length, 0, `${file} ${name} runs a local action from another checkout`); + } + } +}); + +const recordScript = read("actions/record-build-tag/action.yml") + .split(/^ {6}run: \|\n/m)[1] + .replace(/^ {8}/gm, "") + .replace(/^remote=.*$/m, 'remote="$TEST_REMOTE"'); + +function recordTag(commitOf) { + const directory = mkdtempSync(join(tmpdir(), "t3-record-tag-")); + const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + try { + const remote = join(directory, "remote.git"); + const work = join(directory, "work"); + git(directory, "init", "--quiet", "--bare", remote); + git(directory, "init", "--quiet", "--initial-branch=main", work); + const commit = (message) => { + git( + work, + "-c", + "user.name=t", + "-c", + "user.email=t@example.com", + "commit", + "--quiet", + "--allow-empty", + "-m", + message, + ); + return git(work, "rev-parse", "HEAD"); + }; + const shas = { first: commit("first") }; + shas.head = commit("second"); + git(work, "push", "--quiet", remote, "main"); + git(work, "checkout", "--quiet", "--detach"); + shas.elsewhere = commit("not on main"); + git(work, "push", "--quiet", remote, "HEAD:refs/heads/other"); + git(work, "checkout", "--quiet", "main"); + const result = spawnSync("bash", ["-c", recordScript], { + cwd: work, + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOME: directory, + TEST_REMOTE: remote, + GITHUB_REF: "refs/heads/main", + TAG: "build/1", + MESSAGE: "", + REPLACE: "false", + COMMIT: commitOf(shas), + }, + }); + const tagged = git(directory, "ls-remote", remote, "refs/tags/build/1").split(/\s/)[0]; + return { status: result.status, tagged, shas }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +test("the build record tags the named commit only when it is on the workflow's ref", () => { + const onRef = recordTag((shas) => shas.first); + assert.deepEqual([onRef.status, onRef.tagged], [0, onRef.shas.first]); + const head = recordTag(() => ""); + assert.deepEqual([head.status, head.tagged], [0, head.shas.head]); + for (const commitOf of [(shas) => shas.elsewhere, () => "main", () => "0".repeat(40)]) { + const refused = recordTag(commitOf); + assert.deepEqual([refused.status, refused.tagged], [1, ""]); + } +}); + +test("the store build record job runs the workflow's own action and passes the built commit as data", () => { + const { record } = jobs("workflows/mobile-eas-production-build.yml"); + assert.doesNotMatch(record, /^ +ref: /m); + assert.match(record, /^ {10}commit: \$\{\{ inputs\.sha \}\}$/m); +}); + +test("release deploys give the Vercel token to the deploy step only", () => { + const all = jobs("workflows/release.yml"); + for (const name of ["build_web", "build_marketing"]) { + assert.doesNotMatch(all[name].split(/^ {4}steps:\n/m)[0], /secrets\.VERCEL/); + const withToken = steps(all[name]).filter((step) => step.includes("secrets.VERCEL_TOKEN")); + assert.equal(withToken.length, 1); + assert.match(withToken[0], /name: Build staged deployment/); + } +}); + +test("the version override token covers this repository only", () => { + const { version, production } = jobs("workflows/mobile-eas-production.yml"); + const mint = steps(version).find((step) => step.includes("create-github-app-token")); + assert.doesNotMatch(mint, /^\s+(?:owner|repositories):/m); + assert.match(mint, /^\s+permission-contents: write$/m); + assert.doesNotMatch(production, /RELEASE_APP|create-github-app-token/); +}); + +test("the Vite+ toolchain is cached before the job installs or runs project code", () => { + const names = Array.from( + read("actions/setup-ci-deps/action.yml").matchAll( + /^ {4}- name: (.+)\n(?: {6}.*\n)*? {6}uses: (\S+)|^ {4}- name: (.+)$/gm, + ), + (match) => ({ name: match[1] ?? match[3], uses: match[2] ?? "" }), + ); + const index = (name) => names.findIndex((step) => step.name === name); + assert.match(names[index("Restore Vite+")].uses, /^actions\/cache\/restore@/); + assert.match(names[index("Save Vite+")].uses, /^actions\/cache\/save@/); + assert.ok(index("Save Vite+") < index("Resolve pnpm store")); + assert.ok(index("Save Vite+") < index("Install dependencies")); + // The combined action saves at the end of the job, after everything ran. + assert.ok(names.every((step) => !step.uses.startsWith("actions/cache@"))); +}); + +const consumeScript = steps(jobs("workflows/mobile-eas-preview-fork.yml").preview) + .find((step) => step.startsWith("id: consume\n")) + .split(/^ {10}script: \|\n/m)[1] + .replace(/^ {12}/gm, ""); +const consume = new (Object.getPrototypeOf(async () => {}).constructor)( + "github", + "context", + "core", + consumeScript, +); + +async function runConsume(permission, removeStatus) { + const outputs = {}; + const removed = []; + await consume( + { + rest: { + repos: { + async getCollaboratorPermissionLevel({ username }) { + assert.equal(username, "labeler"); + return { data: { permission } }; + }, + }, + issues: { + async removeLabel(params) { + if (removeStatus) throw Object.assign(new Error("gone"), { status: removeStatus }); + removed.push(params.name); + }, + }, + }, + }, + { + repo: { owner: "example", repo: "app" }, + payload: { + sender: { login: "labeler" }, + label: { name: "deploy" }, + pull_request: { number: 7 }, + }, + }, + { info() {}, warning() {}, setOutput: (name, value) => (outputs[name] = value) }, + ); + return { outputs, removed }; +} + +for (const [permission, consumed] of [ + ["admin", "true"], + ["maintain", "true"], + ["write", "true"], + ["triage", "false"], + ["read", "false"], + ["none", "false"], +]) { + test(`a fork preview label from ${permission} access is removed and ${consumed === "true" ? "builds" : "builds nothing"}`, async () => { + assert.deepEqual(await runConsume(permission), { + outputs: { consumed }, + removed: ["deploy"], + }); + }); +} + +test("a fork preview label removed before the run builds nothing", async () => { + assert.deepEqual(await runConsume("admin", 404), { outputs: { consumed: "false" }, removed: [] }); +}); + +test("a version override rewrites only the app version", () => { + const config = read("../apps/mobile/app.config.ts"); + const next = setMobileVersion(config, "9.8.7"); + assert.match(next, /^ {2}version: repoEnv\.T3CODE_MOBILE_VERSION \?\? "9\.8\.7",$/m); + assert.equal(setMobileVersion(next, "9.8.7"), next); + assert.deepEqual( + next.split("\n").filter((line, index) => line !== config.split("\n")[index]).length, + 1, + ); + for (const version of ["", "1", "1.2.3.4", "1.2-beta", '1.2", extra: "x']) { + assert.throws(() => setMobileVersion(config, version), /two or three dot-separated integers/); + } + assert.throws(() => setMobileVersion("export default {};", "1.2.3"), /Could not update/); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4c0cfc691b37..70208c7a16479 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -339,7 +339,7 @@ jobs: run: python3 -B .github/scripts/stage-preview-bundle.test.py - name: Test release checks - run: node --test .github/scripts/check-nightly-release.test.cjs .github/scripts/vercel-deployment-output.test.cjs .github/scripts/mobile-preview-comment.test.cjs .github/scripts/mobile-ios-preview-record.test.cjs .github/scripts/test-delta.test.cjs + run: node --test .github/scripts/check-nightly-release.test.cjs .github/scripts/vercel-deployment-output.test.cjs .github/scripts/mobile-preview-comment.test.cjs .github/scripts/mobile-ios-preview-record.test.cjs .github/scripts/test-delta.test.cjs .github/scripts/workflow-credentials.test.cjs - name: Finish installing browser secret helper build libraries timeout-minutes: 5 diff --git a/.github/workflows/mobile-eas-preview-build.yml b/.github/workflows/mobile-eas-preview-build.yml new file mode 100644 index 0000000000000..a7774c24bd0af --- /dev/null +++ b/.github/workflows/mobile-eas-preview-build.yml @@ -0,0 +1,198 @@ +name: Mobile EAS Preview Build + +# One preview client and its build record, called per platform by +# mobile-eas-preview.yml. The build job runs dependency and build scripts with a +# read-only token. Only the record job, on a fresh runner that runs none of +# them, gets the token that can push tags. The caller's concurrency group covers +# both jobs, so a build queued for the same fingerprint starts after the tag exists. + +on: + workflow_call: + inputs: + platform: + description: android or ios + required: true + type: string + fingerprint: + required: true + type: string + secrets: + EXPO_PREVIEW_TOKEN: + required: true + outputs: + client: + description: Install link for the client with this fingerprint + value: ${{ jobs.android.outputs.client || jobs.ios.outputs.client }} + +jobs: + android: + name: Build + if: inputs.platform == 'android' + runs-on: blacksmith-32vcpu-ubuntu-2404 + timeout-minutes: 60 + permissions: + contents: read + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} + # Set only by a new build: the tag message, which is the install link. + record: ${{ steps.build.outputs.link }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + FINGERPRINT: ${{ inputs.fingerprint }} + BUILD_TAG: mobile-android-preview-build/${{ inputs.fingerprint }} + # Phones only: emulators use the development client from the native-client cache. + ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - id: record + name: Check build record + run: | + if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" + fi + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk + + # `eas upload` hosts the APK on EAS and returns the page testers install from. + - id: build + name: Upload + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash + run: | + eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + echo "### Android preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" + + ios: + name: Build + if: inputs.platform == 'ios' + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + permissions: + contents: read + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} + # Set only by a new build: the tag message, the install link and profile expiry. + record: ${{ steps.profile.outputs.record }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + FINGERPRINT: ${{ inputs.fingerprint }} + BUILD_TAG: mobile-ios-preview-build/${{ inputs.fingerprint }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Setup Node + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: package.json + + - id: record + name: Check build record + run: | + if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then + link="$(git tag -l --format='%(contents)' "$BUILD_TAG" | node .github/scripts/mobile-ios-preview-record.cjs read)" + if [ -n "$link" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo "link=$link" >> "$GITHUB_OUTPUT" + fi + fi + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: ios + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.ipa + + # EAS hosts the signed client and returns its install page. + - id: build + name: Upload + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash + run: | + eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" + + # The tag stores the install link and provisioning-profile expiry. + - id: profile + name: Read the provisioning profile + if: steps.record.outputs.built != 'true' + env: + LINK: ${{ steps.build.outputs.link }} + run: | + profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | grep -E '^Payload/[^/]+\.app/embedded\.mobileprovision$')" + unzip -p "$RUNNER_TEMP/t3code-preview.ipa" "$profile_path" > "$RUNNER_TEMP/preview.mobileprovision" + security cms -D -i "$RUNNER_TEMP/preview.mobileprovision" > "$RUNNER_TEMP/preview-profile.plist" + record="$(node .github/scripts/mobile-ios-preview-record.cjs create "$LINK" "$RUNNER_TEMP/preview-profile.plist")" + echo "record=$record" >> "$GITHUB_OUTPUT" + + # The tag is the record later runs look up. Android's message is the install + # link and is never replaced; iOS replaces an expired record for the fingerprint. + record: + name: Record build + needs: [android, ios] + if: ${{ !cancelled() && (needs.android.outputs.record != '' || needs.ios.outputs.record != '') }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 + permissions: + contents: write # pushes the build record tag + steps: + # The commit the build job built. No build ran in this checkout. + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Record build + uses: ./.github/actions/record-build-tag + with: + tag: mobile-${{ inputs.platform }}-preview-build/${{ inputs.fingerprint }} + message: ${{ needs.android.outputs.record || needs.ios.outputs.record }} + replace: ${{ inputs.platform == 'ios' }} + token: ${{ github.token }} diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index 890bd0c2aecd9..7a8d784f9d73d 100644 --- a/.github/workflows/mobile-eas-preview-fork.yml +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -43,12 +43,21 @@ jobs: NODE_OPTIONS: --max-old-space-size=8192 MOBILE_VERSION_POLICY: fingerprint steps: - # If a maintainer removed the label first, that removal wins. + # The label counts only from someone with write access, who could push a + # same-repo branch and get this build anyway. If a maintainer removed the + # label first, that removal wins. - id: consume name: Consume the deployment label uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | + const sender = context.payload.sender.login; + const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: sender, + }); + const authorized = ["admin", "maintain", "write"].includes(access.permission); try { await github.rest.issues.removeLabel({ owner: context.repo.owner, @@ -56,12 +65,16 @@ jobs: issue_number: context.payload.pull_request.number, name: context.payload.label.name, }); - core.setOutput("consumed", "true"); } catch (error) { if (error.status !== 404) throw error; core.info("The label was removed before this run could consume it. Skipping."); core.setOutput("consumed", "false"); + return; } + if (!authorized) { + core.warning(`${sender} has ${access.permission} access; a fork preview needs write access. Label removed, nothing built.`); + } + core.setOutput("consumed", String(authorized)); - id: expo-token name: Check for EXPO_PREVIEW_TOKEN diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index 53061f25e9c48..5aeb32d647763 100644 --- a/.github/workflows/mobile-eas-preview.yml +++ b/.github/workflows/mobile-eas-preview.yml @@ -247,181 +247,43 @@ jobs: group="$(eas update --auto --branch "pr-$PR" --platform android --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" echo "group=$group" >> "$GITHUB_OUTPUT" + # Each build runs in mobile-eas-preview-build.yml, whose record job alone gets + # the token that pushes the tag. The group covers both of its jobs. android-build: name: Android preview client needs: android if: needs.android.outputs.build == 'true' - runs-on: blacksmith-32vcpu-ubuntu-2404 - timeout-minutes: 60 concurrency: # One build per fingerprint; a second PR with the same one finds the tag. group: mobile-android-preview-build-${{ needs.android.outputs.fingerprint }} cancel-in-progress: false queue: max permissions: - contents: write # pushes the build record tag - pull-requests: write - outputs: - client: ${{ steps.build.outputs.link || steps.record.outputs.link }} - env: - APP_VARIANT: preview - NODE_OPTIONS: --max-old-space-size=8192 - MOBILE_VERSION_POLICY: fingerprint - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - FINGERPRINT: ${{ needs.android.outputs.fingerprint }} - BUILD_TAG: mobile-android-preview-build/${{ needs.android.outputs.fingerprint }} - # Phones only: emulators use the development client from the native-client cache. - ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - fetch-depth: 0 - - - id: record - name: Check build record - run: | - if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" - fi - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: android - profile: preview:dev - environment: preview - expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - output: ${{ runner.temp }}/t3code-preview.apk - - # `eas upload` hosts the APK on EAS and returns the page testers install from. - - id: build - name: Upload - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - shell: bash - run: | - eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" - link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" - if [ -z "$link" ]; then - echo "::error::eas upload returned no install link" - exit 1 - fi - echo "link=$link" >> "$GITHUB_OUTPUT" - echo "### Android preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - - # The tag is the record later runs look up; its message is the install link. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - message: ${{ steps.build.outputs.link }} - token: ${{ github.token }} + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-preview-build.yml + with: + platform: android + fingerprint: ${{ needs.android.outputs.fingerprint }} + secrets: + EXPO_PREVIEW_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} ios-build: name: iOS preview client needs: ios if: needs.ios.outputs.build == 'true' - runs-on: blacksmith-12vcpu-macos-27 - timeout-minutes: 60 concurrency: # One build per fingerprint; a second PR with the same one finds the tag. group: mobile-ios-preview-build-${{ needs.ios.outputs.fingerprint }} cancel-in-progress: false queue: max permissions: - contents: write # pushes the build record tag - pull-requests: write - outputs: - client: ${{ steps.build.outputs.link || steps.record.outputs.link }} - env: - APP_VARIANT: preview - NODE_OPTIONS: --max-old-space-size=8192 - MOBILE_VERSION_POLICY: fingerprint - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - FINGERPRINT: ${{ needs.ios.outputs.fingerprint }} - BUILD_TAG: mobile-ios-preview-build/${{ needs.ios.outputs.fingerprint }} - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - fetch-depth: 0 - - - name: Setup Node - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - id: record - name: Check build record - run: | - if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then - link="$(git tag -l --format='%(contents)' "$BUILD_TAG" | node .github/scripts/mobile-ios-preview-record.cjs read)" - if [ -n "$link" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo "link=$link" >> "$GITHUB_OUTPUT" - fi - fi - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: ios - profile: preview:dev - environment: preview - expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - output: ${{ runner.temp }}/t3code-preview.ipa - - # EAS hosts the signed client and returns its install page. - - id: build - name: Upload - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - shell: bash - run: | - eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" - link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" - if [ -z "$link" ]; then - echo "::error::eas upload returned no install link" - exit 1 - fi - echo "link=$link" >> "$GITHUB_OUTPUT" - echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - - # The tag stores the install link and provisioning-profile expiry. - - id: profile - name: Read the provisioning profile - if: steps.record.outputs.built != 'true' - env: - LINK: ${{ steps.build.outputs.link }} - run: | - profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | grep -E '^Payload/[^/]+\.app/embedded\.mobileprovision$')" - unzip -p "$RUNNER_TEMP/t3code-preview.ipa" "$profile_path" > "$RUNNER_TEMP/preview.mobileprovision" - security cms -D -i "$RUNNER_TEMP/preview.mobileprovision" > "$RUNNER_TEMP/preview-profile.plist" - record="$(node .github/scripts/mobile-ios-preview-record.cjs create "$LINK" "$RUNNER_TEMP/preview-profile.plist")" - echo "record=$record" >> "$GITHUB_OUTPUT" - - # Replaces an expired record for the same fingerprint. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - message: ${{ steps.profile.outputs.record }} - replace: "true" - token: ${{ github.token }} + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-preview-build.yml + with: + platform: ios + fingerprint: ${{ needs.ios.outputs.fingerprint }} + secrets: + EXPO_PREVIEW_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} comment: name: Mobile preview comment diff --git a/.github/workflows/mobile-eas-production-build.yml b/.github/workflows/mobile-eas-production-build.yml new file mode 100644 index 0000000000000..54289e4dc7e72 --- /dev/null +++ b/.github/workflows/mobile-eas-production-build.yml @@ -0,0 +1,196 @@ +name: Mobile EAS Production Build + +# One store build and its build record, called per platform by +# mobile-eas-production.yml. The build job runs dependency and build scripts with +# a read-only token. Only the record job, on a fresh runner that runs none of +# them, gets the token that can push tags. The caller's concurrency group covers +# both jobs, so a queued run for the same fingerprint starts after the tag exists. + +on: + workflow_call: + inputs: + platform: + description: android or ios + required: true + type: string + profile: + description: eas.json build and submit profile + required: true + type: string + sha: + description: Commit to build and tag + required: true + type: string + tag: + description: Build record tag, without refs/tags/ + required: true + type: string + secrets: + EXPO_PRODUCTION_TOKEN: + required: true + MOBILE_SOURCEMAPS_R2: + required: false + +jobs: + # ARM-only, without release lint (see the production profile in eas.json), + # with Gradle, ccache, and pnpm state on a sticky disk. + android: + name: Build + if: ${{ !cancelled() && inputs.platform == 'android' }} + runs-on: blacksmith-32vcpu-ubuntu-2404 + timeout-minutes: 60 + permissions: + contents: read + outputs: + submitted: ${{ steps.submit.outcome == 'success' }} + env: + APP_VARIANT: production + NODE_OPTIONS: --max-old-space-size=8192 + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + BUILD_TAG: ${{ inputs.tag }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ inputs.sha }} + fetch-depth: 0 + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + # A queued run can follow a build of the same fingerprint; manual runs always build. + - id: record + name: Check build record + env: + FORCE: ${{ github.event_name == 'workflow_dispatch' }} + run: | + if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: android + profile: production + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.aab + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - name: Check ABIs + if: steps.record.outputs.built != 'true' + run: | + abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" + echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" + if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then + echo "::error::Expected only ARM native libraries in the AAB, found $abis" + exit 1 + fi + + # A --path submission doesn't keep its archive on EAS; this is the only downloadable copy. + - name: Keep the AAB + if: steps.record.outputs.built != 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: android-store-aab-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/t3code.aab + retention-days: 14 + if-no-files-found: error + + - id: submit + name: Submit to Google Play + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + run: eas submit --platform android --profile production --path "$RUNNER_TEMP/t3code.aab" --non-interactive + + # No sticky disk: it mounts ext4 and only works on Linux runners. + ios: + name: Build + if: ${{ !cancelled() && inputs.platform == 'ios' }} + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + permissions: + contents: read + outputs: + submitted: ${{ steps.submit.outcome == 'success' }} + env: + APP_VARIANT: production + NODE_OPTIONS: --max-old-space-size=8192 + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + PROFILE: ${{ inputs.profile }} + BUILD_TAG: ${{ inputs.tag }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ inputs.sha }} + fetch-depth: 0 + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + # A queued run can follow a build of the same fingerprint; manual runs always build. + - id: record + name: Check build record + env: + FORCE: ${{ github.event_name == 'workflow_dispatch' }} + run: | + if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo ":white_check_mark: ios: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: ios + profile: ${{ env.PROFILE }} + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.ipa + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - id: submit + name: Submit to App Store Connect + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + run: eas submit --platform ios --profile "$PROFILE" --path "$RUNNER_TEMP/t3code.ipa" --non-interactive + + # The tag means "delivered", so it follows the submit. If it can't be + # pushed, the next merge rebuilds with a new build number; nothing is lost. + record: + name: Record build + needs: [android, ios] + if: ${{ !cancelled() && (needs.android.outputs.submitted == 'true' || needs.ios.outputs.submitted == 'true') }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 + permissions: + contents: write # pushes the build record tag + env: + BUILD_TAG: ${{ inputs.tag }} + steps: + # The workflow's own commit, so the action below is this workflow's. The + # built commit is passed as data. + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Record build + uses: ./.github/actions/record-build-tag + with: + tag: ${{ inputs.tag }} + commit: ${{ inputs.sha }} + token: ${{ github.token }} + + - name: Summarize + env: + PLATFORM: ${{ inputs.platform }} + run: | + echo ":rocket: $PLATFORM: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index fe4d7456acdf4..0bfe62444d81b 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -68,6 +68,7 @@ on: - pnpm-lock.yaml - pnpm-workspace.yaml - .github/workflows/mobile-eas-production.yml + - .github/workflows/mobile-eas-production-build.yml jobs: production: @@ -83,6 +84,7 @@ jobs: permissions: contents: read outputs: + version_override: ${{ steps.version_override.outputs.applied }} android_build: ${{ steps.reconcile.outputs.android_build || steps.android_manual.outputs.android_build }} android_fingerprint: ${{ steps.reconcile.outputs.android_fingerprint || steps.android_manual.outputs.android_fingerprint }} android_version: ${{ steps.reconcile.outputs.android_version || steps.android_manual.outputs.android_version }} @@ -119,21 +121,11 @@ jobs: echo "EXPO_PRODUCTION_TOKEN is not available; skipping EAS production job." fi - - id: version_app_token - name: Mint release app token for version override - if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != '' && inputs.profile != 'testflight' - uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 - with: - app-id: ${{ secrets.RELEASE_APP_ID }} - private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} - owner: ${{ github.repository_owner }} - - name: Checkout if: steps.expo-token.outputs.present == 'true' uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 - token: ${{ steps.version_app_token.outputs.token || github.token }} # No sparse-checkout here: it makes actions/checkout fetch with # --filter=blob:none, and eas-cli archives the project via # `git clone --depth 1 file://`, which fails (exit 128) @@ -188,48 +180,21 @@ jobs: appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); NODE - - name: Apply manual version override - if: steps.version_app_token.outcome == 'success' + # Only so the versions and fingerprints below are read from the tree that + # will be built. This job installs dependencies, so it gets no token that can + # push: the version job makes the same commit as the Release App afterwards. + - id: version_override + name: Apply manual version override + if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != '' && inputs.profile != 'testflight' env: - GH_TOKEN: ${{ steps.version_app_token.outputs.token }} - APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }} RELEASE_VERSION: ${{ inputs.version }} run: | - if [ "$GITHUB_REF_TYPE" != "branch" ]; then - echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2 - exit 1 - fi - if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then - echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2 - exit 1 + node .github/scripts/set-mobile-version.cjs "$RELEASE_VERSION" + if ! git diff --quiet -- apps/mobile/app.config.ts; then + git -c user.name=mobile-version -c user.email=mobile-version@users.noreply.github.com \ + commit --no-verify --quiet -m "chore(mobile): bump app version to $RELEASE_VERSION" -- apps/mobile/app.config.ts fi - - node --input-type=module -e ' - import fs from "node:fs"; - const path = "apps/mobile/app.config.ts"; - const source = fs.readFileSync(path, "utf8"); - const next = source.replace( - /^( version: repoEnv\.T3CODE_MOBILE_VERSION \?\? ")[^"]+(".*)$/m, - `$1${process.env.RELEASE_VERSION}$2`, - ); - if (next === source && !source.includes(` version: repoEnv.T3CODE_MOBILE_VERSION ?? "${process.env.RELEASE_VERSION}"`)) { - throw new Error("Could not update app version"); - } - fs.writeFileSync(path, next); - ' - vp fmt apps/mobile/app.config.ts - - if git diff --quiet -- apps/mobile/app.config.ts; then - echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed." - exit 0 - fi - - user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)" - git config user.name "${APP_SLUG}[bot]" - git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" - git add apps/mobile/app.config.ts - git commit --no-verify -m "chore(mobile): bump app version to $RELEASE_VERSION" - git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}" + echo "applied=true" >> "$GITHUB_OUTPUT" - name: Summarize manual build version if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' @@ -453,165 +418,95 @@ jobs: fi done - # ARM-only, without release lint (see the production profile in eas.json), - # with Gradle, ccache, and pnpm state on a sticky disk. Its own concurrency - # group keeps later OTAs from waiting on it. - android: - name: Android store build + # Commits a store version override as the Release App. It installs nothing and + # runs no dependency code, so that token never shares a runner with any. It + # runs after the production job so the push's own run queues behind this one. + version: + name: Commit version override needs: production - # Skipped when the production job failed: no store build after a failed OTA. - if: needs.production.outputs.android_build == 'true' - runs-on: blacksmith-32vcpu-ubuntu-2404 - timeout-minutes: 60 - concurrency: - group: mobile-android-store-build - cancel-in-progress: false + if: ${{ !cancelled() && needs.production.result == 'success' && needs.production.outputs.version_override == 'true' }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 permissions: - contents: write # pushes the build record tag - env: - APP_VARIANT: production - NODE_OPTIONS: --max-old-space-size=8192 - EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - BUILD_TAG: mobile-android-build/${{ needs.production.outputs.android_version }}/${{ needs.production.outputs.android_fingerprint }} + contents: read + outputs: + sha: ${{ steps.commit.outputs.sha }} steps: + # No owner input: the token covers this repository only, with contents write. + - id: app_token + name: Mint release app token + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 + with: + app-id: ${{ secrets.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + permission-contents: write + - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ needs.production.outputs.android_sha }} - fetch-depth: 0 + token: ${{ steps.app_token.outputs.token }} - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - # A queued run can follow a build of the same fingerprint; manual runs always build. - - id: record - name: Check build record + - id: commit + name: Commit and push the version env: - FORCE: ${{ github.event_name == 'workflow_dispatch' }} - run: | - if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: android - profile: production - environment: production - expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - output: ${{ runner.temp }}/t3code.aab - sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - - - name: Check ABIs - if: steps.record.outputs.built != 'true' + GH_TOKEN: ${{ steps.app_token.outputs.token }} + APP_SLUG: ${{ steps.app_token.outputs.app-slug }} + RELEASE_VERSION: ${{ inputs.version }} run: | - abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" - echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" - if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then - echo "::error::Expected only ARM native libraries in the AAB, found $abis" - exit 1 + node .github/scripts/set-mobile-version.cjs "$RELEASE_VERSION" + if git diff --quiet -- apps/mobile/app.config.ts; then + echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed." + else + user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)" + git config user.name "${APP_SLUG}[bot]" + git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" + git add apps/mobile/app.config.ts + git commit --no-verify -m "chore(mobile): bump app version to $RELEASE_VERSION" + git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}" fi + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - # A --path submission doesn't keep its archive on EAS; this is the only downloadable copy. - - name: Keep the AAB - if: steps.record.outputs.built != 'true' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: android-store-aab-${{ github.run_id }}-${{ github.run_attempt }} - path: ${{ runner.temp }}/t3code.aab - retention-days: 14 - if-no-files-found: error - - - name: Submit to Google Play - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: eas submit --platform android --profile production --path "$RUNNER_TEMP/t3code.aab" --non-interactive - - # The tag means "delivered", so it follows the submit. If it can't be - # pushed, the next merge rebuilds with a new build number; nothing is lost. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - token: ${{ github.token }} - - - name: Summarize - if: steps.record.outputs.built != 'true' - run: | - echo ":rocket: android: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" + # Each store build runs in mobile-eas-production-build.yml, whose record job + # alone gets the token that pushes the tag. The group covers both of its jobs, + # and being its own group keeps later OTAs from waiting on a build. + android: + name: Android store build + needs: [production, version] + # Skipped when the production job failed: no store build after a failed OTA. + # The version job is skipped unless there is an override. + if: ${{ !cancelled() && needs.production.result == 'success' && needs.version.result != 'failure' && needs.production.outputs.android_build == 'true' }} + concurrency: + group: mobile-android-store-build + cancel-in-progress: false + permissions: + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-production-build.yml + with: + platform: android + profile: production + sha: ${{ needs.version.outputs.sha || needs.production.outputs.android_sha }} + tag: mobile-android-build/${{ needs.production.outputs.android_version }}/${{ needs.production.outputs.android_fingerprint }} + secrets: + EXPO_PRODUCTION_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - # No sticky disk: it mounts ext4 and only works on Linux runners. ios: name: iOS store build - needs: production + needs: [production, version] # Skipped when the production job failed: no store build after a failed OTA. - if: needs.production.outputs.ios_build == 'true' - runs-on: blacksmith-12vcpu-macos-27 - timeout-minutes: 60 + # The version job is skipped unless there is an override. + if: ${{ !cancelled() && needs.production.result == 'success' && needs.version.result != 'failure' && needs.production.outputs.ios_build == 'true' }} concurrency: group: mobile-ios-store-build cancel-in-progress: false permissions: - contents: write # pushes the build record tag - env: - APP_VARIANT: production - NODE_OPTIONS: --max-old-space-size=8192 - EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - PROFILE: ${{ needs.production.outputs.ios_profile }} - BUILD_TAG: mobile-ios-build/${{ needs.production.outputs.ios_profile }}/${{ needs.production.outputs.ios_version }}/${{ needs.production.outputs.ios_fingerprint }} - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - ref: ${{ needs.production.outputs.ios_sha }} - fetch-depth: 0 - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - # A queued run can follow a build of the same fingerprint; manual runs always build. - - id: record - name: Check build record - env: - FORCE: ${{ github.event_name == 'workflow_dispatch' }} - run: | - if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo ":white_check_mark: ios: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: ios - profile: ${{ env.PROFILE }} - environment: production - expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - output: ${{ runner.temp }}/t3code.ipa - sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - - - name: Submit to App Store Connect - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: eas submit --platform ios --profile "$PROFILE" --path "$RUNNER_TEMP/t3code.ipa" --non-interactive - - # The tag means "delivered", so it follows the submit. If it can't be - # pushed, the next merge rebuilds with a new build number; nothing is lost. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - token: ${{ github.token }} - - - name: Summarize - if: steps.record.outputs.built != 'true' - run: | - echo ":rocket: ios: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-production-build.yml + with: + platform: ios + profile: ${{ needs.production.outputs.ios_profile }} + sha: ${{ needs.version.outputs.sha || needs.production.outputs.ios_sha }} + tag: mobile-ios-build/${{ needs.production.outputs.ios_profile }}/${{ needs.production.outputs.ios_version }}/${{ needs.production.outputs.ios_fingerprint }} + secrets: + EXPO_PRODUCTION_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8693e959055bf..92ec860dbe33c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1103,6 +1103,9 @@ jobs: if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel != 'preview' }} runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 15 + # npm's trusted publisher for `t3` names this environment, which admits only + # main and v* tags. + environment: production permissions: contents: read id-token: write @@ -1191,9 +1194,6 @@ jobs: T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }} T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }} T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }} - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} - VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} T3CODE_WEB_ROUTER_URL: ${{ vars.T3CODE_WEB_ROUTER_URL }} VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: @@ -1231,9 +1231,14 @@ jobs: - name: Refresh release lockfile run: vp install --lockfile-only --ignore-scripts + # The Vercel secrets are on this step only, not on the install above. - id: deploy name: Build staged deployment shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} run: | set -euo pipefail @@ -1364,8 +1369,6 @@ jobs: deployment_url: ${{ steps.deploy.outputs.deployment_url }} project_id: ${{ steps.deploy.outputs.project_id }} env: - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout @@ -1382,9 +1385,13 @@ jobs: with: install-args: --filter=@t3tools/marketing... + # The Vercel secrets are on this step only, not on the install above. - id: deploy name: Build staged deployment shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} run: | set -euo pipefail diff --git a/.github/workflows/web-preview.yml b/.github/workflows/web-preview.yml index 69db6b6025e8f..7d3f1efd57c13 100644 --- a/.github/workflows/web-preview.yml +++ b/.github/workflows/web-preview.yml @@ -39,11 +39,6 @@ jobs: (github.event.action != 'labeled' || github.event.label.name == 'preview:web') runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 - env: - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} - VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} - VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -54,6 +49,8 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false + # The Vercel CLI imports @vercel/config from here to read apps/web/vercel.ts. + # No dependency lifecycle script runs in this job. - name: Setup Vite+ uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: @@ -61,12 +58,18 @@ jobs: cache: true run-install: | args: + - --ignore-scripts - --filter=@t3tools/scripts... - --filter=@t3tools/web... - id: deploy name: Deploy preview shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} + VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} run: | set -euo pipefail diff --git a/docs/operations/03_release.md b/docs/operations/03_release.md index d213041d57eb5..73a63fdfd4dd3 100644 --- a/docs/operations/03_release.md +++ b/docs/operations/03_release.md @@ -47,7 +47,7 @@ Windows packages the bundled server and its unpacked native modules in `resource ### npm OIDC trusted publishing -Configure `t3` on npm with GitHub Actions Trusted Publishing for `.github/workflows/release.yml` (the workflow publishes only the `t3` launcher tarball via `npm publish --provenance`). +Configure `t3` on npm with GitHub Actions Trusted Publishing for `.github/workflows/release.yml` (the workflow publishes only the `t3` launcher tarball via `npm publish --provenance`). Set the publisher's environment to `production`, which `publish_cli` declares. ### Apple signing and notarization (macOS) From 784da01b2906aca88918c6221cb86fe332ab0f60 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 18:15:41 -0600 Subject: [PATCH 103/221] fix(web): Esc in Find in PDF clears it without closing the sheet (#41749) Co-authored-by: Julius Marminge --- .../files/PdfViewer.browser.test.tsx | 50 ++++++++++++++++++- apps/web/src/components/files/PdfViewer.tsx | 11 +++- 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/files/PdfViewer.browser.test.tsx b/apps/web/src/components/files/PdfViewer.browser.test.tsx index 81bf3bcf91364..1563088cf32f4 100644 --- a/apps/web/src/components/files/PdfViewer.browser.test.tsx +++ b/apps/web/src/components/files/PdfViewer.browser.test.tsx @@ -1,5 +1,8 @@ import { expect, it, vi } from "vite-plus/test"; -import { render } from "../../../test/render"; +import { userEvent } from "vite-plus/test/browser"; + +import { RightPanelSheet } from "~/components/RightPanelSheet"; +import { act, render } from "../../../test/render"; import "~/index.css"; // Vite serves the worker module through its transform with an inline source map (6.8 MB for @@ -333,3 +336,48 @@ it("follows a link to another page and exposes a web link", async () => { URL.revokeObjectURL(url); } }); + +it("Escape in Find in PDF clears it without closing the panel sheet", async () => { + const url = URL.createObjectURL(testPdf()); + const onCloseSheet = vi.fn(); + try { + await using screen = await render( + + + , + ); + const find = screen.getByRole("searchbox", { name: "Find in PDF" }); + await find.fill("quarterly"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + find.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + find + .element() + .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true })); + }); + await expect.element(find).toHaveValue("quarterly"); + } + expect(find.element().getAttribute("type")).toBe("text"); + + await userEvent.keyboard("{Escape}"); + await expect.element(find).toHaveValue(""); + // Holding Escape repeats the keydown, which must not also close the sheet. + await act(() => { + find + .element() + .dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true }), + ); + }); + expect(onCloseSheet).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + await vi.waitFor(() => expect(onCloseSheet).toHaveBeenCalledOnce()); + } finally { + URL.revokeObjectURL(url); + } +}); diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsx index 9842a621c0302..3f0368d67cfb4 100644 --- a/apps/web/src/components/files/PdfViewer.tsx +++ b/apps/web/src/components/files/PdfViewer.tsx @@ -522,10 +522,12 @@ export default function PdfViewer(props: {
+ {/* Native search inputs clear on Escape even during IME composition. */} { + if (event.key !== "Escape" || event.nativeEvent.isComposing || event.keyCode === 229) + return; + if (!query && !event.repeat) return; + event.stopPropagation(); + setQuery(""); + }} />
{query ? ( From e3b79cd0bf9cdffd8d7dff24f43e77704ee621b8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:17:50 -0800 Subject: [PATCH 104/221] fix: Windows system tools run by absolute path, and mobile links and shares are handled more strictly (#41767) Co-authored-by: Claude Fable 5.2 --- .../features/files/FileMarkdownPreview.tsx | 4 +- .../sharing/IncomingShareProvider.tsx | 30 +++++++----- .../sharing/incoming-share-model.test.ts | 29 +++++++++++ .../features/sharing/incoming-share-model.ts | 28 +++++++++++ apps/mobile/src/lib/appLinking.test.ts | 10 ++++ apps/mobile/src/lib/appLinking.ts | 9 +++- apps/mobile/src/lib/openExternalUrl.test.ts | 15 +++++- apps/mobile/src/lib/openExternalUrl.ts | 11 +++++ apps/mobile/src/native/useOpenPullRequest.ts | 6 +-- apps/server/src/background/KeepAwake.test.ts | 9 ++++ apps/server/src/background/KeepAwake.ts | 8 +-- apps/server/src/cli/uninstall.ts | 6 ++- apps/server/src/cloud/bootService.test.ts | 42 ++++++++-------- apps/server/src/cloud/bootService.ts | 24 +++++---- apps/server/src/cloud/pinnedRuntime.ts | 3 +- .../src/device/deviceToolMaintenance.ts | 2 +- apps/server/src/legacyServerOwner.ts | 9 +++- .../src/mcp/toolkits/project/handlers.test.ts | 10 +++- .../src/mcp/toolkits/project/handlers.ts | 49 ++++++++++++------- apps/server/src/preview/PortScanner.test.ts | 2 +- apps/server/src/preview/PortScanner.ts | 4 +- apps/server/src/process/SpawnWorker.ts | 13 +++-- apps/server/src/serverOwnership.ts | 2 +- apps/server/src/serviceLauncher.ts | 9 ++-- apps/server/src/terminal/Manager.ts | 3 +- apps/server/src/workspace/TaskFolders.ts | 3 +- apps/web/src/workspaceBasenameLookup.test.ts | 9 ++++ .../src/workspaceBasenameLookup.ts | 3 ++ .../src/server/AcpSessionRuntime.ts | 8 ++- packages/provider-pi/src/server/rpc.ts | 8 ++- packages/shared/package.json | 4 ++ packages/shared/src/windowsSystem.ts | 8 +++ 32 files changed, 291 insertions(+), 89 deletions(-) create mode 100644 packages/shared/src/windowsSystem.ts diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx index 23035511a5c2d..2e8d030d2b2f8 100644 --- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx +++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx @@ -16,7 +16,7 @@ import { import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { RefreshControl } from "../../components/ui/RefreshControl"; -import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; +import { tryOpenWebLink } from "../../lib/openExternalUrl"; import { FONT_FAMILIES } from "../../lib/fontFamilies"; import { resolveNativeMarkdownTypography } from "../../lib/appearancePreferences"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; @@ -228,7 +228,7 @@ export function FileMarkdownPreview(props: { openMedia(href, true); }; const onLinkPress = (href: string) => { - if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link"); + if (!openMedia(href)) void tryOpenWebLink(href, "markdown-link"); }; const refreshControl = props.onRefresh ? ( diff --git a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx index 134e92e62f43a..dcfc3b99643b6 100644 --- a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx +++ b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx @@ -18,7 +18,7 @@ import { CommonActions } from "@react-navigation/native"; import { buildIncomingShareDraft, - isShareFileUriUnderOwnedRoots, + isOwnedShareFileUri, selectIncomingShareAttachmentsForServer, type IncomingShareDestination, type IncomingShareDraft, @@ -98,19 +98,25 @@ async function readFileSize(uri: string): Promise { return new File(uri).size ?? null; } -async function removeOwnedFile(uri: string): Promise { +/** `persisted` marks a copy this app saved itself, which needs no ownership check. */ +async function removeOwnedFile(uri: string, persisted = false): Promise { if (!uri.startsWith("file:")) { return; } try { const { File, Paths } = await import("expo-file-system"); // Delete only app-owned files; iOS open-in-place shares can reference the sender's original. - const ownedRootUris = [ - Paths.document.uri, - Paths.cache.uri, - ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri), - ]; - if (!isShareFileUriUnderOwnedRoots(uri, ownedRootUris)) { + const owned = + persisted || + isOwnedShareFileUri(uri, { + platform: Platform.OS, + cacheUri: Paths.cache.uri, + otherRootUris: [ + Paths.document.uri, + ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri), + ], + }); + if (!owned) { return; } const file = new File(uri); @@ -142,7 +148,7 @@ async function removeReplayedPayloadFiles(payloads: ReadonlyArray) uris.add(payload.contentUri); } } - await Promise.all([...uris].map(removeOwnedFile)); + await Promise.all([...uris].map((uri) => removeOwnedFile(uri))); } // Share the queue across remounts so lifecycle notifications cannot ingest one handoff twice. @@ -187,10 +193,12 @@ const incomingShareInbox = new IncomingShareInbox({ return { draft, cleanup: async () => { - await Promise.all([...cleanupUris].map(removeOwnedFile)); + await Promise.all( + [...cleanupUris].map((uri) => removeOwnedFile(uri, persistedUris.has(uri))), + ); }, rollback: async () => { - await Promise.all([...persistedUris].map(removeOwnedFile)); + await Promise.all([...persistedUris].map((uri) => removeOwnedFile(uri, true))); }, }; }, 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 7ca92b23c3208..7cab7a84da14e 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -8,6 +8,7 @@ import type { ResolvedSharePayload, SharePayload } from "expo-sharing"; import { buildIncomingShareDraft, hasIncomingShareContent, + isOwnedShareFileUri, isShareFileUriUnderOwnedRoots, selectIncomingShareAttachments, selectIncomingShareAttachmentsForServer, @@ -671,6 +672,34 @@ describe("share cleanup ownership", () => { ).toBe(false); }); + it("deletes only the resolver's share copies on Android", () => { + const data = "file:///data/user/0/codes.t3.app"; + const owned = (uri: string, platform = "android") => + isOwnedShareFileUri(uri, { + platform, + cacheUri: `${data}/cache/`, + otherRootUris: [`${data}/files/`], + }); + const copy = `${data}/cache/shared-0b0e3f0c-6c1d-4b53-9d0a-2f6f1c3a9e11`; + expect(owned(`file:${copy.slice("file://".length)}/report.pdf`)).toBe(true); + expect( + owned( + "file:///data/data/codes.t3.app/cache/shared-0b0e3f0c-6c1d-4b53-9d0a-2f6f1c3a9e11/a.png", + ), + ).toBe(true); + for (const uri of [ + `${data}/files/t3-composer-attachments/id-report.pdf`, + `${data}/files/SQLite/state.db`, + `${data}/cache/http-cache/journal`, + `${data}/cache/shared-notes/notes.txt`, + `${copy}/..%2F..%2Ffiles%2FSQLite%2Fstate.db`, + copy, + ]) { + expect(owned(uri)).toBe(false); + } + expect(owned(`${data}/files/SQLite/state.db`, "ios")).toBe(true); + }); + it("refuses non-file URIs and the owned root itself", () => { expect(isShareFileUriUnderOwnedRoots("content://shared/report", ownedRoots)).toBe(false); expect( diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 86c17c6059e0e..30a334ca46aaf 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -93,6 +93,34 @@ export function isShareFileUriUnderOwnedRoots( }); } +/** + * On Android only the native resolver's `shared-` copies are this app's to delete; other + * shared URIs are not copies. + */ +export function isOwnedShareFileUri( + uri: string, + owned: { + readonly platform: string; + readonly cacheUri: string; + readonly otherRootUris: ReadonlyArray; + }, +): boolean { + if (owned.platform !== "android") { + return isShareFileUriUnderOwnedRoots(uri, [owned.cacheUri, ...owned.otherRootUris]); + } + // The resolver reports its copy by canonical path, where `/data/user/0` is `/data/data`. + const canonical = (fileUri: string) => + normalizedFileUriPath(fileUri)?.replace(/^\/data\/user\/0\//, "/data/data/"); + const path = canonical(uri); + const cachePath = canonical(owned.cacheUri)?.replace(/\/*$/, "/"); + return ( + path !== undefined && + cachePath !== undefined && + path.startsWith(cachePath) && + /^shared-[\da-f-]{36}\/[^/]+$/i.test(path.slice(cachePath.length)) + ); +} + export interface IncomingShareFileReader { readonly readBase64: (uri: string) => Promise; readonly removeOwnedFile: (uri: string) => Promise | void; diff --git a/apps/mobile/src/lib/appLinking.test.ts b/apps/mobile/src/lib/appLinking.test.ts index 75db18a2337b8..09db1de62056a 100644 --- a/apps/mobile/src/lib/appLinking.test.ts +++ b/apps/mobile/src/lib/appLinking.test.ts @@ -91,6 +91,16 @@ describe("draft deep links", () => { }); }); + it.each(["/new/draft", "/new/draft/branch"])("drops the checkout a %s link names", (path) => { + const project = { environmentId: "env-1", projectId: "project-1" }; + const linked = { ...project, branch: "other", worktreePath: "/elsewhere" }; + const name = path === "/new/draft" ? "Thread" : "NewTaskBranch"; + expect(restoreDraftLinkState({ routes: [{ name, params: linked }] }, path)?.routes[0]).toEqual({ + name: "Thread", + params: { draft: project }, + }); + }); + it("leaves live-thread and project-selection links unchanged", () => { const state = { routes: [{ name: "Thread", params: { threadId: "thread-1" } }] }; expect(restoreDraftLinkState(state, "/threads/env-1/thread-1")).toBe(state); diff --git a/apps/mobile/src/lib/appLinking.ts b/apps/mobile/src/lib/appLinking.ts index 570c86b36abf4..fc448b4d02ac4 100644 --- a/apps/mobile/src/lib/appLinking.ts +++ b/apps/mobile/src/lib/appLinking.ts @@ -35,7 +35,14 @@ export function restoreDraftLinkState( if (!state || !pathname || !/^new\/draft(?:\/|$)/.test(pathname)) return state; const target = state.routes.at(-1); if (!target) return state; - const draft = target.params ?? {}; + // The draft screen checks out its branch on mount; the checkout comes from the draft, not the link. + const { + branch: _branch, + worktreePath: _worktreePath, + ...draft + } = (target.params ?? {}) as { + readonly [param: string]: unknown; + }; const routes = state.routes.slice(0, -1); routes.push({ name: "Thread", params: { draft } }); if (pathname !== "new/draft") routes.push(target); diff --git a/apps/mobile/src/lib/openExternalUrl.test.ts b/apps/mobile/src/lib/openExternalUrl.test.ts index 1dd1ff7db002b..f14037d99205f 100644 --- a/apps/mobile/src/lib/openExternalUrl.test.ts +++ b/apps/mobile/src/lib/openExternalUrl.test.ts @@ -1,7 +1,7 @@ import { Linking } from "react-native"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { tryOpenExternalUrl } from "./openExternalUrl"; +import { tryOpenExternalUrl, tryOpenWebLink } from "./openExternalUrl"; vi.mock("react-native", () => ({ Linking: { openURL: vi.fn() }, @@ -34,3 +34,16 @@ describe("tryOpenExternalUrl", () => { expect(diagnostics).not.toContain("43123"); }); }); + +describe("tryOpenWebLink", () => { + it("opens web, mail and phone links only", async () => { + openURL.mockResolvedValue(undefined); + for (const url of ["https://example.com/a", "HTTP://example.com", "mailto:a@example.com"]) { + await expect(tryOpenWebLink(url, "pull-request")).resolves.toBe(true); + } + for (const url of ["otherapp://open", "intent://x#Intent;end", "/owner/repo", ""]) { + await expect(tryOpenWebLink(url, "pull-request")).resolves.toBe(false); + } + expect(openURL).toHaveBeenCalledTimes(3); + }); +}); diff --git a/apps/mobile/src/lib/openExternalUrl.ts b/apps/mobile/src/lib/openExternalUrl.ts index 962769b184e33..d57442ac78045 100644 --- a/apps/mobile/src/lib/openExternalUrl.ts +++ b/apps/mobile/src/lib/openExternalUrl.ts @@ -61,3 +61,14 @@ export async function tryOpenExternalUrl( return false; } } + +/** + * For a link in rendered text, such as a pull request body: opens web, mail and phone links + * only. + */ +export async function tryOpenWebLink( + url: string, + target: ExternalUrlTarget = "external-link", +): Promise { + return /^(?:https?|mailto|tel):/i.test(url) && (await tryOpenExternalUrl(url, target)); +} diff --git a/apps/mobile/src/native/useOpenPullRequest.ts b/apps/mobile/src/native/useOpenPullRequest.ts index b492ece6fbef5..aac80fb3004a4 100644 --- a/apps/mobile/src/native/useOpenPullRequest.ts +++ b/apps/mobile/src/native/useOpenPullRequest.ts @@ -7,7 +7,7 @@ import { import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useProjects, useThreadShell } from "../state/entities"; -import { tryOpenExternalUrl } from "../lib/openExternalUrl"; +import { tryOpenWebLink } from "../lib/openExternalUrl"; import { appAtomRegistry } from "../state/atom-registry"; import { environmentServerConfigsAtom } from "../state/server"; import { issueTrackerEnvironment } from "../state/issueTrackers"; @@ -59,7 +59,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean trackers: connections?._tag === "Success" ? connections.value : undefined, }) : null; - if (!issue || !environmentId) return tryOpenExternalUrl(url, "pull-request"); + if (!issue || !environmentId) return tryOpenWebLink(url, "pull-request"); const candidate = pullRequestCandidateForIssueLink(url, issue.ref); if (candidate) { const preview = await readPreview({ environmentId, input: candidate.target }); @@ -76,7 +76,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean return true; } // A dropped connection says nothing about what the link names; the browser knows. - if (isAtomCommandInterrupted(preview)) return tryOpenExternalUrl(url, "pull-request"); + if (isAtomCommandInterrupted(preview)) return tryOpenWebLink(url, "pull-request"); } const issueParams = { environmentId, diff --git a/apps/server/src/background/KeepAwake.test.ts b/apps/server/src/background/KeepAwake.test.ts index 8984102729cec..628590930e470 100644 --- a/apps/server/src/background/KeepAwake.test.ts +++ b/apps/server/src/background/KeepAwake.test.ts @@ -34,3 +34,12 @@ describe("KeepAwake.holdWhileWanted", () => { }), ); }); + +describe("KeepAwake.inhibitorCommand", () => { + it("runs PowerShell by its System32 path on Windows", () => { + expect( + KeepAwake.inhibitorCommand("win32", 1, false, { SYSTEMROOT: String.raw`D:\Windows` }) + ?.command, + ).toBe(String.raw`D:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`); + }); +}); diff --git a/apps/server/src/background/KeepAwake.ts b/apps/server/src/background/KeepAwake.ts index f9d2cf3da7532..72e5c1fbf031b 100644 --- a/apps/server/src/background/KeepAwake.ts +++ b/apps/server/src/background/KeepAwake.ts @@ -14,6 +14,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; import { forkParked } from "../serverActivation.ts"; import * as Settings from "../serverSettings.ts"; @@ -27,10 +28,11 @@ const WINDOWS_HOLD_SCRIPT = `$t = Add-Type -Name Power -Namespace T3 -PassThru - * Each command writes a line to stdout once it holds its inhibitor, holds it until it exits, and * exits on its own if the server dies. */ -function inhibitorCommand( +export function inhibitorCommand( platform: NodeJS.Platform, serverPid: number, isWsl: boolean, + env: NodeJS.ProcessEnv, ): | { readonly command: string; @@ -77,7 +79,7 @@ function inhibitorCommand( }; case "win32": return { - command: "powershell.exe", + command: windowsPowerShellPath(env), args: [ "-NoProfile", "-NonInteractive", @@ -145,7 +147,7 @@ export const layer = Layer.effectDiscard( Effect.map((release) => release.toLowerCase().includes("microsoft")), Effect.orElseSucceed(() => false), )); - const command = inhibitorCommand(platform, process.pid, isWsl); + const command = inhibitorCommand(platform, process.pid, isWsl, yield* HostProcess.Environment); if (command === undefined) return; const settings = yield* Settings.ServerSettingsService; const events = yield* OrchestrationEventStore.OrchestrationEventStore; diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index ae884caa63fe7..07978299b4642 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -23,6 +23,7 @@ import { import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; import { awaitDetachedSpawn } from "../process/windowsVerbatimSpawn.ts"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { findWindowsShim } from "./update.ts"; export class CliUninstallError extends Schema.TaggedError()( @@ -281,7 +282,10 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { // Windows refuses to unlink this running executable; a detached shell removes it after exit. if (platform === "win32") { const runtimeDir = plan.runtimeDir; - const comspec = environment["ComSpec"] ?? environment["COMSPEC"] ?? "cmd.exe"; + const comspec = + environment["ComSpec"] ?? + environment["COMSPEC"] ?? + windowsSystem32Path(environment, "cmd.exe"); const notScheduled = () => new CliUninstallError({ reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`, diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index c327464ddfa24..309f90f4bd26a 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -53,6 +53,8 @@ vi.mock("node:fs", async (importOriginal) => { }; }); +const SCHTASKS = "C:\\Windows\\System32\\schtasks.exe"; + const windowsTaskOptions = { userId: "PC\\theo", homeDir: "C:\\Users\\theo", @@ -251,13 +253,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( command === "systemctl --user disable --now t3code.service" || command === "systemctl --user restart --no-block t3code.service" || command.startsWith("launchctl bootout --wait ") || - (input.command === "schtasks" && input.args[0] === "/End") + (input.command === SCHTASKS && input.args[0] === "/End") ) { markersAtStop.push(yield* fs.exists(marker)); } if ( command === "systemctl --user daemon-reload" || - (input.command === "schtasks" && input.args[0] === "/Create") + (input.command === SCHTASKS && input.args[0] === "/Create") ) { markersAtPreparation.push(yield* fs.exists(marker)); } @@ -276,8 +278,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( } if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true; const taskMissing = - input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined; - if (input.command === "schtasks" && !failed) { + input.command === SCHTASKS && input.args[0] !== "/Create" && control.task === undefined; + if (input.command === SCHTASKS && !failed) { if (input.args[0] === "/Create") { const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? "")); control.task = { xml, enabled: !serviceTaskIsDisabled(xml) }; @@ -318,7 +320,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( }) : input.args[0] === "--version" ? `t3 v${/versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n` - : input.command === "schtasks" && input.args.includes("/XML") + : input.command === SCHTASKS && input.args.includes("/XML") ? control.task?.enabled === false ? disabledServiceTask(control.task.xml) : (control.task?.xml ?? "") @@ -1581,9 +1583,9 @@ process.disconnect(); protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: "1.2.3", }); - expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual([ - `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, - "schtasks /Run /TN t3code-PC-theo", + expect(commands.filter((command) => command.startsWith(`${SCHTASKS} `))).toEqual([ + `${SCHTASKS} /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]); // No launcher holds the lock here. expect(yield* service.status).toMatchObject({ @@ -1593,7 +1595,7 @@ process.disconnect(); }); // A task that Task Scheduler refuses to delete stays installed, so a retry finds it. - control.failCommand = "schtasks /Delete /TN t3code-PC-theo /F"; + control.failCommand = `${SCHTASKS} /Delete /TN t3code-PC-theo /F`; expect((yield* service.uninstall.pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); expect((yield* service.status).installed).toBe(true); control.failCommand = undefined; @@ -1601,9 +1603,9 @@ process.disconnect(); commands.length = 0; expect(yield* service.uninstall).toBe(true); expect(commands).toEqual([ - "schtasks /Change /TN t3code-PC-theo /DISABLE", - "schtasks /End /TN t3code-PC-theo", - "schtasks /Delete /TN t3code-PC-theo /F", + `${SCHTASKS} /Change /TN t3code-PC-theo /DISABLE`, + `${SCHTASKS} /End /TN t3code-PC-theo`, + `${SCHTASKS} /Delete /TN t3code-PC-theo /F`, ]); expect(control.task).toBeUndefined(); expect((yield* service.status).installed).toBe(false); @@ -1643,11 +1645,11 @@ process.disconnect(); commands.length = 0; yield* service.withStopped(Effect.sync(() => commands.push("repair"))); expect(commands.filter((command) => !command.includes("/Query"))).toEqual([ - "schtasks /Change /TN t3code-PC-theo /DISABLE", - "schtasks /End /TN t3code-PC-theo", + `${SCHTASKS} /Change /TN t3code-PC-theo /DISABLE`, + `${SCHTASKS} /End /TN t3code-PC-theo`, "repair", - "schtasks /Change /TN t3code-PC-theo /ENABLE", - "schtasks /Run /TN t3code-PC-theo", + `${SCHTASKS} /Change /TN t3code-PC-theo /ENABLE`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]); }), ); @@ -1668,14 +1670,14 @@ process.disconnect(); const inside = yield* makeService(undefined, "1.2.4", undefined, true); const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`; const handoff = [ - `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, - "schtasks /End /TN t3code-PC-theo", - "schtasks /Run /TN t3code-PC-theo", + `${SCHTASKS} /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + `${SCHTASKS} /End /TN t3code-PC-theo`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]; commands.length = 0; expect(yield* inside.install()).toMatchObject({ handedOff: true, logPath: plan.logPath }); - expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual(handoff); + expect(commands.filter((command) => command.startsWith(`${SCHTASKS} `))).toEqual(handoff); expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.4"); expect( yield* fs.readFileString(`${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`), diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 90d01b10526f3..f95bae2a811aa 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -482,6 +482,8 @@ interface WindowsTaskSteps { readonly remove: Effect.Effect; } +const schtasksPath = (systemRoot: string) => `${systemRoot}\\System32\\schtasks.exe`; + function schtasksManager(input: { readonly path: Path.Path; readonly homeDir: string; @@ -489,13 +491,14 @@ function schtasksManager(input: { readonly steps: WindowsTaskSteps; }): BootServiceManager { const unitPath = scheduledTaskPath(input.path, input.session.localAppData); + const schtasks = schtasksPath(input.session.systemRoot); const task = ["/TN", input.session.taskName]; const register = { step: "registering the scheduled task", - command: "schtasks", + command: schtasks, args: ["/Create", "/XML", unitPath, ...task, "/F"], }; - const run = { step: "starting the service", command: "schtasks", args: ["/Run", ...task] }; + const run = { step: "starting the service", command: schtasks, args: ["/Run", ...task] }; const stop: ReadonlyArray = [ { step: "disabling the scheduled task", run: input.steps.disable }, { @@ -519,7 +522,7 @@ function schtasksManager(input: { restart: [ { step: "enabling the scheduled task", - command: "schtasks", + command: schtasks, args: ["/Change", ...task, "/ENABLE"], }, { ...run, step: "restarting the service after a failed update" }, @@ -531,7 +534,7 @@ function schtasksManager(input: { restart: [ { step: "ending the scheduled task", - command: "schtasks", + command: schtasks, args: ["/End", ...task], optional: true, }, @@ -903,6 +906,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { Option.getOrUndefined(Option.flatMapNullishOr(unit, bootServiceBaseDirOf)) ?? input.baseDir, ); const windowsTask = ["/TN", windowsSession.taskName]; + const schtasks = schtasksPath(windowsSession.systemRoot); /** Runs a command that changes the task; a task that is not registered has nothing to change. */ const changeWindowsTask = Effect.fn("cloud.boot_service.change_windows_task")(function* ( step: string, @@ -911,12 +915,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ) { const toError = (cause: unknown) => new BootServiceCommandError({ step, cause }); const changed = yield* runner - .run({ command: "schtasks", args: [verb, ...windowsTask, flag] }) + .run({ command: schtasks, args: [verb, ...windowsTask, flag] }) .pipe(Effect.mapError(toError)); if (changed.code === 0) return; const queried = yield* runner .run({ - command: "schtasks", + command: schtasks, args: ["/Query", ...windowsTask, "/HRESULT"], timeout: Duration.seconds(5), }) @@ -951,14 +955,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { unit: string, ) { const register = (xmlPath: string) => - runStep("registering the scheduled task", "schtasks", [ + runStep("registering the scheduled task", schtasks, [ "/Create", "/XML", xmlPath, ...windowsTask, "/F", ]); - const registered = yield* probe("schtasks", ["/Query", ...windowsTask, "/XML"]); + const registered = yield* probe(schtasks, ["/Query", ...windowsTask, "/XML"]); if ( Option.isSome(registered) && registered.value.code === 0 && @@ -981,7 +985,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // Task Scheduler then reports the task stopped at once, so the lock says when it really is. const stopWindowsLauncher = Effect.gen(function* () { const unit = yield* readUnit().pipe(Effect.option); - yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore); + yield* runner.run({ command: schtasks, args: ["/End", ...windowsTask] }).pipe(Effect.ignore); yield* Effect.tryPromise({ try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal), catch: (cause) => @@ -1215,7 +1219,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ) { const [task, running] = yield* Effect.all( [ - probe("schtasks", ["/Query", "/TN", windowsSession.taskName, "/XML"]), + probe(schtasks, ["/Query", "/TN", windowsSession.taskName, "/XML"]), Effect.promise(() => serviceLauncherIsRunning(launcherLockPath(unit))), ], { concurrency: "unbounded" }, diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index e544852ef3dcc..06e320bc314ad 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -25,6 +25,7 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts"; const PINNED_RUNTIME_DIR = "runtime"; @@ -792,7 +793,7 @@ const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables") .run({ ...(platform === "win32" ? { - command: "powershell.exe", + command: windowsPowerShellPath(yield* HostProcess.Environment), args: [ "-NoProfile", "-NonInteractive", diff --git a/apps/server/src/device/deviceToolMaintenance.ts b/apps/server/src/device/deviceToolMaintenance.ts index 2832071d099d0..7ff3a961eee9d 100644 --- a/apps/server/src/device/deviceToolMaintenance.ts +++ b/apps/server/src/device/deviceToolMaintenance.ts @@ -65,7 +65,7 @@ function pruneTools(root, specs, flat) { return withToolMaintenance(root, () => { // Keep installs used by any running helper, including older T3 releases. const scan = process.platform === 'win32' - ? require('node:child_process').spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine'], { encoding: 'utf8', timeout: 10000 }) + ? require('node:child_process').spawnSync((process.env.SystemRoot || process.env.windir || 'C:\\Windows') + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine'], { encoding: 'utf8', timeout: 10000 }) : require('node:child_process').spawnSync('ps', ['-ax', '-o', 'command='], { encoding: 'utf8', timeout: 10000 }); if (scan.status !== 0 || !scan.stdout) return; for (const [name, required] of specs) { diff --git a/apps/server/src/legacyServerOwner.ts b/apps/server/src/legacyServerOwner.ts index 9ed24c9c838f2..0b0b195ad38e7 100644 --- a/apps/server/src/legacyServerOwner.ts +++ b/apps/server/src/legacyServerOwner.ts @@ -1,9 +1,14 @@ // Effect-free so the service launcher shares the pre-lock owner identity check with server startup. +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; -export const legacyOwnerStartTimeCommand = (pid: number, platform: NodeJS.Platform) => { +export const legacyOwnerStartTimeCommand = ( + pid: number, + platform: NodeJS.Platform, + hostEnv: NodeJS.ProcessEnv, +) => { const windows = platform === "win32"; return { - command: windows ? "powershell.exe" : "ps", + command: windows ? windowsPowerShellPath(hostEnv) : "ps", args: windows ? [ "-NoProfile", diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index d03b038ee0780..37fbdcf12cbf8 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -567,10 +567,14 @@ it.effect("a launch binds only an existing checkout that is one of the project's Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" }); + // Git registers resolved paths, and a launch keeps the registered one. + const root = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" }), + ); const repo = path.join(root, "repo"); const worktree = path.join(root, "feature"); const outside = path.join(root, "outside"); + const alias = path.join(root, "alias"); yield* fileSystem.makeDirectory(repo); yield* fileSystem.makeDirectory(outside); @@ -615,9 +619,13 @@ it.effect("a launch binds only an existing checkout that is one of the project's code: "invalid_request", }); } + // The thread keeps the registered worktree path when launched through a link to it. + yield* fileSystem.symlink(worktree, alias); + expect((yield* launchInto(alias)).at(-1)?.result).toMatchObject({ projectId }); expect(launched.map((launch) => launch.workspaceStrategy)).toEqual([ { type: "existing_worktree", worktreePath: worktree }, { type: "existing_worktree", worktreePath: repo }, + { type: "existing_worktree", worktreePath: worktree }, ]); yield* fileSystem.remove(worktree, { recursive: true }); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 511dcfe26c3df..f92df228a422f 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -87,24 +87,29 @@ function worktreeCheckHint( }`; } -/** Require project worktrees so launches cannot target arbitrary host directories. */ -const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* ( +/** + * Require project worktrees so launches cannot target arbitrary host directories. Returns the + * path Git registered, so the thread stays bound to that worktree. + */ +const projectWorktreePath = Effect.fn("mcp.assertProjectWorktree")(function* ( workspaceRoot: string, worktreePath: string, ) { const git = yield* GitVcsDriver.GitVcsDriver; const fileSystem = yield* FileSystem.FileSystem; const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path)); - const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe( - Effect.flatMap((paths) => Effect.forEach(paths, real)), - Effect.orElseSucceed((): ReadonlyArray => []), - ); - if (!worktrees.includes(yield* real(worktreePath))) - return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: - "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.", - }); + const registered = yield* git + .listWorktreePaths(workspaceRoot) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + const requested = yield* real(worktreePath); + for (const candidate of registered) { + if ((yield* real(candidate)) === requested) return candidate; + } + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.", + }); }); /** The composer falls back to the project's t3.json when no setting picks the mode. */ @@ -307,15 +312,23 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { }), ), ); - if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree") - yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath); + const workspaceStrategy = + project !== undefined && input.workspaceStrategy?.type === "existing_worktree" + ? { + ...input.workspaceStrategy, + worktreePath: yield* projectWorktreePath( + project.workspaceRoot, + input.workspaceStrategy.worktreePath, + ), + } + : input.workspaceStrategy; if (!replaying && input.modelSelection !== undefined) { const { instanceId, model } = input.modelSelection; const registry = yield* ProviderRegistry.ProviderRegistry; // The thread runs in this folder, whose own provider config can add models. const cwd = - input.workspaceStrategy?.type === "existing_worktree" - ? input.workspaceStrategy.worktreePath + workspaceStrategy?.type === "existing_worktree" + ? workspaceStrategy.worktreePath : project?.workspaceRoot; const requireModel = ( providers: ReadonlyArray, @@ -357,14 +370,14 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { // An outside caller that names no workspace follows the new-threads-in-a-worktree // default, as the composer does. const requestedStrategy = - input.workspaceStrategy === undefined && + workspaceStrategy === undefined && caller === undefined && project !== undefined && projectSettings !== undefined && (projectSettings.defaultThreadEnvMode ?? (yield* projectFileThreadEnvMode(project.workspaceRoot))) === "worktree" ? yield* defaultWorktreeStrategy(project.workspaceRoot) - : input.workspaceStrategy; + : workspaceStrategy; // An omitted startFromOrigin follows the new-worktree setting, as the composer and // t3_worktree_handoff do. Otherwise a stale local branch silently becomes the base. const strategy = diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index 52636a342900f..b7f2f139e2011 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -685,7 +685,7 @@ effectIt.effect("ignores a partial Windows netstat snapshot when one query exits layerNoProc, Layer.succeed(ProcessRunner.ProcessRunner, { run: (input) => { - if (input.command === "tasklist.exe") { + if (input.command === String.raw`C:\Windows\System32\tasklist.exe`) { return Effect.succeed( processOutput('"node.exe","1234","Console","1","50,000 K"\r\n'), ); diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index db5dd3fa9e654..bbbd6bf53db92 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { isLoopbackHost, LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; @@ -845,12 +846,13 @@ export const make = Effect.gen(function* PortDiscoveryMake() { ); const cachedPids = new Set(cached.map(([pid]) => pid)); const expiresAtMillis = nowMillis + WINDOWS_PROCESS_NAME_TTL_MS; + const tasklist = windowsSystem32Path(yield* HostProcess.Environment, "tasklist.exe"); const fetched = yield* Effect.forEach( [...pids].filter((pid) => !cachedPids.has(pid)), (pid) => processRunner .run({ - command: "tasklist.exe", + command: tasklist, args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`], timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS), maxOutputBytes: 64 * 1024, diff --git a/apps/server/src/process/SpawnWorker.ts b/apps/server/src/process/SpawnWorker.ts index 5a391ab18ca1b..58373b5bdc0a8 100644 --- a/apps/server/src/process/SpawnWorker.ts +++ b/apps/server/src/process/SpawnWorker.ts @@ -8,6 +8,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { supportsEnvChdir } from "@t3tools/shared/envTrampoline"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; // Windows runs CreateProcess synchronously on the calling thread, and antivirus or a busy disk can // hold it for seconds; Linux's spawn waits for chdir and the PATH search, which a hung mount @@ -503,10 +504,14 @@ class SpawnWorkerPool { if (!killed) killPid(); done(); }; - this.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { - stdio: "ignore", - windowsHide: true, - }) + this.spawn( + windowsSystem32Path(process.env, "taskkill.exe"), + ["/pid", String(pid), "/T", "/F"], + { + stdio: "ignore", + windowsHide: true, + }, + ) .on("error", () => finish(false)) .on("exit", (code) => finish(code === 0)); } diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts index 20bb46a45e66e..c39c4ee4428ff 100644 --- a/apps/server/src/serverOwnership.ts +++ b/apps/server/src/serverOwnership.ts @@ -88,7 +88,7 @@ const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* ( const runner = yield* ProcessRunner.ProcessRunner; const result = yield* runner .run({ - ...legacyOwnerStartTimeCommand(state.pid, platform), + ...legacyOwnerStartTimeCommand(state.pid, platform, yield* HostProcess.Environment), timeout: Duration.seconds(2), maxOutputBytes: 16_384, }) diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 44220f2c4b148..61e52b19d63f6 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -9,6 +9,7 @@ import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; import { acquireServiceSelectionLock } from "./cloud/serviceSelectionLock.ts"; import { RESTORE_OOMD_WATCH_SCRIPT } from "./cloud/userManagerOom.ts"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { isNoCopyOnWrite, markNoCopyOnWrite } from "./noCopyOnWrite.ts"; import type { @@ -137,8 +138,10 @@ export interface ServiceUnit { readonly reload: () => Promise; } +const SCHTASKS = () => windowsSystem32Path(process.env, "schtasks.exe"); + const runSchtasks = (...args: ReadonlyArray) => - NodeUtil.promisify(NodeChildProcess.execFile)("schtasks", args, { + NodeUtil.promisify(NodeChildProcess.execFile)(SCHTASKS(), args, { windowsHide: true, timeout: 30_000, }); @@ -880,7 +883,7 @@ export async function stateDirOwned(baseDir: string): Promise { if (!Number.isFinite(recordedAt)) return true; // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. const platform = process.platform; - const { command, args, env } = legacyOwnerStartTimeCommand(pid, platform); + const { command, args, env } = legacyOwnerStartTimeCommand(pid, platform, process.env); const output = await new Promise((resolve) => NodeChildProcess.execFile( command, @@ -1654,7 +1657,7 @@ export async function main(options: LauncherOptions = {}): Promise { // lets the next repeating trigger start the service again. if (windows && options.serviceUnit !== undefined) { const taskName = serviceTaskName(process.env.USERDOMAIN ?? "", process.env.USERNAME ?? ""); - NodeChildProcess.spawnSync("schtasks", ["/End", "/TN", taskName], { + NodeChildProcess.spawnSync(SCHTASKS(), ["/End", "/TN", taskName], { stdio: "ignore", windowsHide: true, }); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 92600d0a326a8..a27f6b1d03447 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -918,11 +918,12 @@ const windowsProcessTableSnapshot = Effect.fn("terminal.windowsProcessTableSnaps ProcessRunner.ProcessRunner > { const processRunner = yield* ProcessRunner.ProcessRunner; + const powershell = windowsPowerShellPath(yield* HostProcess.Environment); const command = '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output "$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)" }'; const result = yield* processRunner .run({ - command: "powershell.exe", + command: powershell, args: ["-NoProfile", "-NonInteractive", "-Command", command], timeout, maxOutputBytes: 262_144, diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 75c12d8a7409b..b202bd38d7f65 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -14,6 +14,7 @@ import { import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@t3tools/shared/git"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import * as Cause from "effect/Cause"; @@ -309,7 +310,7 @@ const make = Effect.gen(function* () { processes .run({ operation: "TaskFolders.worktreeLayout", - command: onWindows ? "cmd.exe" : "sh", + command: onWindows ? windowsSystem32Path(hostEnvironment, "cmd.exe") : "sh", args: onWindows ? ["/d", "/s", "/c", command] : ["-c", command], cwd: taskFolder.projectRoot, env: { diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 7c1d17587813e..0930fecde82d0 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -222,6 +222,15 @@ describe("agentWorkingDirectories", () => { ), ).toEqual(["/work/d"]); }); + + it("leaves network shares out of the search roots", () => { + expect( + directories( + "cd //files.example/share", + String.raw`cd '\\files.example\share'; cd C:\work\repo`, + ), + ).toEqual([String.raw`C:\work\repo`]); + }); }); // regression: #35337 a bare file name the agent cited from a subfolder of an unregistered checkout diff --git a/packages/client-runtime/src/workspaceBasenameLookup.ts b/packages/client-runtime/src/workspaceBasenameLookup.ts index ae55263fb2bd4..7d50a12304c2e 100644 --- a/packages/client-runtime/src/workspaceBasenameLookup.ts +++ b/packages/client-runtime/src/workspaceBasenameLookup.ts @@ -1,6 +1,7 @@ import { FILESYSTEM_METADATA_BATCH_LIMIT } from "@t3tools/contracts"; import { isAbsolutePath, + isNetworkPath, isWindowsAbsolutePath, resolveWorkspaceFilePath, } from "@t3tools/shared/path"; @@ -229,6 +230,8 @@ function literalDirectory(operand: string): string | null { const path = /^["']/.test(operand) ? operand.slice(1, -1) : operand; // The shell would expand these, and only it knows to what. if (!isAbsolutePath(path) || /[$`*?[\]{}"']/.test(path)) return null; + // Search roots are local directories; the server stats each one. + if (isNetworkPath(path)) return null; return path.includes("\\") && !isWindowsAbsolutePath(path) ? null : path; } diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index b08eef243fc3e..fb1cd976a9a65 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -31,6 +31,7 @@ import * as EffectAcpProtocol from "effect-acp/protocol"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { AgentScope, AgentScopeThreadId, RAISE_OOM_SCORE_LINE } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import { appendAcpStderrTail, sanitizeAcpStderrExcerpt } from "./stderr.ts"; @@ -1044,7 +1045,12 @@ const terminateWindowsProcessTreeWithTaskkill = ( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const taskkill = yield* spawner.spawn( - ChildProcess.make("taskkill", ["/PID", String(pid), "/T", "/F"]), + ChildProcess.make(windowsSystem32Path(yield* HostProcess.Environment, "taskkill.exe"), [ + "/PID", + String(pid), + "/T", + "/F", + ]), ); const outputFiber = yield* Stream.decodeText(taskkill.all).pipe( Stream.mkString, diff --git a/packages/provider-pi/src/server/rpc.ts b/packages/provider-pi/src/server/rpc.ts index 3cdb2058f1cf3..f51bc493535b6 100644 --- a/packages/provider-pi/src/server/rpc.ts +++ b/packages/provider-pi/src/server/rpc.ts @@ -12,6 +12,7 @@ import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { MAX_TOOL_OUTPUT_IMAGES, @@ -272,7 +273,12 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp const terminateWindowsTree = Effect.gen(function* () { if (hasExited()) return; const taskkill = yield* spawner.spawn( - ChildProcess.make("taskkill", ["/PID", String(child.pid), "/T", "/F"]), + ChildProcess.make(windowsSystem32Path(yield* HostProcess.Environment, "taskkill.exe"), [ + "/PID", + String(child.pid), + "/T", + "/F", + ]), ); yield* taskkill.exitCode; }).pipe(Effect.scoped, Effect.ignore); diff --git a/packages/shared/package.json b/packages/shared/package.json index d12cd9b003982..f51761a9f8188 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -107,6 +107,10 @@ "types": "./src/shell.ts", "import": "./src/shell.ts" }, + "./windowsSystem": { + "types": "./src/windowsSystem.ts", + "import": "./src/windowsSystem.ts" + }, "./envTrampoline": { "types": "./src/envTrampoline.ts", "import": "./src/envTrampoline.ts" diff --git a/packages/shared/src/windowsSystem.ts b/packages/shared/src/windowsSystem.ts new file mode 100644 index 0000000000000..1d74ccdc5e5a3 --- /dev/null +++ b/packages/shared/src/windowsSystem.ts @@ -0,0 +1,8 @@ +// Effect-free so the standalone service launcher can use it. + +/** Windows system tools are run by absolute path, independent of PATH and the working directory. */ +export const windowsSystem32Path = (env: NodeJS.ProcessEnv, executable: string) => + `${env.SystemRoot || env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\${executable}`; + +export const windowsPowerShellPath = (env: NodeJS.ProcessEnv) => + windowsSystem32Path(env, String.raw`WindowsPowerShell\v1.0\powershell.exe`); From 08580964723e68ef71dcdd5cbda3fcf94929efac Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 16:20:13 -0800 Subject: [PATCH 105/221] fix: Forgejo and GitCafe merges carry the expected head commit (#41773) Co-authored-by: Claude Fable 5.2 --- ...equestDetailPanel.permissions.browser.test.tsx | 15 ++++++++++++++- .../pullRequest/PullRequestDetailPanel.tsx | 7 +++++-- .../src/server/ForgejoPullRequestProvider.ts | 3 +++ .../server/ForgejoSourceControlProvider.test.ts | 9 +++++++++ .../src/server/GitCafePullRequestProvider.test.ts | 9 +++++++-- .../src/server/GitCafePullRequestProvider.ts | 2 +- 6 files changed, 39 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx index e7a4733ae9410..c73254811aab8 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.permissions.browser.test.tsx @@ -223,9 +223,22 @@ it("keeps a merge and a review on the head the reader was shown until they load await vi.waitFor(() => expect(sent("verdict")).toEqual(["shown-head"])); expect(sent("action")).toEqual(["shown-head"]); + // The pin moves once the reload has been asked of the host, not at the click. + const reload = Promise.withResolvers<{ _tag: "Success"; value: undefined }>(); + command.mockImplementation((call) => + call?.input?.reference === undefined + ? Promise.resolve({ _tag: "Success", value: undefined }) + : reload.promise, + ); await screen.getByRole("button", { name: "Load new commits" }).click(); await merge(); - await vi.waitFor(() => expect(sent("action")).toEqual(["shown-head", "pushed-head"])); + await vi.waitFor(() => expect(sent("action")).toEqual(["shown-head", "shown-head"])); + reload.resolve({ _tag: "Success", value: undefined }); + await expect.element(screen.getByText(/still applies to/)).not.toBeInTheDocument(); + await merge(); + await vi.waitFor(() => + expect(sent("action")).toEqual(["shown-head", "shown-head", "pushed-head"]), + ); }); it("reads the first diff page once the pointer rests on the Code tab", async () => { diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 110aac26cde5c..8a7e7bb2fe96e 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -1931,9 +1931,12 @@ export function PullRequestDetailPanel({
} @@ -295,13 +377,21 @@ export function PullRequestStackMenu({ term: changeRequestTermKind(terminology), }, ) - : gt( - "{count, plural, one {Rebase {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Rebase {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", - { - count: unmerged.length, - term: changeRequestTermKind(terminology), - }, - )} + : confirmation === "enable-auto-merge" + ? gt( + "{count, plural, one {Auto-merge {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Auto-merge {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + { + count: mergeLayers.length, + term: changeRequestTermKind(terminology), + }, + ) + : gt( + "{count, plural, one {Rebase {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Rebase {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + { + count: unmerged.length, + term: changeRequestTermKind(terminology), + }, + )} {confirmation === "merge" @@ -314,10 +404,20 @@ export function PullRequestStackMenu({ host: hostLabel, }, ) - : gt( - "Rebase the remote branches from bottom to top onto {base}. This rewrites branch history and may restart checks. If a layer fails, earlier updates remain.", - { base: stack.base }, - )} + : confirmation === "enable-auto-merge" + ? gt( + "Merge #{number} and its unmerged layers below into {base} using {method} once every one of them meets the requirements on {host}. This may happen immediately.", + { + number: reference.number, + base: stack.base, + method: mergeMethod, + host: hostLabel, + }, + ) + : gt( + "Rebase the remote branches from bottom to top onto {base}. This rewrites branch history and may restart checks. If a layer fails, earlier updates remain.", + { base: stack.base }, + )} @@ -337,7 +437,11 @@ export function PullRequestStackMenu({ Cancel diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 36f57764ea37a..4d3d656f33916 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12787,5 +12787,24 @@ "99d51127f573296b": "Weiteres Konto", "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", "99963c0142e17f00": "Für das neue {tracker}-Konto.", - "6d8e4ebc889bace9": "Konto hinzufügen" + "6d8e4ebc889bace9": "Konto hinzufügen", + "8a883c4fbc127b68": "Auto-Merge für den Stack wird aktiviert...", + "5fb2a26ae31e8983": "Auto-Merge für den Stack konnte nicht aktiviert werden", + "986d0dcbf4dd0098": "Auto-Merge für den Stack aktiviert", + "f3ed1f63c8a3eef2": "{host} mergt den Stack bis #{number}, sobald die Anforderungen erfüllt sind.", + "bd536a0a1754f6cb": "Auto-Merge für den Stack konnte nicht abgebrochen werden", + "bb90ac3b2f3a72d5": "Der Host hat das Abbrechen des Auto-Merge abgelehnt. Aktualisiere und versuche es erneut.", + "9c28753c777c37b7": "{count, plural, one {Auto-Merge für {count} {term, select, mr {Merge Request} cr {Änderungsanfrage} other {Pull Request}}?} other {Auto-Merge für {count} {term, select, mr {Merge Requests} cr {Änderungsanfragen} other {Pull Requests}}?}}", + "a86b49982e18784d": "#{number} und die darunterliegenden nicht gemergten Ebenen per {method} in {base} mergen, sobald jede davon die Anforderungen auf {host} erfüllt. Das kann sofort passieren.", + "b1afda5c964deee4": [ + "Auto-Merge für Stack (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Auto-Merge für Stack abbrechen", + "012c67c7f1a99e33": "Auto-Merge für Stack" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 22791e2badd65..da9e327abf64f 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12796,5 +12796,24 @@ "99d51127f573296b": "Another account", "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", "99963c0142e17f00": "For the new {tracker} account.", - "6d8e4ebc889bace9": "Add account" + "6d8e4ebc889bace9": "Add account", + "8a883c4fbc127b68": "Enabling stack auto-merge...", + "5fb2a26ae31e8983": "Could not enable stack auto-merge", + "986d0dcbf4dd0098": "Stack auto-merge enabled", + "f3ed1f63c8a3eef2": "{host} merges the stack through #{number} once its requirements are met.", + "bd536a0a1754f6cb": "Could not cancel stack auto-merge", + "bb90ac3b2f3a72d5": "The host refused to cancel auto-merge. Refresh and try again.", + "9c28753c777c37b7": "{count, plural, one {Auto-merge {count} {term, select, mr {merge request} cr {change request} other {pull request}}?} other {Auto-merge {count} {term, select, mr {merge requests} cr {change requests} other {pull requests}}?}}", + "a86b49982e18784d": "Merge #{number} and its unmerged layers below into {base} using {method} once every one of them meets the requirements on {host}. This may happen immediately.", + "b1afda5c964deee4": [ + "Auto-merge stack (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancel stack auto-merge", + "012c67c7f1a99e33": "Auto-merge stack" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 2c68ad496ac5f..ff24104e8075f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12782,5 +12782,24 @@ "99d51127f573296b": "Otra cuenta", "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", - "6d8e4ebc889bace9": "Añadir cuenta" + "6d8e4ebc889bace9": "Añadir cuenta", + "8a883c4fbc127b68": "Activando la fusión automática de la pila...", + "5fb2a26ae31e8983": "No se pudo activar la fusión automática de la pila", + "986d0dcbf4dd0098": "Fusión automática de la pila activada", + "f3ed1f63c8a3eef2": "{host} fusionará la pila hasta #{number} cuando se cumplan sus requisitos.", + "bd536a0a1754f6cb": "No se pudo cancelar la fusión automática de la pila", + "bb90ac3b2f3a72d5": "El host rechazó cancelar la fusión automática. Actualiza e inténtalo de nuevo.", + "9c28753c777c37b7": "{count, plural, one {¿Fusionar automáticamente {count} {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}?} other {¿Fusionar automáticamente {count} {term, select, mr {merge requests} cr {solicitudes de cambios} other {pull requests}}?}}", + "a86b49982e18784d": "Fusiona #{number} y sus capas sin fusionar de debajo en {base} mediante {method} cuando todas cumplan los requisitos de {host}. Puede ocurrir de inmediato.", + "b1afda5c964deee4": [ + "Fusión automática de la pila (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancelar la fusión automática de la pila", + "012c67c7f1a99e33": "Fusión automática de la pila" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index cb4db84726d56..64b28506bfe6a 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12787,5 +12787,24 @@ "99d51127f573296b": "Autre compte", "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", "99963c0142e17f00": "Pour le nouveau compte {tracker}.", - "6d8e4ebc889bace9": "Ajouter un compte" + "6d8e4ebc889bace9": "Ajouter un compte", + "8a883c4fbc127b68": "Activation de la fusion automatique de la pile...", + "5fb2a26ae31e8983": "Impossible d’activer la fusion automatique de la pile", + "986d0dcbf4dd0098": "Fusion automatique de la pile activée", + "f3ed1f63c8a3eef2": "{host} fusionnera la pile jusqu’à #{number} dès que ses conditions seront remplies.", + "bd536a0a1754f6cb": "Impossible d’annuler la fusion automatique de la pile", + "bb90ac3b2f3a72d5": "L’hôte a refusé d’annuler la fusion automatique. Actualisez et réessayez.", + "9c28753c777c37b7": "{count, plural, one {Fusionner automatiquement {count} {term, select, mr {merge request} cr {demande de modification} other {pull request}} ?} other {Fusionner automatiquement {count} {term, select, mr {merge requests} cr {demandes de modification} other {pull requests}} ?}}", + "a86b49982e18784d": "Fusionner #{number} et ses couches non fusionnées inférieures dans {base} avec {method} dès que chacune remplit les conditions de {host}. Cela peut se produire immédiatement.", + "b1afda5c964deee4": [ + "Fusion automatique de la pile (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Annuler la fusion automatique de la pile", + "012c67c7f1a99e33": "Fusion automatique de la pile" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 01c10337742d3..f4c1b792d77e2 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12728,5 +12728,24 @@ "99d51127f573296b": "別のアカウント", "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", "99963c0142e17f00": "新しい {tracker} アカウント用です。", - "6d8e4ebc889bace9": "アカウントを追加" + "6d8e4ebc889bace9": "アカウントを追加", + "8a883c4fbc127b68": "スタックの自動マージを有効にしています...", + "5fb2a26ae31e8983": "スタックの自動マージを有効にできませんでした", + "986d0dcbf4dd0098": "スタックの自動マージを有効にしました", + "f3ed1f63c8a3eef2": "要件が満たされると、{host} が #{number} までのスタックをマージします。", + "bd536a0a1754f6cb": "スタックの自動マージをキャンセルできませんでした", + "bb90ac3b2f3a72d5": "ホストが自動マージのキャンセルを拒否しました。更新してもう一度お試しください。", + "9c28753c777c37b7": "{count, plural, other {{term, select, mr {マージリクエスト {count} 件を自動マージしますか?} cr {変更リクエスト {count} 件を自動マージしますか?} other {プルリクエスト {count} 件を自動マージしますか?}}}}", + "a86b49982e18784d": "#{number} と、その下の未マージのレイヤーがすべて {host} の要件を満たしたら、{method} で {base} にマージします。すぐにマージされる場合があります。", + "b1afda5c964deee4": [ + "スタックを自動マージ (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "スタックの自動マージをキャンセル", + "012c67c7f1a99e33": "スタックを自動マージ" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index eb4cf8b1c5273..0ef52c37295fc 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12724,5 +12724,24 @@ "99d51127f573296b": "다른 계정", "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", "99963c0142e17f00": "새 {tracker} 계정용입니다.", - "6d8e4ebc889bace9": "계정 추가" + "6d8e4ebc889bace9": "계정 추가", + "8a883c4fbc127b68": "스택 자동 병합을 켜는 중...", + "5fb2a26ae31e8983": "스택 자동 병합을 켤 수 없습니다", + "986d0dcbf4dd0098": "스택 자동 병합을 켰습니다", + "f3ed1f63c8a3eef2": "요구 사항이 충족되면 {host}에서 #{number}까지 스택을 병합합니다.", + "bd536a0a1754f6cb": "스택 자동 병합을 취소할 수 없습니다", + "bb90ac3b2f3a72d5": "호스트가 자동 병합 취소를 거부했습니다. 새로 고친 후 다시 시도하세요.", + "9c28753c777c37b7": "{count, plural, other {{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} {count}개를 자동 병합할까요?}}", + "a86b49982e18784d": "#{number}와(과) 그 아래의 병합되지 않은 레이어가 모두 {host}의 요구 사항을 충족하면 {method}(으)로 {base}에 병합합니다. 바로 병합될 수도 있습니다.", + "b1afda5c964deee4": [ + "스택 자동 병합(", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "스택 자동 병합 취소", + "012c67c7f1a99e33": "스택 자동 병합" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 06eea3c29b995..c7354ff24613d 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12787,5 +12787,24 @@ "99d51127f573296b": "Outra conta", "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", "99963c0142e17f00": "Para a nova conta do {tracker}.", - "6d8e4ebc889bace9": "Adicionar conta" + "6d8e4ebc889bace9": "Adicionar conta", + "8a883c4fbc127b68": "Ativando o merge automático da pilha...", + "5fb2a26ae31e8983": "Não foi possível ativar o merge automático da pilha", + "986d0dcbf4dd0098": "Merge automático da pilha ativado", + "f3ed1f63c8a3eef2": "{host} vai mesclar a pilha até o #{number} quando os requisitos forem atendidos.", + "bd536a0a1754f6cb": "Não foi possível cancelar o merge automático da pilha", + "bb90ac3b2f3a72d5": "O host recusou o cancelamento do merge automático. Atualize e tente novamente.", + "9c28753c777c37b7": "{count, plural, one {Mesclar automaticamente {count} {term, select, mr {merge request} cr {solicitação de alteração} other {pull request}}?} other {Mesclar automaticamente {count} {term, select, mr {merge requests} cr {solicitações de alteração} other {pull requests}}?}}", + "a86b49982e18784d": "Mescla o #{number} e as camadas não mescladas abaixo dele em {base} usando {method} quando todas atenderem aos requisitos de {host}. Isso pode acontecer imediatamente.", + "b1afda5c964deee4": [ + "Merge automático da pilha (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Cancelar merge automático da pilha", + "012c67c7f1a99e33": "Merge automático da pilha" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 44148970bd468..20e9a76a10fa1 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12787,5 +12787,24 @@ "99d51127f573296b": "Другой аккаунт", "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", "99963c0142e17f00": "Для нового аккаунта {tracker}.", - "6d8e4ebc889bace9": "Добавить аккаунт" + "6d8e4ebc889bace9": "Добавить аккаунт", + "8a883c4fbc127b68": "Включение автослияния стека...", + "5fb2a26ae31e8983": "Не удалось включить автослияние стека", + "986d0dcbf4dd0098": "Автослияние стека включено", + "f3ed1f63c8a3eef2": "{host} сольёт стек до #{number}, когда будут выполнены требования.", + "bd536a0a1754f6cb": "Не удалось отменить автослияние стека", + "bb90ac3b2f3a72d5": "Хост отказался отменить автослияние. Обновите и повторите попытку.", + "9c28753c777c37b7": "{count, plural, one {Включить автослияние для {count} {term, select, mr {мерж-реквеста} cr {запроса на изменение} other {пул-реквеста}}?} few {Включить автослияние для {count} {term, select, mr {мерж-реквестов} cr {запросов на изменение} other {пул-реквестов}}?} many {Включить автослияние для {count} {term, select, mr {мерж-реквестов} cr {запросов на изменение} other {пул-реквестов}}?} other {Включить автослияние для {count} {term, select, mr {мерж-реквеста} cr {запроса на изменение} other {пул-реквеста}}?}}", + "a86b49982e18784d": "#{number} и несмёрженные слои под ним будут слиты в {base} методом {method}, когда каждый из них выполнит требования {host}. Это может произойти сразу.", + "b1afda5c964deee4": [ + "Автослияние стека (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Отменить автослияние стека", + "012c67c7f1a99e33": "Автослияние стека" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 2bb20d01df420..946abe27ad7cd 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12794,5 +12794,24 @@ "99d51127f573296b": "Ett konto till", "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", "99963c0142e17f00": "För det nya {tracker}-kontot.", - "6d8e4ebc889bace9": "Lägg till konto" + "6d8e4ebc889bace9": "Lägg till konto", + "8a883c4fbc127b68": "Aktiverar automatisk merge för stacken...", + "5fb2a26ae31e8983": "Kunde inte aktivera automatisk merge för stacken", + "986d0dcbf4dd0098": "Automatisk merge för stacken aktiverad", + "f3ed1f63c8a3eef2": "{host} mergar stacken till och med #{number} när kraven är uppfyllda.", + "bd536a0a1754f6cb": "Kunde inte avbryta automatisk merge för stacken", + "bb90ac3b2f3a72d5": "Värden vägrade avbryta den automatiska mergen. Uppdatera och försök igen.", + "9c28753c777c37b7": "{count, plural, one {Merga {count} {term, select, mr {merge request} cr {ändringsbegäran} other {pull request}} automatiskt?} other {Merga {count} {term, select, mr {merge requests} cr {ändringsbegäranden} other {pull requests}} automatiskt?}}", + "a86b49982e18784d": "Merga #{number} och dess omergade lager under in i {base} med {method} när vart och ett uppfyller kraven på {host}. Det kan ske direkt.", + "b1afda5c964deee4": [ + "Merga stacken automatiskt (", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "Avbryt automatisk merge för stacken", + "012c67c7f1a99e33": "Merga stacken automatiskt" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 0def42b8dda67..34b76ab61689c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12806,5 +12806,24 @@ "99d51127f573296b": "其他账号", "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", "99963c0142e17f00": "用于新的 {tracker} 账号。", - "6d8e4ebc889bace9": "添加账号" + "6d8e4ebc889bace9": "添加账号", + "8a883c4fbc127b68": "正在启用堆叠自动合并…", + "5fb2a26ae31e8983": "无法启用堆叠自动合并", + "986d0dcbf4dd0098": "已启用堆叠自动合并", + "f3ed1f63c8a3eef2": "满足要求后,{host} 会合并截至 #{number} 的堆叠。", + "bd536a0a1754f6cb": "无法取消堆叠自动合并", + "bb90ac3b2f3a72d5": "主机拒绝取消自动合并。请刷新后重试。", + "9c28753c777c37b7": "{count, plural, other {自动合并 {count} 个 {term, select, mr {merge request} cr {change request} other {pull request}}?}}", + "a86b49982e18784d": "当 #{number} 及其下方未合并的各层都满足 {host} 的要求时,使用 {method} 将它们合并到 {base}。这可能会立即发生。", + "b1afda5c964deee4": [ + "自动合并堆叠(", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ")" + ], + "33d18dda74f6d7b3": "取消堆叠自动合并", + "012c67c7f1a99e33": "自动合并堆叠" } diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 3318ae3cdcb58..557dbcab85d84 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -310,6 +310,8 @@ export const PullRequestCapabilities = Schema.Struct({ edit: Schema.optional(PullRequestEditCapabilities), stacks: Schema.optional(Schema.Boolean), stackActions: Schema.optional(Schema.Boolean), + /** Stack actions also arm and cancel auto-merge for a layer and the open layers below it. */ + stackAutoMerge: Schema.optional(Schema.Boolean), labels: Schema.optional(Schema.Boolean), /** The host searches the repository's users, so composers can complete `@login`. */ mentions: Schema.optional(Schema.Boolean), diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index e38255b2eb377..76b3b8cf1908b 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -2761,6 +2761,102 @@ layer("GitHubPullRequestApi.layer", (it) => { }), ); + it.effect("arms and cancels auto-merge for a stack through the pinned layer", () => + Effect.gen(function* () { + route( + [ + "stacks?pull_request=7", + [ + { + number: 3, + url: "https://api.github.com/repos/acme/web/stacks/3", + base: { ref: "main" }, + pull_requests: [ + { number: 6, head: { ref: "one", sha: "aaa" }, state: "open", draft: false }, + { number: 7, head: { ref: "two", sha: "bbb" }, state: "open", draft: false }, + ], + }, + ], + ], + ["PullRequestNodeId", { data: { repository: { pullRequest: { id: "PR_7" } } } }], + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + const target = { cwd: "/w", repository: "acme/web", host: "github.com", number: 7 }; + yield* cli.runPullRequestAction({ + ...target, + action: "enable-auto-merge", + mergeMethod: "squash", + stackNumber: 3, + expectedStackHeads: [ + { number: 6, headSha: "aaa" }, + { number: 7, headSha: "bbb" }, + ], + }); + yield* cli.runPullRequestAction({ ...target, action: "disable-auto-merge", stackNumber: 3 }); + expect(variablesOf("enablePullRequestAutoMerge(")).toEqual([ + { + input: { + pullRequestId: "PR_7", + mergeMethod: "SQUASH", + expectedHeadOid: "bbb", + includeStack: true, + }, + }, + ]); + expect(variablesOf("DisableStackAutoMerge")).toEqual([{ pullRequestId: "PR_7" }]); + expect(restCallsTo("merge-async")).toEqual([]); + }), + ); + + it.effect("merges a stack that is already mergeable instead of arming auto-merge", () => + Effect.gen(function* () { + route( + [ + "stacks?pull_request=7", + [ + { + number: 3, + url: "https://api.github.com/repos/acme/web/stacks/3", + base: { ref: "main" }, + pull_requests: [ + { number: 7, head: { ref: "two", sha: "bbb" }, state: "open", draft: false }, + ], + }, + ], + ], + ["PullRequestNodeId", { data: { repository: { pullRequest: { id: "PR_7" } } } }], + [ + "enablePullRequestAutoMerge(", + { + data: { enablePullRequestAutoMerge: null }, + errors: [ + { + type: "UNPROCESSABLE", + message: + "Auto-merge is not needed because all requested pull requests are already mergeable", + }, + ], + }, + ], + ["merge-async", { status: "merged", details: {} }], + ); + const cli = yield* GitHubPullRequestApi.GitHubPullRequestApi; + yield* cli.runPullRequestAction({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + action: "enable-auto-merge", + mergeMethod: "squash", + stackNumber: 3, + expectedStackHeads: [{ number: 7, headSha: "bbb" }], + }); + expect(restCallsTo("merge-async")).toMatchObject([ + { method: "PUT", body: { merge_method: "squash", sha: "bbb" } }, + ]); + }), + ); + it.effect.each(["merge", "enable-auto-merge"] as const)( "removes agent credits from the proposed message for %s", (action) => diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 4412c5da35f37..567415248ba9d 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -2753,15 +2753,58 @@ export const make = Effect.gen(function* () { .pipe(graphql(target)); }); } - if (input.stackNumber !== undefined) - return runGitHubStackAction({ ...input, stackNumber: input.stackNumber }).pipe( - Effect.provideService(GitHubRest.GitHubRest, api), - Effect.provideService(GitHubAppAccess.GitHubAppAccess, appAccess), - Effect.provideService(GitHubRequestPolicy.GitHubRequestPolicy, policy), - Effect.provideService(HttpClient.HttpClient, httpClient), - Effect.provideService(SourceControlHost.SourceControlHost, sourceControlHost), - Effect.provideService(FileSystem.FileSystem, fileSystem), + if (input.stackNumber !== undefined) { + const stackNumber = input.stackNumber; + const target = { ...input, operation: "runPullRequestAction" }; + // A stack auto-merge request sits on the layer it was armed on and covers those below. + if (input.action === "disable-auto-merge") + return pullRequestNodeId(target).pipe( + Effect.flatMap((pullRequestId) => + actionSummary( + client + .DisableStackAutoMerge({ pullRequestId }) + .pipe(Effect.map((result) => result.disablePullRequestAutoMerge?.pullRequest)), + ).pipe(graphql(target)), + ), + ); + const stackAction = (action: typeof input.action) => + runGitHubStackAction({ ...input, action, stackNumber }).pipe( + Effect.provideService(GitHubRest.GitHubRest, api), + Effect.provideService(GitHubAppAccess.GitHubAppAccess, appAccess), + Effect.provideService(GitHubRequestPolicy.GitHubRequestPolicy, policy), + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.provideService(SourceControlHost.SourceControlHost, sourceControlHost), + Effect.provideService(FileSystem.FileSystem, fileSystem), + ); + if (input.action !== "enable-auto-merge") return stackAction(input.action); + const expectedHeadOid = input.expectedStackHeads?.find( + (layer) => layer.number === input.number, + )?.headSha; + return stackAction("enable-auto-merge").pipe( + Effect.andThen(pullRequestNodeId(target)), + Effect.flatMap((pullRequestId) => + actionSummary( + client + .EnablePullRequestAutoMerge({ + input: { + pullRequestId, + mergeMethod: GRAPHQL_MERGE_METHODS[input.mergeMethod ?? "merge"] ?? "MERGE", + ...(expectedHeadOid === undefined ? {} : { expectedHeadOid }), + includeStack: true, + }, + }) + .pipe(Effect.map((result) => result.enablePullRequestAutoMerge?.pullRequest)), + ).pipe(graphql(target)), + ), + // Like `gh pr merge --auto`: a stack that can merge now merges, re-pinned to its heads. + Effect.catchIf( + (error) => + error._tag === "GitHubApiResponseError" && + (error.githubErrors ?? []).some((message) => message.includes("already mergeable")), + () => stackAction("merge"), + ), ); + } if (input.action === "revert") { return pullRequestNodeId({ ...input, operation: "revertPullRequest" }).pipe( Effect.flatMap((pullRequestId) => diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index d1f3746d38d3e..e05724a6e4d67 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -55,6 +55,7 @@ const CAPABILITIES: PullRequestCapabilities = { edit: { changeRequest: true, comment: true, maintainerEdits: true }, stacks: true, stackActions: true, + stackAutoMerge: true, labels: true, // Statuses and check runs land on the head commit itself and are read whole, so an empty list // after a push is CI that never started rather than a read that saw nothing. diff --git a/packages/source-control-github/src/server/githubStackActions.ts b/packages/source-control-github/src/server/githubStackActions.ts index fb524ae0518de..9819fe1707b60 100644 --- a/packages/source-control-github/src/server/githubStackActions.ts +++ b/packages/source-control-github/src/server/githubStackActions.ts @@ -124,7 +124,11 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function* number: input.number, stackNumber: input.stackNumber, }; - if (input.action !== "merge" && input.action !== "update-branch") + if ( + input.action !== "merge" && + input.action !== "update-branch" && + input.action !== "enable-auto-merge" + ) return yield* new GitHubStackUnsupportedError({ ...identity }); const endpoint = `repos/${input.repository}`; const read = yield* api.rest({ @@ -146,9 +150,9 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function* return yield* new GitHubStackChangedError({ ...identity, number: input.number, completed: 0 }); } const affectedLayers = - input.action === "merge" ? stack.layers.slice(0, targetIndex + 1) : stack.layers; + input.action === "update-branch" ? stack.layers : stack.layers.slice(0, targetIndex + 1); const open = affectedLayers.filter((layer) => layer.state !== "merged"); - if (input.action === "merge" && target.state !== "open") + if (input.action !== "update-branch" && target.state !== "open") return yield* new GitHubStackUnsupportedError({ ...identity }); if ( !input.expectedStackHeads || @@ -230,6 +234,8 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function* } if (open.some((layer) => layer.isDraft)) return yield* new GitHubStackUnsupportedError({ ...identity }); + // Auto-merge is armed by the caller's GraphQL mutation once the layers are pinned here. + if (input.action === "enable-auto-merge") return; const decode = (raw: string) => decodeMergeResponse(raw).pipe( Effect.mapError((cause) => new GitHubStackResponseInvalidError({ ...identity, cause })), diff --git a/packages/source-control-github/src/server/pullRequestMutations.graphql b/packages/source-control-github/src/server/pullRequestMutations.graphql index 550b26ca4fd4f..ba8bdbd6d3fd9 100644 --- a/packages/source-control-github/src/server/pullRequestMutations.graphql +++ b/packages/source-control-github/src/server/pullRequestMutations.graphql @@ -151,6 +151,15 @@ mutation DisablePullRequestAutoMerge($pullRequestId: ID!) { } } +# Its own document: Enterprise Server rejects `includeStack` wherever it is named. +mutation DisableStackAutoMerge($pullRequestId: ID!) { + disablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, includeStack: true }) { + pullRequest { + ...PullRequestActionSummary + } + } +} + mutation UpdatePullRequestBranch( $pullRequestId: ID! $expectedHeadOid: GitObjectID! diff --git a/packages/source-control-github/src/server/pullRequestMutations.graphql.ts b/packages/source-control-github/src/server/pullRequestMutations.graphql.ts index b62bf95973126..d243d3e9f541f 100644 --- a/packages/source-control-github/src/server/pullRequestMutations.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestMutations.graphql.ts @@ -554,6 +554,32 @@ export declare namespace DisablePullRequestAutoMerge { export type Result = typeof DisablePullRequestAutoMerge.result.Type } +/** `mutation DisableStackAutoMerge` */ +export const DisableStackAutoMerge = GraphQL.mutation("DisableStackAutoMerge", { + document: { + variables: [ + { name: "pullRequestId", body: "ID!" } + ], + selections: [ + { name: "disablePullRequestAutoMerge", body: ["(input:{pullRequestId:$", "pullRequestId", " includeStack:true}){pullRequest{...PullRequestActionSummary}}"] } + ], + fragments: [ + { name: "PullRequestActionSummary", body: ["on PullRequest{number title url headRefName baseRefName state isDraft updatedAt mergedAt closedAt headRefOid author{__typename login avatarUrl...on User{name}}autoMergeRequest{mergeMethod}}"] } + ] + }, + variables: { + pullRequestId: Shared.ID + }, + result: Schema.Struct({ + /** Disable auto merge on the given pull request */ + disablePullRequestAutoMerge: Schema.NullOr(DisablePullRequestAutoMergePayload) + }) +}) +export declare namespace DisableStackAutoMerge { + export type Variables = typeof DisableStackAutoMerge.variables.Type + export type Result = typeof DisableStackAutoMerge.result.Type +} + /** Autogenerated return type of UpdatePullRequestBranch. */ export const UpdatePullRequestBranchPayload = Schema.Struct({ /** The updated pull request. */ @@ -807,4 +833,4 @@ export declare namespace DeletePullRequestBranch { } /** Every operation in pullRequestMutations.graphql. */ -export const PullRequestMutationsGraphQLGroup = GraphQLGroup.make(AddReviewThreadReply, AddReaction, RemoveReaction, ResolveReviewThread, UnresolveReviewThread, UpdatePullRequest, RevertPullRequest, UpdateIssueComment, UpdateReviewComment, SetFileViewed, MergePullRequest, EnablePullRequestAutoMerge, DisablePullRequestAutoMerge, UpdatePullRequestBranch, MarkPullRequestReadyForReview, ConvertPullRequestToDraft, ClosePullRequest, ReopenPullRequest, AddComment, DeletePullRequestBranch) +export const PullRequestMutationsGraphQLGroup = GraphQLGroup.make(AddReviewThreadReply, AddReaction, RemoveReaction, ResolveReviewThread, UnresolveReviewThread, UpdatePullRequest, RevertPullRequest, UpdateIssueComment, UpdateReviewComment, SetFileViewed, MergePullRequest, EnablePullRequestAutoMerge, DisablePullRequestAutoMerge, DisableStackAutoMerge, UpdatePullRequestBranch, MarkPullRequestReadyForReview, ConvertPullRequestToDraft, ClosePullRequest, ReopenPullRequest, AddComment, DeletePullRequestBranch) From ceb820e24ebeb7a91790e1fe793072a4c2a5c2bb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:16:59 -0800 Subject: [PATCH 136/221] fix(scripts): server benchmark keeps the rounds it finished when a later run fails (#41716) --- scripts/server-metrics.test.ts | 32 ++++++++++++++ scripts/server-metrics.ts | 81 +++++++++++++++++++++++++++------- 2 files changed, 97 insertions(+), 16 deletions(-) diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index e87174969c9ed..6597e9297514b 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -1,3 +1,5 @@ +import { it as effectIt } from "@effect/vitest"; +import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; @@ -19,6 +21,7 @@ import { ServerMetrics, slope, } from "./server-metrics-report.ts"; +import { runAbRounds } from "./server-metrics.ts"; const decodeMetrics = Schema.decodeSync(ServerMetrics); @@ -103,6 +106,17 @@ describe("compareMetrics", () => { expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9), 10, gatedRules).regressed).toEqual([]); }); + it("compares the unequal run counts an ab that stopped early leaves", () => { + const steady = cpuRuns(26.1, 27.4, 25.8); + const partial = compareMetrics(steady, cpuRuns(2.2, 2.5), 10, gatedRules); + expect(partial.improved).toContain("quiet.cpuPct"); + expect(partial.table).toContain("(3 runs), after `abc` (2 runs)"); + const single = compareMetrics(steady, cpuRuns(2.2), 10, gatedRules); + expect(single.improved).toContain("quiet.cpuPct"); + expect(single.table).toContain("| quiet.cpuPct | 26.1 | 2.2 | -92% | | better |"); + expect(compareMetrics(steady, cpuRuns(), 10, gatedRules).compared).toBe(0); + }); + it("reads a file written before loop delay and GC were recorded", () => { const older = decodeMetrics({ meta, @@ -601,3 +615,21 @@ describe("activityRenewalMissed", () => { expect(activityRenewalMissed(0, sentAt, repliedAt)).toBe(missed); }); }); + +describe("runAbRounds", () => { + effectIt.effect("keeps the runs that finished when a later run fails", () => + Effect.gen(function* () { + const files: Record<0 | 1, ReadonlyArray> = { 0: [], 1: [] }; + const failure = yield* Effect.flip( + runAbRounds({ + rounds: 3, + outDir: "out", + runSide: (side) => (side === 0 ? Effect.succeed("a1") : Effect.fail("b crashed")), + save: (side, runs) => Effect.sync(() => (files[side] = [...runs])), + }), + ); + expect(failure).toBe("b crashed"); + expect(files).toEqual({ 0: ["a1"], 1: [] }); + }), + ); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index c3482c72e70ff..9fa06fcfdea5c 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -2129,8 +2129,56 @@ const writeMetrics = Effect.fn("serverMetrics.writeMetrics")(function* ( ) { const fs = yield* FileSystem.FileSystem; const json = yield* encodeMetrics(metrics); - if (Option.isSome(out)) yield* fs.writeFileString(out.value, `${json}\n`); - else yield* Console.log(json); + if (Option.isNone(out)) return yield* Console.log(json); + // A sibling then a rename, so a failed write keeps the previous file whole. + const temp = `${out.value}.tmp`; + yield* fs.writeFileString(temp, `${json}\n`); + yield* fs.rename(temp, out.value); +}); + +/** + * Runs A and B alternately, saving a side after each of its runs so a failure keeps the finished + * runs. On a failure it reports how many runs of each side reached disk. + */ +export const runAbRounds = Effect.fn("serverMetrics.abRounds")(function* < + A, + S, + E, + R, + ES, + RS, +>(options: { + readonly rounds: number; + readonly outDir: string; + readonly runSide: (side: 0 | 1) => Effect.Effect; + readonly save: (side: 0 | 1, runs: ReadonlyArray) => Effect.Effect; +}) { + const runs: [A[], A[]] = [[], []]; + const persisted = [0, 0]; + const saveSide = Effect.fn("serverMetrics.abSave")(function* (side: 0 | 1) { + const count = runs[side].length; + const saved = yield* options.save(side, runs[side]); + persisted[side] = count; + return saved; + }); + const saved: [S, S] = [yield* saveSide(0), yield* saveSide(1)]; + yield* Effect.gen(function* () { + for (let round = 0; round < options.rounds; round++) { + // A B, then B A, so a drift in machine load lands on both sides. + for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) { + yield* Console.error(`round ${round + 1}/${options.rounds}: ${side === 0 ? "A" : "B"}`); + runs[side].push(yield* options.runSide(side)); + saved[side] = yield* saveSide(side); + } + } + }).pipe( + Effect.onError(() => + Console.error( + `ab stopped early; ${options.outDir} keeps ${persisted[0]} A and ${persisted[1]} B runs`, + ), + ), + ); + return saved; }); /** Prints the comparison and sets exit code 1 when a metric got worse. */ @@ -2375,20 +2423,21 @@ const abCommand = Command.make( yield* withSeed(unseeded[0], input), yield* withSeed(unseeded[1], input), ] as const; - const runs: [Measured[], Measured[]] = [[], []]; - for (let round = 0; round < input.rounds; round++) { - // A B, then B A, so a drift in machine load lands on both sides. - for (const side of round % 2 === 0 ? ([0, 1] as const) : ([1, 0] as const)) { - yield* Console.error(`round ${round + 1}/${input.rounds}: ${side === 0 ? "A" : "B"}`); - runs[side].push((yield* runOnce(sides[side])).measured); - } - } - const loadAfter = yield* machineLoad; - const before: ServerMetrics = { meta: { ...metas[0], loadAfter }, runs: runs[0] }; - const after: ServerMetrics = { meta: { ...metas[1], loadAfter }, runs: runs[1] }; - yield* writeMetrics(Option.some(path.join(outDir, "a.json")), before); - yield* writeMetrics(Option.some(path.join(outDir, "b.json")), after); - yield* report(before, after, input.threshold); + // Written up front and after every run; compare takes unequal run counts. + const saved = yield* runAbRounds({ + rounds: input.rounds, + outDir, + runSide: (side) => runOnce(sides[side]).pipe(Effect.map((run) => run.measured)), + save: Effect.fn("serverMetrics.abSaveFile")(function* (side, runs) { + const file: ServerMetrics = { + meta: { ...metas[side], loadAfter: yield* machineLoad }, + runs: [...runs], + }; + yield* writeMetrics(Option.some(path.join(outDir, side === 0 ? "a.json" : "b.json")), file); + return file; + }), + }); + yield* report(saved[0], saved[1], input.threshold); }, Effect.scoped), ).pipe( Command.withDescription( From 337e8f00d68bd0fc8ca66c1d715fbb238fd38b4c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:17:08 -0800 Subject: [PATCH 137/221] fix(server): saving a workflow no longer blocks workflow calls until running agent steps finish (#41751) --- apps/server/src/workflows/WorkflowEngine.ts | 57 ++++- .../src/workflows/WorkflowRuntime.test.ts | 74 +++++- apps/server/src/workflows/stepServices.ts | 2 + apps/server/src/workflows/workflow.ts | 5 + apps/server/src/workflows/workflowAgent.ts | 221 +++++++++++++----- 5 files changed, 294 insertions(+), 65 deletions(-) diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts index 77ff4cf0ada2e..5e6509dd33647 100644 --- a/apps/server/src/workflows/WorkflowEngine.ts +++ b/apps/server/src/workflows/WorkflowEngine.ts @@ -44,6 +44,7 @@ import { import { issueReference, noteFor, stepReferences } from "./runReferences.ts"; import { forStep, KeyValues, layerKeyValues, EngineLink, layerEngineLink } from "./stepServices.ts"; import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { settleTurn, TurnEnd, TurnWatch } from "./workflowAgent.ts"; import { type Issue, isSettled, @@ -87,6 +88,8 @@ const DELIVERY_HEADERS = [ "idempotency-key", ]; const CANCEL_WAITS = Duration.seconds(30); +const decodeTurnWatch = Schema.decodeUnknownEffect(Schema.toCodecJson(TurnWatch)); +const encodeTurnEnd = Schema.encodeEffect(Schema.toCodecJson(TurnEnd)); // Times of day are the server's own, as they are for scheduled tasks. const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone); @@ -193,6 +196,49 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( yield* send(wait, value); }); + // Agent turns being watched now, by run and wait. The fibers live in the engine's scope, so a + // reload stops them at once and the next engine picks the turns up from their open waits. + const watchingTurns = new Set(); + const seeTurn = Effect.fn("WorkflowEngine.seeTurn")(function* (wait: WorkflowStore.WaitRow) { + const id = `${wait.run_id}/${wait.name}`; + // Taken before the first yield: the wait's own step and the sweep can both ask at once. + if (watchingTurns.has(id)) return; + watchingTurns.add(id); + const watch = yield* decodeTurnWatch(WorkflowStore.jsonValue(wait.watch_json ?? "null")).pipe( + Effect.option, + ); + if (Option.isNone(watch)) { + watchingTurns.delete(id); + return; + } + yield* settleTurn(watch.value).pipe( + Effect.flatMap(encodeTurnEnd), + Effect.catch((error) => encodeTurnEnd({ lost: text(error) })), + Effect.flatMap( + Effect.fnUntraced(function* (end) { + const woke = { expired: false, value: end as Schema.Json }; + if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke); + }), + ), + Effect.provideService(WorkflowAgents, agents), + Effect.provideContext(stepReferences(store, wait.run_id, watch.value.agent.step)), + Effect.provideService(SqlClient.SafeIntegers, false), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : Effect.logWarning("A workflow could not see an agent's turn through", cause).pipe( + Effect.annotateLogs({ wait: id }), + ), + ), + Effect.ensuring(Effect.sync(() => watchingTurns.delete(id))), + Effect.forkIn(scope), + ); + }); + const watchTurn = Effect.fn("WorkflowEngine.watchTurn")(function* (runId: string, name: string) { + const wait = yield* store.waitAt({ runId, wait: name }); + if (wait !== undefined) yield* seeTurn(wait); + }); + const start: Workflows["Service"]["start"] = Effect.fn("Workflows.start")( function* (name, input, options) { // A parent written against one version of a child must not get another one's payload. @@ -450,13 +496,17 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( const fireWatches = Effect.gen(function* () { const now = DateTime.toEpochMillis(yield* DateTime.now); for (const wait of yield* store.watches) { + const watched = WorkflowStore.jsonValue(wait.watch_json ?? "null"); + // An agent's turn is watched by a fiber of its own, started again here after a reload. + if (typeof watched === "object" && watched !== null && "agent" in watched) { + yield* seeTurn(wait); + continue; + } const id = `watch:${wait.run_id}/${wait.name}`; const last = lookedAt.get(id); if (last !== undefined && now - last < Duration.toMillis(LOOK_EVERY)) continue; lookedAt.set(id, now); - const watch = WorkflowStore.jsonValue( - wait.watch_json ?? "null", - ) as unknown as PullRequestWatch; + const watch = watched as unknown as PullRequestWatch; yield* forge.pullRequests.read(watch.pullRequest as PullRequestAddress).pipe( // Each look keeps where the pull request stands on the wait's own step. Effect.provideContext(stepReferences(store, wait.run_id, wait.name)), @@ -939,6 +989,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* ( signalAll, start, ended, + watchTurn, cancel: (runId, reason) => cancel(runId, reason), list: Effect.fn("WorkflowEngine.list")(function* (filter) { return (yield* store.runsWhere(filter)).map((row) => ({ diff --git a/apps/server/src/workflows/WorkflowRuntime.test.ts b/apps/server/src/workflows/WorkflowRuntime.test.ts index 344e6d871efd9..62403042de1bc 100644 --- a/apps/server/src/workflows/WorkflowRuntime.test.ts +++ b/apps/server/src/workflows/WorkflowRuntime.test.ts @@ -3,7 +3,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Context from "effect/Context"; +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 FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -15,7 +18,7 @@ import * as TestClock from "effect/testing/TestClock"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; -import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { type AgentResult, WorkflowAgents } from "./WorkflowAgents.ts"; import * as WorkflowEngine from "./WorkflowEngine.ts"; import * as WorkflowRuntime from "./WorkflowRuntime.ts"; import { engineTag, type WorkflowDefinition } from "./workflow.ts"; @@ -39,6 +42,7 @@ workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.Stri const setup = Effect.fn("setup")(function* ( wrap: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem = (fileSystem) => fileSystem, engine?: (definitions: ReadonlyArray) => Layer.Layer, + agents?: WorkflowAgents["Service"], ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -54,7 +58,11 @@ const setup = Effect.fn("setup")(function* ( (definitions: ReadonlyArray) => engine?.(definitions) ?? WorkflowEngine.layer(definitions).pipe( - Layer.provide(Layer.mock(WorkflowAgents)({})), + Layer.provide( + agents === undefined + ? Layer.mock(WorkflowAgents)({}) + : Layer.succeed(WorkflowAgents, agents), + ), Layer.provide(database), Layer.provide(NodeCrypto.layer), ), @@ -424,6 +432,68 @@ it.effect("a change held back by a run goes in once that run ends, with no furth }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); +it.effect( + "a reload does not wait for an agent that is still at work, and its step ends with the turn", + () => + Effect.gen(function* () { + const ended = yield* Deferred.make(); + const started = yield* Deferred.make(); + const { fileSystem, at, runtime } = yield* setup(undefined, undefined, { + start: (input) => + Effect.as(Deferred.succeed(started, undefined), { + threadId: "thread", + turnId: input.key, + }), + result: () => Deferred.await(ended), + interrupt: () => Effect.succeed("stopped" as const), + }); + yield* fileSystem.writeFileString( + at("helper.ts"), + `T3.workflow("helper", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map(T3.agent("work", { brief: "Do it.", project: "p" }), (done) => done.value), +); +`, + ); + const ticking = (effect: Effect.Effect) => + Effect.raceFirst(effect, Effect.forever(TestClock.adjust("1 second"))); + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const helped = yield* ticking( + Effect.gen(function* () { + const run = yield* workflows.start("helper", {}, { idempotencyKey: "a" }); + yield* Deferred.await(started); + yield* workflows.waitFor(run.runId, (row) => row.status === "waiting"); + return run; + }), + ); + + // The test clock stands still during the save, so an engine that waited for the agent's + // step to finish would never stop: the step is not given up on, and the turn does not end. + // The swap cannot be interrupted, so a stuck save is unblocked by ending the turn. + const saving = yield* Effect.forkChild(definitions.save("greet.ts", greet("hello"))); + const saved = yield* Fiber.await(saving).pipe( + Effect.timeoutOption("10 seconds"), + TestClock.withLive, + ); + if (Option.isNone(saved)) { + yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "late" }); + yield* ticking(Fiber.await(saving)); + assert.fail("The reload waited for the agent's turn to end."); + } + assert.isTrue(Exit.isSuccess(saved.value) && saved.value.value.changed); + assert.equal((yield* workflows.get(helped.runId)).run.status, "waiting"); + + // The turn ends after the reload, and the new engine carries its result into the run. + yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "all done" }); + const done = yield* ticking( + workflows.waitFor(helped.runId, (run) => run.status === "completed"), + ); + assert.equal(done.result, "all done"); + }).pipe(Effect.provide(runtime), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + it.effect( "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again", () => diff --git a/apps/server/src/workflows/stepServices.ts b/apps/server/src/workflows/stepServices.ts index 53c6773494c3b..bdfd63b23d856 100644 --- a/apps/server/src/workflows/stepServices.ts +++ b/apps/server/src/workflows/stepServices.ts @@ -117,6 +117,8 @@ export class EngineLink extends Context.Service< readonly list: ListRuns; /** Tell the run that invoked `runId`, if one did, how it ended. */ readonly ended: (runId: string) => Effect.Effect; + /** Watch the agent turn behind an open wait of `runId` until it ends. */ + readonly watchTurn: (runId: string, wait: string) => Effect.Effect; } | undefined; /** The steps of each run that are running in this process right now. */ diff --git a/apps/server/src/workflows/workflow.ts b/apps/server/src/workflows/workflow.ts index bad9b9f513a97..34bb7ffb20a18 100644 --- a/apps/server/src/workflows/workflow.ts +++ b/apps/server/src/workflows/workflow.ts @@ -67,6 +67,8 @@ export class RunContext extends Context.Service< readonly forStep: (name: string) => Context.Context; /** The steps running now, which a cancelled run's cleanup waits for. */ readonly inFlight: InFlight; + /** Have the engine see the agent turn behind the open wait `wait` through, and wake it. */ + readonly watchTurn: (wait: string) => Effect.Effect; } >()("t3/workflows/workflow/RunContext") {} @@ -867,6 +869,9 @@ export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWo names: new Set(), forStep: (name) => forStep(store, keyValues, link, forge, runId, name), inFlight: link.inFlight, + watchTurn: Effect.fn("RunContext.watchTurn")(function* (wait: string) { + if (link.current !== undefined) yield* link.current.watchTurn(runId, wait); + }), }), ), ); diff --git a/apps/server/src/workflows/workflowAgent.ts b/apps/server/src/workflows/workflowAgent.ts index 03956086b03c8..e53b68d571391 100644 --- a/apps/server/src/workflows/workflowAgent.ts +++ b/apps/server/src/workflows/workflowAgent.ts @@ -6,6 +6,7 @@ import { identity } from "effect/Function"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import { Activity, DurableDeferred } from "effect/workflow"; import { checkOptions } from "./options.ts"; import { stepReferences } from "./runReferences.ts"; @@ -17,6 +18,7 @@ import { type StepFailed, text, waitAs, + wakeOf, } from "./workflow.ts"; import type { IssueAddress } from "./WorkflowForge.ts"; import { @@ -26,6 +28,7 @@ import { AgentTurn, WorkflowAgents, } from "./WorkflowAgents.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; /** A thread an agent step ran in, to hand to a later step that should continue it. */ export interface AgentThread { @@ -92,6 +95,97 @@ const NEW_THREAD_OPTIONS = [ "interactionMode", ] as const; +/** What the engine needs to see one turn of an agent step through to its end. */ +export const TurnWatch = Schema.Struct({ + agent: Schema.Struct({ + step: Schema.String, + turn: AgentTurn, + startedAt: Schema.optional(Schema.Number), + timeoutMs: Schema.optional(Schema.Number), + quietMs: Schema.optional(Schema.Number), + owesOutput: Schema.Boolean, + onFailure: Schema.Literals(["pause", "return"]), + }), +}); +export type TurnWatch = typeof TurnWatch.Type; + +/** How a watched turn ended: its result, or why it could not be read, which pauses the run. */ +export const TurnEnd = Schema.Union([ + Schema.Struct({ result: AgentResult }), + Schema.Struct({ lost: Schema.String }), +]); +export type TurnEnd = typeof TurnEnd.Type; + +/** The turn's result, or its thread stopped when the step's time is up. */ +export const settleTurn = Effect.fn("workflow.agent.settle")(function* ({ + agent: watch, +}: TurnWatch): Effect.fn.Return { + const agents = yield* WorkflowAgents; + const { turn, startedAt } = watch; + const threadOf = { threadId: turn.threadId, environment: turn.environment }; + const resultOf = (quiet: number | undefined) => + agents + .result(turn, { quiet: quiet === undefined ? undefined : Duration.millis(quiet) }) + .pipe( + watch.onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), + ), + ); + const settled = Effect.gen(function* () { + if (watch.timeoutMs === undefined || startedAt === undefined) { + return yield* resultOf(watch.quietMs); + } + const limit = Duration.millis(watch.timeoutMs); + const left = startedAt + watch.timeoutMs - (yield* Clock.currentTimeMillis); + const result = yield* resultOf(watch.quietMs).pipe( + Effect.timeoutOption(Duration.millis(Math.max(0, left))), + ); + if (Option.isSome(result)) return result.value; + // A stop that still fails pauses the run, so resuming tries the stop again. A step that + // returns its failure says the turn may still be running. + const stopping = agents + .interrupt({ ...threadOf, turnId: turn.turnId }) + .pipe(Effect.retry({ times: 2 })); + const stop: "stopped" | "ended" | "failed" = yield* watch.onFailure === "pause" + ? stopping + : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); + const late = `it was not done after ${Duration.format(limit)}`; + if (stop === "ended") { + // The turn ended before it could be stopped, maybe long ago, as a run that resumes late + // finds it. What it left is the answer when it is one. + const ended = yield* resultOf(undefined); + if (ended.ending !== "completed" || !watch.owesOutput || ended.output !== undefined) { + return ended; + } + // Stopping the later turn it may answer from could stop someone else's. + return { + ending: "stopped" as const, + detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, + reply: "", + }; + } + return { + ending: "stopped" as const, + detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, + reply: "", + }; + }); + return yield* settled.pipe( + Effect.map((result): TurnEnd => ({ result })), + Effect.catch((error) => Effect.succeed({ lost: text(error) })), + ); +}); + +// An agent turn's wait takes no signal from outside: only the engine's watch ends it. +const NOTHING_FITS = WorkflowStore.jsonText({ not: {} }); +// A result journaled when the wait for a turn still ran inside its activity, which kept the +// engine from stopping, and every workflow call with it, until the turn ended. +const Opened = Schema.Union([AgentResult, Schema.Struct({ ending: Schema.Literal("watching") })]); +const decodeTurnEnd = Schema.decodeUnknownEffect(Schema.toCodecJson(TurnEnd)); +const encodeWatch = Schema.encodeEffect(Schema.toCodecJson(TurnWatch)); + const attempt = Effect.fn("workflow.agent")(function* ( name: string, options: AgentOptions, @@ -121,6 +215,10 @@ const attempt = Effect.fn("workflow.agent")(function* ( const outputCodec = options.returns === undefined ? undefined : Schema.toCodecJson(options.returns); const decodeOutput = outputCodec === undefined ? undefined : Schema.decodeEffect(outputCodec); + const timeoutMs = + options.timeout === undefined + ? undefined + : Duration.toMillis(Duration.fromInputUnsafe(options.timeout)); const threadOf = (turn: AgentTurn): AgentThread => ({ threadId: turn.threadId, ...(turn.environment === undefined ? {} : { environment: turn.environment }), @@ -174,61 +272,73 @@ const attempt = Effect.fn("workflow.agent")(function* ( Effect.succeed({ threadId: "", turnId: "", failed: text(error) }), ), ); - const resultOf = (turn: AgentTurn, wait = { quiet }) => - agents - .result(turn, wait) - .pipe( - Effect.provideContext(touches), - onFailure === "pause" - ? identity - : Effect.catch((error) => - Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), - ), - ); - /** The turn's result, or its thread stopped when the step's time is up. */ - const within = Effect.fn("workflow.agent.within")(function* ( + /** + * The turn's result. The engine watches the turn outside the run and wakes the run once it + * ends, so an engine that stops while an agent works is not held up by it. + */ + const ended = Effect.fn("workflow.agent.ended")(function* ( turn: AgentTurn, startedAt: number | undefined, + round: number, + correction: number, ) { - if (options.timeout === undefined || startedAt === undefined) return yield* resultOf(turn); - const limit = Duration.fromInputUnsafe(options.timeout); - const left = startedAt + Duration.toMillis(limit) - (yield* Clock.currentTimeMillis); - const result = yield* resultOf(turn).pipe( - Effect.timeoutOption(Duration.millis(Math.max(0, left))), + const watch = WorkflowStore.jsonText( + yield* encodeWatch({ + agent: { + step: name, + turn, + startedAt, + timeoutMs, + quietMs: quiet === undefined ? undefined : Duration.toMillis(quiet), + owesOutput: outputSchema !== undefined, + onFailure, + }, + }).pipe(Effect.orDie), ); - if (Option.isSome(result)) return result.value; - // A stop that still fails pauses the run unrecorded, so resuming tries the stop again. A step - // that returns its failure says the turn may still be running. - const stopping = agents - .interrupt({ ...threadOf(turn), turnId: turn.turnId }) - .pipe(Effect.retry({ times: 2 })); - const stop: "stopped" | "ended" | "failed" = yield* onFailure === "pause" - ? stopping - : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); - const late = `it was not done after ${Duration.format(limit)}`; - if (stop === "ended") { - // The turn ended before it could be stopped, maybe long ago, as a run that resumes late - // finds it. What it left is the answer when it is one. - const ended = yield* resultOf(turn, { quiet: undefined }); - if ( - ended.ending !== "completed" || - outputSchema === undefined || - ended.output !== undefined - ) { - return ended; - } - // Stopping the later turn it may answer from could stop someone else's. - return { - ending: "stopped" as const, - detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, - reply: "", - }; + const first = `agent/${name}/${round}/result/${correction}`; + for (let lost = 0; ; lost++) { + const at = lost === 0 ? first : `${first}/again/${lost}`; + const wake = wakeOf(at); + const token = yield* DurableDeferred.token(wake); + const opened = yield* journaled( + run, + name, + at, + Opened, + Effect.gen(function* () { + yield* run.store.runStatus(run.runId, "waiting", `agent ${name}`); + yield* run.store.waitOpened({ + runId: run.runId, + name: at, + workflow: run.workflow, + key: undefined, + token, + schemaJson: NOTHING_FITS, + requestJson: null, + watchJson: watch, + deadline: null, + }); + yield* run.watchTurn(at); + return { ending: "watching" as const }; + }), + ); + if (opened.ending !== "watching") return opened; + const woke = yield* DurableDeferred.await(wake); + const end = yield* Effect.orDie(decodeTurnEnd(woke.value)); + yield* Activity.make({ name: `${at}/close`, execute: run.store.waitClosed(run.runId, at) }); + if ("result" in end) return end.result; + // Fails the first time it is reached, which pauses the run here. Resuming the run reaches + // it again, and the turn is watched once more. + yield* journaled( + run, + name, + `${at}/lost`, + Schema.Void, + Effect.flatMap(run.store.mark(run.runId, `${at}/lost`), (arrivals) => + arrivals > 1 ? Effect.void : Effect.fail(end.lost), + ), + ); } - return { - ending: "stopped" as const, - detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, - reply: "", - }; }); const done = (round: number, produced: Schema.Json, said?: string) => journaled( @@ -263,16 +373,7 @@ const attempt = Effect.fn("workflow.agent")(function* ( let stopped = false; let died = false; for (let correction = 0; turn.failed === undefined; correction++) { - const result = yield* journaled( - run, - name, - `agent/${name}/${round}/result/${correction}`, - AgentResult, - Effect.andThen( - run.store.runStatus(run.runId, "waiting", `agent ${name}`), - within(turn, startedAt), - ), - ); + const result = yield* ended(turn, startedAt, round, correction); if (result.ending !== "completed") { stopped = result.ending === "stopped"; died = result.ending === "failed"; From 5bf6b122b5edc8b89184151ba6436a81cfb346e6 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:29:19 +0100 Subject: [PATCH 138/221] fix(web): a long pull request search no longer ends in a broken character (#41838) Co-authored-by: Julius Marminge --- .../pullRequest/PullRequestListEmptyState.tsx | 4 +++- ...quest-search-keeps-whole-characters.e2e.ts | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 scripts/scenarios/pull-request-search-keeps-whole-characters.e2e.ts diff --git a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx index 7edf26efc3acc..c5e26dfd6e67e 100644 --- a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx @@ -1,4 +1,5 @@ import { RefreshIcon } from "~/components/ui/refresh-icon"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { T, useGT, Var } from "gt-react"; import { PlusIcon, SearchIcon } from "lucide-react"; @@ -70,7 +71,8 @@ export function PullRequestListEmptyState({ onRefresh: () => void; }) { const gt = useGT(); - const shownQuery = query.length > 48 ? `${query.slice(0, 48)}…` : query; + const shownQuery = + query.length > 48 ? `${query.slice(0, splitsSurrogatePair(query, 48) ? 47 : 48)}…` : query; if (!hasProjects) { return ( diff --git a/scripts/scenarios/pull-request-search-keeps-whole-characters.e2e.ts b/scripts/scenarios/pull-request-search-keeps-whole-characters.e2e.ts new file mode 100644 index 0000000000000..f28695fa19bfd --- /dev/null +++ b/scripts/scenarios/pull-request-search-keeps-whole-characters.e2e.ts @@ -0,0 +1,21 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const KEPT = "a".repeat(47); +// The emoji's two UTF-16 units straddle unit 48, where the shown search is cut. +const QUERY = `${KEPT}😀 and the rest of the search`; + +test( + "A long pull request search that matches nothing ends without a broken character", + WEB, + async ({ t3, app, screen }) => { + await t3.project("demo"); + await t3.open(`/pull-requests?${new URLSearchParams({ q: QUERY })}`); + + const title = screen.getByText(/^Nothing matches/); + await title.waitFor({ timeout: 60_000 }); + await app.screenshot("no-matches"); + await expect(title).toHaveText(`Nothing matches “${KEPT}…”`); + }, +); From a5d86e6382bee1fbe82e0dac8c2a92f2a8adaa77 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:31:08 -0800 Subject: [PATCH 139/221] fix(web): Push on the default branch no longer commits files changed while confirming (#41844) --- .../components/GitActionsControl.logic.test.ts | 16 ++++++++++++++++ .../src/components/GitActionsControl.logic.ts | 4 ++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 13b6ed8982513..87b076271807e 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -128,6 +128,22 @@ describe("when: on default ref without open PR", () => { }); }); + it("resolveQuickAction pushes without committing when the tree is clean and ahead", () => { + const withUpstream = resolveQuickAction( + status({ refName: "main", aheadCount: 1 }), + false, + true, + ); + assert.deepInclude(withUpstream, { kind: "run_action", action: "push", label: "Push" }); + + const withoutUpstream = resolveQuickAction( + status({ refName: "main", aheadCount: 1, hasUpstream: false }), + false, + true, + ); + assert.deepInclude(withoutUpstream, { kind: "run_action", action: "push", label: "Push" }); + }); + it("offers a feature branch only to actions that commit the changes", () => { const reason = (action: DefaultBranchConfirmableAction, hasWorkingTreeChanges: boolean) => resolveFeatureBranchUnavailableReason({ action, branchName: "main", hasWorkingTreeChanges }); diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index 81ab7a51ad3db..eb13b53f95d7d 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -401,7 +401,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultRef ? "commit_push" : "push", + action: "push", }; } return { @@ -439,7 +439,7 @@ export function resolveQuickAction( label: resolve(msg("Push", { $context: "verb, git action" })), disabled: false, kind: "run_action", - action: isDefaultRef ? "commit_push" : "push", + action: "push", }; } return { From 061717307335d95b67a8fa677ee5c437a230839d Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 20:35:20 -0600 Subject: [PATCH 140/221] fix(cli): t3 policy check expands ~ in the policy file path (#41848) Co-authored-by: Julius Marminge --- apps/server/src/cli/policy.test.ts | 21 +++++++++++++++++++++ apps/server/src/cli/policy.ts | 5 +++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/policy.test.ts b/apps/server/src/cli/policy.test.ts index d06998ff42882..04e29808078c1 100644 --- a/apps/server/src/cli/policy.test.ts +++ b/apps/server/src/cli/policy.test.ts @@ -9,6 +9,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { Command } from "effect/cli"; +import * as TestConsole from "effect/testing/TestConsole"; import { cli } from "../binCli.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; @@ -85,4 +86,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => { ); }), ); + + it.effect("check reads a ~/ policy file from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-check-" }); + const file = path.join(home, "policy.json"); + yield* fs.writeFileString( + file, + JSON.stringify({ schemaVersion: 1, organization: "Tilde Corp" }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })(["policy", "check", "~/policy.json"]).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provide(NetService.layer), + ); + + assert.include((yield* TestConsole.logLines).join("\n"), `Managed by Tilde Corp (${file}`); + }).pipe(Effect.provide(Layer.fresh(TestConsole.layer))), + ); }); diff --git a/apps/server/src/cli/policy.ts b/apps/server/src/cli/policy.ts index c48e2bc535a6f..e8badd9123615 100644 --- a/apps/server/src/cli/policy.ts +++ b/apps/server/src/cli/policy.ts @@ -96,14 +96,15 @@ const checkCommand = Command.make("check", { Command.withDescription("Validate a policy file before deploying it."), Command.withHandler( Effect.fn("cli.policy.check")(function* ({ file }) { + const policyFile = yield* expandHomePath(file); // Startup treats a missing file as no policy; a draft that is not there checks nothing. - if (!(yield* (yield* FileSystem.FileSystem).exists(file))) { + if (!(yield* (yield* FileSystem.FileSystem).exists(policyFile))) { return yield* new CliError.UserError({ cause: file, userMessage: `No policy file at ${file}.`, }); } - const policy = yield* ManagedPolicy.load(file); + const policy = yield* ManagedPolicy.load(policyFile); yield* Console.log(describePolicy(policy, yield* ManagedPolicy.loadedPolicy(policy))); }), ), From 57ffba5dfb0a39de4de7abbb6d69ce15ac3074d7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:35:49 -0800 Subject: [PATCH 141/221] fix(ssh): a second desktop no longer stops a remote server it did not launch (#41842) --- packages/ssh/src/tunnel.test.ts | 56 +++++++++++++++++++++++++++++++++ packages/ssh/src/tunnel.ts | 54 ++++++++++++++++++++++--------- 2 files changed, 96 insertions(+), 14 deletions(-) diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index f123820ccd191..2f7874ff08f58 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -1612,6 +1612,62 @@ server.listen(Number(flag("--port") ?? 0), "127.0.0.1", () => { }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.live( + "another desktop with the same connection details neither owns nor stops the server", + () => + Effect.gen(function* () { + const { fs, home, fakeServer, sshAsLocalShell, stateDir } = + yield* prepare("an unrelated process"); + const launch = (launcherId: string) => + SshTunnel.launchOrReuseRemoteServer( + target, + undefined, + { nodeScriptPath: fakeServer }, + launcherId, + ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, sshAsLocalShell)); + const runtimePid = fs + .readFileString(`${home}/.t3/userdata/server-runtime.json`) + .pipe(Effect.map((runtime) => Number(JSON.parse(runtime).pid))); + + assert.equal((yield* launch("a".repeat(32))).remoteServerKind, "managed"); + const serverPid = yield* runtimePid; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + try { + process.kill(serverPid, "SIGKILL"); + } catch {} + }), + ); + + const otherDesktop = yield* launch("b".repeat(32)); + assert.equal( + yield* fs.readFileString(`${stateDir}/launcher`), + `${"a".repeat(32)}\n`, + "the second desktop recorded itself as the server's launcher", + ); + assert.equal(otherDesktop.remoteServerKind, "external"); + + const layer = Layer.mergeAll( + NodeServices.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, sshAsLocalShell), + Layer.succeed(HttpClient.HttpClient, testHttpClient), + Layer.succeed(NetService.NetService, testNetService), + SshAuth.SshPasswordPrompt.disabledLayer, + SshTunnel.SshEnvironmentManager.layer({ + resolveCliRunner: Effect.succeed(ARCHIVE), + resolveLauncherId: Effect.succeed("b".repeat(32)), + }), + ); + yield* Effect.flatMap(SshTunnel.SshEnvironmentManager, (manager) => + manager.disconnectEnvironment(target), + ).pipe(Effect.provide(layer)); + assert.isTrue( + yield* isRunning(serverPid), + "the second desktop's disconnect stopped the server the first desktop launched", + ); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.live.each(staleIds)("disconnecting does not signal %s named by the managed pid file", (kind) => Effect.gen(function* () { const { fs, holder, sshAsLocalShell, staleId, stateDir } = yield* prepare(kind); diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 401af98a92335..8a50f7c45c892 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -702,7 +702,14 @@ if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then RUNNER_CHANGED=1 fi mv "$RUNNER_NEXT" "$RUNNER_FILE" -if [ -n "$LAUNCHER_ID" ]; then +# Desktops with the same connection details share this record. A server +# another desktop launched is only borrowed: it is neither replaced nor +# claimed here, and that desktop's ID stays on record. +RECORDED_LAUNCHER="$(cat "$STATE_DIR/launcher" 2>/dev/null || true)" +FOREIGN_LAUNCHER=0 +if [ -n "$LAUNCHER_ID" ] && [ -n "$RECORDED_LAUNCHER" ] && [ "$RECORDED_LAUNCHER" != "$LAUNCHER_ID" ]; then + FOREIGN_LAUNCHER=1 +elif [ -n "$LAUNCHER_ID" ]; then printf '%s\\n' "$LAUNCHER_ID" >"$STATE_DIR/launcher" fi pick_port() { @@ -897,6 +904,8 @@ if adopt_default_server && [ -n "$ADOPTED_PID" ] && [ -n "$LAUNCHER_ID" ]; then printf 'managed\\n' >"$MANAGED_FILE" printf 'external\\n' >"$SIBLING_DIR/managed" rm -f "$SIBLING_DIR/pid" + printf '%s\\n' "$LAUNCHER_ID" >"$STATE_DIR/launcher" + FOREIGN_LAUNCHER=0 RUNNER_CHANGED=1 if cmp -s "$RUNNER_FILE" "$SIBLING_DIR/run-t3.sh"; then RUNNER_CHANGED=0 @@ -917,7 +926,7 @@ if [ "$REMOTE_MANAGED" = "external" ]; then elif [ -n "$REMOTE_PORT" ] && managed_server_running "$REMOTE_PID"; then # Reconnect owns the local tunnel, not the lifetime of an already running # server. A changed runner is the update path and replaces an older server. - if [ "$RUNNER_CHANGED" -eq 1 ] && ! keeps_running_server; then + if [ "$RUNNER_CHANGED" -eq 1 ] && [ "$FOREIGN_LAUNCHER" -eq 0 ] && ! keeps_running_server; then kill "$REMOTE_PID" 2>/dev/null || true wait_for_pid_exit "$REMOTE_PID" REMOTE_PID="" @@ -935,6 +944,8 @@ elif [ -n "$REMOTE_PORT" ] && managed_server_running "$REMOTE_PID"; then elif ! wait_ready "@@T3_READY_TIMEOUT_MS@@"; then printf 'Remote T3 server is still running but did not become ready. Retry the connection; the server was left running.\\n' >&2 exit 1 + elif [ "$FOREIGN_LAUNCHER" -eq 1 ]; then + REMOTE_MANAGED="external" fi else REMOTE_PID="" @@ -1022,8 +1033,10 @@ if [ -z "$REMOTE_PORT" ]; then printf '%s\\n' "$REMOTE_PID" >"$PID_FILE" printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE" printf 'managed\\n' >"$MANAGED_FILE" - # A stop keeps the launcher file; it must not name this server's owner. - if [ -z "$LAUNCHER_ID" ]; then + # A stop keeps the launcher file; it must name this server's owner. + if [ -n "$LAUNCHER_ID" ]; then + printf '%s\\n' "$LAUNCHER_ID" >"$STATE_DIR/launcher" + else rm -f "$STATE_DIR/launcher" fi if ! wait_ready "@@T3_READY_TIMEOUT_MS@@"; then @@ -1082,6 +1095,13 @@ STATE_DIR="$HOME/.t3/ssh-launch/@@T3_STATE_KEY@@" PID_FILE="$STATE_DIR/pid" PORT_FILE="$STATE_DIR/port" MANAGED_FILE="$STATE_DIR/managed" +LAUNCHER_ID="@@T3_LAUNCHER_ID@@" +RECORDED_LAUNCHER="$(cat "$STATE_DIR/launcher" 2>/dev/null || true)" +# Another desktop with the same connection details launched this server. +if [ -n "$LAUNCHER_ID" ] && [ -n "$RECORDED_LAUNCHER" ] && [ "$RECORDED_LAUNCHER" != "$LAUNCHER_ID" ]; then + printf '{"stopped":false}\\n' + exit 0 +fi REMOTE_MANAGED="$(cat "$MANAGED_FILE" 2>/dev/null || true)" REMOTE_PID="$(cat "$PID_FILE" 2>/dev/null || true)" @@T3_MANAGED_SERVER_RUNNING_SCRIPT@@ @@ -1200,9 +1220,14 @@ function buildRemotePairingScript(stateKey: string, input?: RemoteT3RunnerOption }); } -function buildRemoteStopScript(stateKey: string): string { +// Launcher IDs are interpolated into remote shell commands, so only hex passes. +const validLauncherId = (launcherId: string | null | undefined) => + typeof launcherId === "string" && /^[0-9a-f]{32}$/u.test(launcherId) ? launcherId : null; + +function buildRemoteStopScript(stateKey: string, launcherId: string | null): string { return applyScriptPlaceholders(REMOTE_STOP_SCRIPT, { T3_STATE_KEY: stateKey, + T3_LAUNCHER_ID: launcherId ?? "", T3_MANAGED_SERVER_RUNNING_SCRIPT: REMOTE_MANAGED_SERVER_RUNNING_SCRIPT, }); } @@ -1235,11 +1260,8 @@ export const launchOrReuseRemoteServer = Effect.fn("ssh/tunnel.launchOrReuseRemo ChildProcessSpawner.ChildProcessSpawner | Digest.Digest | FileSystem.FileSystem | Path.Path > { const stateKey = yield* remoteStateKey(target); - // The launcher ID is interpolated into the remote shell command, so only hex passes. - const launchArgs = - typeof launcherId === "string" && /^[0-9a-f]{32}$/u.test(launcherId) - ? `${stateKey} ${launcherId}` - : stateKey; + const validId = validLauncherId(launcherId); + const launchArgs = validId === null ? stateKey : `${stateKey} ${validId}`; yield* Effect.logInfo("ssh.remoteServer.launch.start", { ...sshTargetLogFields(target), ...sshRunnerLogFields(runner), @@ -1348,6 +1370,7 @@ export const issueRemotePairingToken = Effect.fn("ssh/tunnel.issueRemotePairingT const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( target: DesktopSshEnvironmentTarget, input?: SshAuth.SshAuthOptions, + launcherId?: string | null, ): Effect.fn.Return< void, SshCommandError | SshInvalidTargetError, @@ -1360,7 +1383,7 @@ const stopRemoteServer = Effect.fn("ssh/tunnel.stopRemoteServer")(function* ( }); yield* runSshCommand(target, { remoteCommandArgs: ["sh", "-s"], - stdin: buildRemoteStopScript(stateKey), + stdin: buildRemoteStopScript(stateKey, validLauncherId(launcherId)), ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), @@ -1790,6 +1813,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma const tunnels = new Map(); const targetLocks = yield* KeyedLock.make(); const authSecrets = new Map(); + const resolveLauncherId = options.resolveLauncherId ?? Effect.succeed(null); // Keep one lock per target so reconnect cannot reuse a server while stop is pending. const withTargetLock = Effect.fn("ssh/tunnel.withTargetLock")(function* ( @@ -1951,8 +1975,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma ...sshRunnerLogFields(input.runner), key: input.key, }); - const launcherId = - options.resolveLauncherId === undefined ? null : yield* options.resolveLauncherId; + const launcherId = yield* resolveLauncherId; const remoteLaunch = yield* runWithSshAuth({ key: input.key, target: input.resolvedTarget, @@ -2038,6 +2061,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma remotePort: tunnelEntry.remotePort, }); const authSecret = authSecrets.get(tunnelEntry.key) ?? null; + const launcherId = yield* resolveLauncherId; yield* stopRemoteServer( tunnelEntry.target, authSecret === null @@ -2050,6 +2074,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma batchMode: "no", interactiveAuth: true, }, + launcherId, ).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawnerService), Effect.provideService(Digest.Digest, digestService), @@ -2255,10 +2280,11 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma yield* closeTunnelEntry(entry); }).pipe(Effect.uninterruptible); } + const launcherId = yield* resolveLauncherId; yield* runWithSshAuth({ key, target: resolvedTarget, - operation: (authOptions) => stopRemoteServer(resolvedTarget, authOptions), + operation: (authOptions) => stopRemoteServer(resolvedTarget, authOptions, launcherId), }); yield* Effect.logInfo("ssh.environment.disconnect.succeeded", { ...sshTargetLogFields(resolvedTarget), From e632155b3a1dcf18121cf730f393245f071fa8c9 Mon Sep 17 00:00:00 2001 From: Arman Charan Date: Tue, 24 Nov 2026 12:40:50 +1000 Subject: [PATCH 142/221] fix(claude): measure context from the last main-model pass (#41816) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 70 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 21 +++--- 2 files changed, 80 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index ebf6500441ba7..297527393aaa1 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -10601,6 +10601,76 @@ describe("ClaudeAdapterV2 background wake turns", () => { : [], ); + it.effect("measures Claude context from the last main-model pass in an advisor response", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-advisor-context"), + text: "Continue.", + attachments: [], + }), + ); + const usage = { + input_tokens: 4, + cache_read_input_tokens: 1087272, + cache_creation_input_tokens: 1222, + output_tokens: 711, + iterations: [ + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 543529, + cache_creation_input_tokens: 214, + output_tokens: 268, + }, + { type: "advisor_message", input_tokens: 545497, output_tokens: 3144 }, + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 543743, + cache_creation_input_tokens: 1008, + output_tokens: 443, + }, + ], + }; + for (const frame of [ + usageStreamFrame({ + type: "message_start", + message: { id: "msg_advisor", usage: zeroUsage }, + }), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage, + }), + usageSnapshotFrame("msg_snapshot_only", "00000000-0000-4000-8000-000000000690", { + ...zeroUsage, + iterations: [ + ...usage.iterations, + { type: "advisor_message", input_tokens: 547000, output_tokens: 25 }, + ], + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000691", result: "Done." }), + ]) + yield* Queue.offer(harness.sdkMessages, frame); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual(reportedContextTokens(harness.events), [545196, 545196]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("reports context from final stream usage when the request starts at zero", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 7d16f5afba3c2..f5993b8a1824a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -315,6 +315,7 @@ function claudeMessageInputTokens(usage: { export function claudeProviderTurnTokenUsage( usage: { + readonly iterations?: SDKAssistantMessage["message"]["usage"]["iterations"] | undefined; readonly input_tokens?: number | null | undefined; readonly cache_creation_input_tokens?: number | null | undefined; readonly cache_read_input_tokens?: number | null | undefined; @@ -326,9 +327,11 @@ export function claudeProviderTurnTokenUsage( autoCompactWindow = "", requestedAt?: DateTime.Utc, ) { - const inputTokens = claudeMessageInputTokens(usage); - const outputTokens = optionalClaudeUsageTokenCount(usage.output_tokens) ?? 0; - const cachedInputTokens = optionalClaudeUsageTokenCount(usage.cache_read_input_tokens) ?? 0; + // After an advisor call, the response totals can count the same context twice. + const sample = usage.iterations?.findLast((iteration) => iteration.type === "message") ?? usage; + const inputTokens = claudeMessageInputTokens(sample); + const outputTokens = optionalClaudeUsageTokenCount(sample.output_tokens) ?? 0; + const cachedInputTokens = optionalClaudeUsageTokenCount(sample.cache_read_input_tokens) ?? 0; const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation); // The cache lifetime starts with the request, not when its response ends. const promptCacheExpiresAt = @@ -354,15 +357,11 @@ type ClaudeMessageUsage = Parameters[0]; // message_delta usage is per-message cumulative; null or absent fields retain message_start values and zeros replace them. function mergeClaudeStreamUsage( current: ClaudeMessageUsage, - delta: { - readonly input_tokens?: number | null | undefined; - readonly cache_creation_input_tokens?: number | null | undefined; - readonly cache_read_input_tokens?: number | null | undefined; - readonly output_tokens?: number | null | undefined; - }, + delta: ClaudeMessageUsage, ): ClaudeMessageUsage { return { ...current, + iterations: delta.iterations ?? current.iterations, input_tokens: optionalClaudeUsageTokenCount(delta.input_tokens) ?? optionalClaudeUsageTokenCount(current.input_tokens) ?? @@ -6715,8 +6714,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( context.autoCompactWindow, context.streamUsage?.requestedAt, ); - if (typeof usage !== "number") { - if (claudeMessageInputTokens(usage) <= 0) return; + if ("inputTokens" in tokenUsage) { + if (tokenUsage.inputTokens <= 0) return; context.compactionTokens = undefined; } yield* emitProviderEvent({ From ededa85fe3e140f1b43a067d0586be3ea8649dae Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 23 Nov 2026 21:47:42 -0500 Subject: [PATCH 143/221] fix(server): closing an Android emulator with shutdown no longer leaves its session stuck open (#41840) Co-authored-by: Julius Marminge --- apps/server/src/device/DeviceHubOperations.ts | 40 ++++++++- apps/server/src/device/DeviceService.test.ts | 86 ++++++++++++++++++- 2 files changed, 120 insertions(+), 6 deletions(-) diff --git a/apps/server/src/device/DeviceHubOperations.ts b/apps/server/src/device/DeviceHubOperations.ts index 3a1bcee7a8e2a..9dbc7d6ca64b4 100644 --- a/apps/server/src/device/DeviceHubOperations.ts +++ b/apps/server/src/device/DeviceHubOperations.ts @@ -14,6 +14,9 @@ import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost const BOOT_TIMEOUT = Duration.minutes(3); const SCREENSHOT_TIMEOUT = Duration.seconds(20); +// The hub's Android shutdown waits up to 30 s for the emulator to leave adb after the kill. +const ANDROID_SHUTDOWN_TIMEOUT = Duration.seconds(45); +const ADB_DEVICES_TIMEOUT = Duration.seconds(10); // Let the hub's 30 s simctl timeout report its cause first. const LIST_TIMEOUT_SECONDS = 40; // expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes. @@ -296,11 +299,26 @@ export const makeDeviceHubOperations = (options: { ? attachIosStream(device.id, "open").pipe(Effect.asVoid) : Effect.void; + // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an + // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer + // lists its serial in any state. + const emulatorExited = (serial: string) => + /^emulator-\d+$/.test(serial) + ? run("adb", ["devices"], { timeoutMs: Duration.toMillis(ADB_DEVICES_TIMEOUT) }).pipe( + Effect.map( + ({ code, stdout }) => + code === 0 && + !stdout.split(/\r?\n/).some((line) => line.trim().split(/\s+/)[0] === serial), + ), + Effect.orElseSucceed(() => false), + ) + : Effect.succeed(false); + const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")( function* (device) { - const postShutdown = (path: string, body: Record) => + const postShutdown = (path: string, body: Record, timeout?: Duration.Input) => postJson(path, body, "shutdown").pipe( - Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")), + Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown", timeout)), Effect.flatMap((result) => result.ok ? Effect.void @@ -329,7 +347,23 @@ export const makeDeviceHubOperations = (options: { ), ), ) - : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id }); + : postShutdown( + "/api/devices/shutdown", + { platform: device.platform, id: device.id }, + ANDROID_SHUTDOWN_TIMEOUT, + ).pipe( + Effect.catch((cause) => + emulatorExited(device.id).pipe( + Effect.flatMap((exited) => + exited + ? Effect.logInfo("Android emulator has exited", { + deviceId: device.id, + }) + : Effect.fail(cause), + ), + ), + ), + ); }, ); diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 00e942f1e6df5..972a9a2b150b2 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -18,6 +18,7 @@ import { SshCommandError } from "@t3tools/ssh/errors"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; @@ -192,7 +193,14 @@ const fixture = Effect.fn("fixture")(function* ( const listing = { hangs: false, requested: yield* Deferred.make() }; let booted = false; let shutDown = false; - const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false }; + const connection = { + online: true, + kind: "local" as "local" | "ssh", + failShutdown: false, + shutdownDelay: undefined as Duration.Input | undefined, + adbDevices: undefined as { code: number; stdout: string; stderr: string } | undefined, + }; + const shutdownRequested = yield* Deferred.make(); const http = HttpClient.make((request) => Effect.gen(function* () { requests.push(request.url); @@ -230,6 +238,8 @@ const fixture = Effect.fn("fixture")(function* ( return HttpClientResponse.fromWeb(request, new Response(yield* Ref.get(screenshotBody))); } if (request.url.endsWith("/shutdown")) { + yield* Deferred.succeed(shutdownRequested, undefined); + if (connection.shutdownDelay !== undefined) yield* Effect.sleep(connection.shutdownDelay); if (connection.failShutdown) return HttpClientResponse.fromWeb(request, Response.json({ ok: false })); shutDown = true; @@ -283,10 +293,19 @@ const fixture = Effect.fn("fixture")(function* ( ); }), ); - const run = (command: string) => + const run = (command: string, args: ReadonlyArray) => command === "emulator" ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }) - : Ref.get(encoderResult); + : command === "adb" && args.join(" ") === "devices" + ? Effect.sync( + () => + connection.adbDevices ?? { + code: 0, + stdout: `List of devices attached\n${booted ? "emulator-5554\tdevice\n" : ""}`, + stderr: "", + }, + ) + : Ref.get(encoderResult); const ready: DeviceHost.DeviceHostReady = { nodePath: process.execPath, hub: { origin: "http://device.test" }, @@ -426,6 +445,7 @@ const fixture = Effect.fn("fixture")(function* ( iosAvailable, listing, endDevice, + shutdownRequested, }; }); @@ -1574,6 +1594,66 @@ it.effect.each([ }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))), ); +describe("Android close with shutdown", () => { + const openEmulator = Effect.fn("openEmulator")(function* () { + const harness = yield* fixture(); + yield* harness.service.configure({ enabled: true }); + const threadId = ThreadId.make("android-close"); + const session = yield* harness.service.open({ + threadId, + deviceId: "Pixel_API_35", + platform: "android", + }); + expect(session.deviceId).toBe("emulator-5554"); + return { ...harness, threadId }; + }); + + it.effect("closes the session on a retry once the emulator has exited", () => + Effect.gen(function* () { + const { service, connection, endDevice, threadId } = yield* openEmulator(); + // The hub's `adb emu kill` fails once the serial is gone, so every attempt is rejected. + connection.failShutdown = true; + const first = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(first)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + + endDevice(); + yield* service.close({ threadId, shutdown: true }); + expect((yield* service.state).sessions).toEqual([]); + }), + ); + + it.effect.each([ + { + adb: "lists it offline", + result: { code: 0, stdout: "List of devices attached\nemulator-5554\toffline\n", stderr: "" }, + }, + { adb: "fails", result: { code: 1, stdout: "", stderr: "adb: no server" } }, + ])("keeps the session after a rejected shutdown when adb $adb", ({ result }) => + Effect.gen(function* () { + const { service, connection, threadId } = yield* openEmulator(); + connection.failShutdown = true; + connection.adbDevices = result; + const exit = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(exit)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + }), + ); + + it.effect("waits for an emulator the hub takes longer than 15 seconds to see exit", () => + Effect.gen(function* () { + const { service, connection, shutdownRequested, threadId } = yield* openEmulator(); + // The hub allows the emulator 30 seconds to leave adb after the kill. + connection.shutdownDelay = Duration.seconds(25); + const closing = yield* Effect.forkChild(service.close({ threadId, shutdown: true })); + yield* Deferred.await(shutdownRequested); + yield* TestClock.adjust(Duration.seconds(25)); + expect(Exit.isSuccess(yield* Fiber.await(closing))).toBe(true); + expect((yield* service.state).sessions).toEqual([]); + }), + ); +}); + it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])( "retains hub inventory on %s when AVD enumeration fails and recovers on retry", (hostId) => From 8ef195587d53f99ac0464c706422f6ae067e4666 Mon Sep 17 00:00:00 2001 From: Afshin Jalili <153820238+AfshinJalili@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:21:39 +0330 Subject: [PATCH 144/221] fix(web): tell update-all users where to update desktop servers it can't reach (#33030) Co-authored-by: Julius Marminge --- .../sidebar/updateEverything.logic.test.ts | 31 +++++++++++++------ .../sidebar/updateEverything.logic.ts | 12 +++++-- 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 +- 12 files changed, 51 insertions(+), 22 deletions(-) diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts index f4b1d0053b22b..ea44f1592a956 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts @@ -45,6 +45,20 @@ function machine( }; } +// A desktop-mode server the desktop app cannot control, such as a WSL backend or an older app. +function withoutDesktopControl(base: UpdateEverythingMachine): UpdateEverythingMachine { + return { + ...base, + serverConfig: { + ...base.serverConfig!, + environment: { + ...base.serverConfig!.environment, + capabilities: { repositoryIdentity: true, serverSelfUpdate: "desktop-managed" }, + }, + }, + }; +} + describe("collectServerUpdateTargets", () => { it("updates remote servers that can move to the target and names every skipped one", () => { const { targets, skipped } = collectServerUpdateTargets( @@ -67,6 +81,7 @@ describe("collectServerUpdateTargets", () => { machine("current", "0.0.50", "boot-service"), machine("current-offline", "0.0.50", "boot-service", { connected: false }), machine("manual", "0.0.40", undefined), + withoutDesktopControl(machine("wsl-backend", "0.0.40", "desktop-managed")), ], "0.0.50", ); @@ -82,6 +97,7 @@ describe("collectServerUpdateTargets", () => { ["no-scope", "no permission"], ["busy", "already updating"], ["manual", "needs a manual update"], + ["wsl-backend", "update T3 Code on that machine"], ]); }); @@ -230,15 +246,9 @@ describe("collectChannelSwitchTargets", () => { host(machine("service", "0.1.2", "boot-service"), 70), // A Stable tag built a migration the latest Nightly does not have yet. host(machine("ahead", "0.1.3", "boot-service"), 73), - machine("old-desktop", "0.1.2", "desktop-managed", { - serverConfig: { - ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!, - environment: { - ...machine("old-desktop", "0.1.2", "desktop-managed").serverConfig!.environment, - capabilities: { repositoryIdentity: true, serverSelfUpdate: "desktop-managed" }, - }, - }, - }), + withoutDesktopControl(machine("old-desktop", "0.1.2", "desktop-managed")), + // Already on Nightly, so it needs an update rather than a channel switch. + withoutDesktopControl(machine("behind-desktop", OLD_NIGHTLY, "desktop-managed")), machine("current", NIGHTLY, "boot-service"), // The server refuses a track its policy rules out, so the dialog skips it up front. managedHost(host(machine("no-nightly", "0.1.2", "boot-service"), 70)), @@ -254,7 +264,8 @@ describe("collectChannelSwitchTargets", () => { "ahead", `its database has changes ${NIGHTLY} does not support yet; stay on Stable until Nightly has them`, ], - ["old-desktop", "needs a newer desktop app"], + ["old-desktop", "change the update track on that machine"], + ["behind-desktop", "update T3 Code on that machine"], [ "no-nightly", "Example Corp manages T3 Code updates. Only stable releases can be installed.", diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts index 6930549adf19b..f9bf0976a22e4 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.ts @@ -70,6 +70,10 @@ export interface SkippedMachine { readonly reason: string; } +// Desktop servers without the desktop control fd (older apps, WSL backends: wsl.exe cannot pass +// fds) cannot be updated from here, and their desktop app is not necessarily the stale part. +const UPDATE_ON_THAT_MACHINE = msg("update T3 Code on that machine"); + /** Skip current and app-hosted servers; the latter update with the app and would relaunch mid-run. * Desktop-managed servers use their own feed. Each server's updater checks that it can install the * release before it restarts, so no registry precheck runs here. */ @@ -115,7 +119,7 @@ export function collectServerUpdateTargets( continue; } if (selfUpdate === "desktop-managed" && !desktopAppUpdate) { - skip(resolve(msg("needs a newer desktop app"))); + skip(resolve(UPDATE_ON_THAT_MACHINE)); continue; } const serverChannel = cliReleaseChannelOf(config.environment.serverVersion); @@ -425,7 +429,11 @@ function trackSwitchMove( if (selfUpdate === null) return { skip: resolve(msg("needs a manual update")) }; if (selfUpdate !== "desktop-managed") return { selfUpdate }; if (config.environment.capabilities.desktopAppChannelSwitch !== true) { - return { skip: resolve(msg("needs a newer desktop app")) }; + return { + skip: resolve( + sameTrack ? UPDATE_ON_THAT_MACHINE : msg("change the update track on that machine"), + ), + }; } // Squirrel.Mac renames the bundle for the new track and then cannot relaunch it. if (!sameTrack && config.environment.platform.os === "darwin") { diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 4d3d656f33916..bafbe7d7cb731 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12145,7 +12145,8 @@ "f938bb483eb3d189": "startet zuletzt neu", "9bca02be2b4d612a": "nicht verbunden", "2dcc418b6a13b83c": "erfordert manuelles Update", - "5c8ebc36f84dee7a": "erfordert eine neuere Desktop-App", + "f13e08bd3614112e": "T3 Code auf diesem Rechner aktualisieren", + "3c3348c36a2695af": "Update-Kanal auf diesem Rechner ändern", "fa8faa732a2688ef": "im Kanal {channel}", "9b961309baafa09d": "keine Berechtigung", "9bafb2622c22d145": "wird bereits aktualisiert", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index da9e327abf64f..cde4bbb9458fa 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12153,7 +12153,8 @@ "f938bb483eb3d189": "restarts last", "9bca02be2b4d612a": "not connected", "2dcc418b6a13b83c": "needs a manual update", - "5c8ebc36f84dee7a": "needs a newer desktop app", + "f13e08bd3614112e": "update T3 Code on that machine", + "3c3348c36a2695af": "change the update track on that machine", "fa8faa732a2688ef": "on the {channel} channel", "9b961309baafa09d": "no permission", "9bafb2622c22d145": "already updating", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index ff24104e8075f..ee4496f0bfbc5 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12138,7 +12138,8 @@ "f938bb483eb3d189": "se reinicia el último", "9bca02be2b4d612a": "sin conexión", "2dcc418b6a13b83c": "requiere una actualización manual", - "5c8ebc36f84dee7a": "requiere una app de escritorio más reciente", + "f13e08bd3614112e": "actualiza T3 Code en ese equipo", + "3c3348c36a2695af": "cambia el canal de actualizaciones en ese equipo", "fa8faa732a2688ef": "en el canal {channel}", "9b961309baafa09d": "sin permiso", "9bafb2622c22d145": "ya se está actualizando", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 64b28506bfe6a..dfb02854b6c38 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12143,7 +12143,8 @@ "f938bb483eb3d189": "redémarre en dernier", "9bca02be2b4d612a": "non connecté", "2dcc418b6a13b83c": "nécessite une mise à jour manuelle", - "5c8ebc36f84dee7a": "nécessite une version plus récente de l’app de bureau", + "f13e08bd3614112e": "mettez à jour T3 Code sur cette machine", + "3c3348c36a2695af": "changez le canal de mise à jour sur cette machine", "fa8faa732a2688ef": "sur le canal {channel}", "9b961309baafa09d": "pas d’autorisation", "9bafb2622c22d145": "déjà en cours de mise à jour", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index f4c1b792d77e2..bba2c66a1adf0 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12094,7 +12094,8 @@ "f938bb483eb3d189": "最後に再起動", "9bca02be2b4d612a": "未接続", "2dcc418b6a13b83c": "手動での更新が必要", - "5c8ebc36f84dee7a": "新しいデスクトップアプリが必要", + "f13e08bd3614112e": "そのマシンで T3 Code を更新してください", + "3c3348c36a2695af": "そのマシンで更新トラックを変更してください", "fa8faa732a2688ef": "{channel} チャネル", "9b961309baafa09d": "権限なし", "9bafb2622c22d145": "すでに更新中", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 0ef52c37295fc..988724e7b1c8f 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12090,7 +12090,8 @@ "f938bb483eb3d189": "마지막에 다시 시작", "9bca02be2b4d612a": "연결되지 않음", "2dcc418b6a13b83c": "수동 업데이트 필요", - "5c8ebc36f84dee7a": "최신 데스크톱 앱 필요", + "f13e08bd3614112e": "해당 기기에서 T3 Code를 업데이트하세요", + "3c3348c36a2695af": "해당 기기에서 업데이트 트랙을 변경하세요", "fa8faa732a2688ef": "{channel} 채널", "9b961309baafa09d": "권한 없음", "9bafb2622c22d145": "이미 업데이트 중", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index c7354ff24613d..286cde4c55168 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12143,7 +12143,8 @@ "f938bb483eb3d189": "reinicia por último", "9bca02be2b4d612a": "não conectado", "2dcc418b6a13b83c": "precisa de atualização manual", - "5c8ebc36f84dee7a": "precisa de um app desktop mais novo", + "f13e08bd3614112e": "atualize o T3 Code nessa máquina", + "3c3348c36a2695af": "mude o canal de atualização nessa máquina", "fa8faa732a2688ef": "no canal {channel}", "9b961309baafa09d": "sem permissão", "9bafb2622c22d145": "já está atualizando", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 20e9a76a10fa1..4fbe93bc7f506 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12144,7 +12144,8 @@ "f938bb483eb3d189": "перезапуск последним", "9bca02be2b4d612a": "не подключено", "2dcc418b6a13b83c": "нужно обновить вручную", - "5c8ebc36f84dee7a": "нужна более новая версия десктопного приложения", + "f13e08bd3614112e": "обновите T3 Code на этом компьютере", + "3c3348c36a2695af": "смените канал обновлений на этом компьютере", "fa8faa732a2688ef": "на канале {channel}", "9b961309baafa09d": "нет прав", "9bafb2622c22d145": "уже обновляется", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 946abe27ad7cd..6759119ee8a98 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12151,7 +12151,8 @@ "f938bb483eb3d189": "startar om sist", "9bca02be2b4d612a": "inte ansluten", "2dcc418b6a13b83c": "behöver uppdateras manuellt", - "5c8ebc36f84dee7a": "behöver en nyare skrivbordsapp", + "f13e08bd3614112e": "uppdatera T3 Code på den datorn", + "3c3348c36a2695af": "byt uppdateringsspår på den datorn", "fa8faa732a2688ef": "på kanalen {channel}", "9b961309baafa09d": "ingen behörighet", "9bafb2622c22d145": "uppdateras redan", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 34b76ab61689c..3e4d7229881f3 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12169,7 +12169,8 @@ "f938bb483eb3d189": "最后重启", "9bca02be2b4d612a": "未连接", "2dcc418b6a13b83c": "需要手动更新", - "5c8ebc36f84dee7a": "需要更高版本的桌面应用", + "f13e08bd3614112e": "请在该机器上更新 T3 Code", + "3c3348c36a2695af": "请在该机器上更改更新通道", "fa8faa732a2688ef": "使用 {channel} 通道", "9b961309baafa09d": "没有权限", "9bafb2622c22d145": "正在更新", From 0d90edcf0f97b0e89a7eca608048dd83128024d2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:55:46 -0800 Subject: [PATCH 145/221] fix(relay): APNs request spans and errors no longer record the request URL (#41859) Co-authored-by: Claude Fable 5.2 --- .../src/agentActivity/ApnsClient.test.ts | 100 ++++++++++++++++++ infra/relay/src/agentActivity/ApnsClient.ts | 21 +++- 2 files changed, 117 insertions(+), 4 deletions(-) diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.ts index f06c751982710..90da8ef10499c 100644 --- a/infra/relay/src/agentActivity/ApnsClient.test.ts +++ b/infra/relay/src/agentActivity/ApnsClient.test.ts @@ -4,11 +4,15 @@ import * as NodeCrypto from "node:crypto"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay"; import { describe, expect, it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; +import * as Tracer from "effect/Tracer"; import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientError from "effect/http/HttpClientError"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import type { ApnsCredentials } from "../Config.ts"; @@ -304,4 +308,100 @@ describe("ApnsClient", () => { ApnsProviderTokens.__resetApnsProviderTokenCacheForTest(); }).pipe(Effect.provide(layer)); }); + + it.effect("keeps device tokens out of spans, for delivered and failed requests", () => { + ApnsProviderTokens.__resetApnsProviderTokenCacheForTest(); + const { privateKey } = NodeCrypto.generateKeyPairSync("ec", { + namedCurve: "prime256v1", + privateKeyEncoding: { type: "pkcs8", format: "pem" }, + publicKeyEncoding: { type: "spki", format: "pem" }, + }); + const credentials = { + teamId: "team-spans", + keyId: "key-spans", + privateKey: Redacted.make(privateKey), + bundleId: "com.t3tools.test", + environment: "sandbox", + } satisfies ApnsCredentials; + const spans: Array = []; + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + spans.push(span); + return span; + }, + }); + const urls: Array = []; + let reachable = true; + const httpClient = HttpClient.make((request) => { + urls.push(request.url); + return reachable + ? Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))) + : Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ request, cause: new Error("reset") }), + }), + ); + }); + const layer = ApnsClient.layer.pipe( + Layer.provide(ApnsProviderTokens.layer), + Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)), + Layer.provideMerge(Layer.succeed(Tracer.Tracer, tracer)), + ); + + return Effect.gen(function* () { + const apns = yield* ApnsClient.ApnsClient; + const sendBoth = Effect.all( + [ + apns.sendLiveActivityRequest({ + credentials, + request: apns.makeLiveActivityRequest({ + event: "update", + token: "live-activity-device-token", + state, + nowEpochSeconds: 0, + nowIso: DateTime.formatIso(now), + }), + issuedAtUnixSeconds: 0, + }), + apns.sendPushNotificationRequest({ + credentials, + request: apns.makePushNotificationRequest({ + token: "push-notification-device-token", + notification: { + title: "Thread", + body: "Input: Project", + environmentId: "env", + threadId: "thread", + deepLink: "/threads/env/thread", + }, + }), + issuedAtUnixSeconds: 0, + }), + ], + { mode: "result" }, + ); + + yield* sendBoth; + reachable = false; + yield* sendBoth; + + expect(urls).toHaveLength(4); + expect(urls[0]).toContain("live-activity-device-token"); + expect(urls[1]).toContain("push-notification-device-token"); + const recorded = spans + .flatMap((span) => [ + span.name, + ...Array.from(span.attributes.values(), String), + ...(span.status._tag === "Ended" && Exit.isFailure(span.status.exit) + ? [Cause.pretty(span.status.exit.cause)] + : []), + ]) + .join("\n"); + expect(recorded).toContain("relay.apns.send_live_activity_request"); + expect(recorded).toContain("ApnsHttpRequestError"); + expect(recorded).not.toContain("device-token"); + ApnsProviderTokens.__resetApnsProviderTokenCacheForTest(); + }).pipe(Effect.provide(layer)); + }); }); diff --git a/infra/relay/src/agentActivity/ApnsClient.ts b/infra/relay/src/agentActivity/ApnsClient.ts index b21953c59eecc..b6311812365c7 100644 --- a/infra/relay/src/agentActivity/ApnsClient.ts +++ b/infra/relay/src/agentActivity/ApnsClient.ts @@ -6,6 +6,7 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Headers from "effect/http/Headers"; import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientError from "effect/http/HttpClientError"; import * as HttpClientRequest from "effect/http/HttpClientRequest"; import { ApnsEnvironment, type ApnsCredentials } from "../Config.ts"; import { MAX_SUMMARY_TEXT_LENGTH, truncateText } from "./agentActivityPayloads.ts"; @@ -236,6 +237,16 @@ function makePushNotificationRequest(input: { }; } +// The request URL ends in the device token. The client span records the URL, +// and so does an HTTP client error's message, so neither reaches telemetry. +const withoutClientSpan = Effect.provideService(HttpClient.TracerDisabledWhen, () => true); + +function causeWithoutRequestUrl(cause: unknown): unknown { + return HttpClientError.isHttpClientError(cause) + ? new Error(cause.reason._tag, { cause: cause.reason.cause }) + : cause; +} + function apnsReasonFromBody(body: string): string | undefined { if (body.trim().length === 0) { return undefined; @@ -289,6 +300,7 @@ const make = Effect.gen(function* () { }), HttpClientRequest.bodyJson(input.request.payload), Effect.flatMap(httpClient.execute), + withoutClientSpan, Effect.timeout(APNS_HTTP_STAGE_TIMEOUT), Effect.mapError( (cause) => @@ -300,7 +312,7 @@ const make = Effect.gen(function* () { tokenSuffix: input.request.token.slice(-8), stage: "send", status: null, - cause, + cause: causeWithoutRequestUrl(cause), }), ), ); @@ -316,7 +328,7 @@ const make = Effect.gen(function* () { tokenSuffix: input.request.token.slice(-8), stage: "read-response", status: response.status, - cause, + cause: causeWithoutRequestUrl(cause), }), ), ); @@ -351,6 +363,7 @@ const make = Effect.gen(function* () { }), HttpClientRequest.bodyJson(input.request.payload), Effect.flatMap(httpClient.execute), + withoutClientSpan, Effect.timeout(APNS_HTTP_STAGE_TIMEOUT), Effect.mapError( (cause) => @@ -362,7 +375,7 @@ const make = Effect.gen(function* () { tokenSuffix: input.request.token.slice(-8), stage: "send", status: null, - cause, + cause: causeWithoutRequestUrl(cause), }), ), ); @@ -378,7 +391,7 @@ const make = Effect.gen(function* () { tokenSuffix: input.request.token.slice(-8), stage: "read-response", status: response.status, - cause, + cause: causeWithoutRequestUrl(cause), }), ), ); From 4162207ddd63a2e066eb913f3e295733e1079def Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 18:58:19 -0800 Subject: [PATCH 146/221] fix(web): file menu opens remote files over SSH instead of on the server (#29771) --- apps/desktop/src/electron/ElectronMenu.ts | 18 ++ apps/web/src/components/chat/OpenInPicker.tsx | 154 +----------------- apps/web/src/components/editorIcons.ts | 152 +++++++++++++++++ .../src/components/files/FileBrowserPanel.tsx | 7 +- apps/web/src/contextMenuFallback.ts | 6 + apps/web/src/editorMenuIcons.tsx | 95 +++++++++++ apps/web/src/fileContextMenu.test.ts | 95 ++++++++++- apps/web/src/fileContextMenu.ts | 75 +++++++-- packages/contracts/src/ipc.ts | 4 + 9 files changed, 443 insertions(+), 163 deletions(-) create mode 100644 apps/web/src/components/editorIcons.ts create mode 100644 apps/web/src/editorMenuIcons.tsx diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index a967c75383447..48b61dbefd025 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -85,6 +85,7 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM disabled: sourceItem.disabled === true, ...(sourceItem.separatorBefore === true ? { separatorBefore: true } : {}), ...(typeof sourceItem.checked === "boolean" ? { checked: sourceItem.checked } : {}), + ...(typeof sourceItem.iconImage === "string" ? { iconImage: sourceItem.iconImage } : {}), }; if (sourceItem.children) { @@ -114,6 +115,17 @@ const normalizePosition = ( Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })), ); +// Renderer icons are 32px PNGs; a 2x representation keeps them 16pt and sharp on Retina. +function menuIconImage(dataUrl: string): Option.Option { + try { + const image = Electron.nativeImage.createEmpty(); + image.addRepresentation({ scaleFactor: 2, dataURL: dataUrl }); + return image.isEmpty() ? Option.none() : Option.some(image); + } catch { + return Option.none(); + } +} + /** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; @@ -179,6 +191,12 @@ export const make = Effect.gen(function* () { } else { itemOption.click = () => complete(Option.some(item.id)); } + if (item.iconImage !== undefined) { + const image = menuIconImage(item.iconImage); + if (Option.isSome(image)) { + itemOption.icon = image.value; + } + } if (item.destructive && (!item.children || item.children.length === 0)) { const destructiveIcon = getDestructiveMenuIcon(); if (Option.isSome(destructiveIcon)) { diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index 711f1e4cb3e63..fc125bbd79cfa 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -21,7 +21,7 @@ import { useRemoteOpenState, } from "../../remoteOpen"; import { useEnvironment } from "../../state/environments"; -import { ChevronDownIcon, FolderClosedIcon, SquareArrowOutUpRightIcon } from "lucide-react"; +import { ChevronDownIcon, SquareArrowOutUpRightIcon } from "lucide-react"; import { Group, GroupSeparator } from "../ui/group"; import { @@ -36,35 +36,9 @@ import { MenuTrigger, } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { - AntigravityIcon, - CursorIcon, - FileExplorerIcon, - FinderIcon, - Icon, - KiroIcon, - TraeIcon, - VisualStudioCode, - VisualStudioCodeInsiders, - VSCodium, - Zed, -} from "../Icons"; -import { - AquaIcon, - CLionIcon, - DataGripIcon, - DataSpellIcon, - GoLandIcon, - IntelliJIdeaIcon, - PhpStormIcon, - PyCharmIcon, - RiderIcon, - RubyMineIcon, - RustRoverIcon, - WebStormIcon, -} from "../JetBrainsIcons"; +import { type EditorIconOption, editorIconOptions } from "../editorIcons"; import { announce } from "~/lib/announce"; -import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils"; +import { cn } from "~/lib/utils"; import { shellEnvironment } from "~/state/shell"; import { useAtomCommand } from "~/state/use-atom-command"; import { @@ -77,131 +51,15 @@ import { import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { useComposerMenuState } from "./useComposerMenuState"; -type OpenInOption = { - label: string; - Icon: Icon; - value: EditorId; - kind: "brand" | "generic"; -}; +type OpenInOption = EditorIconOption & { label: string }; const resolveOpenInOptions = ( platform: string, availableEditors: ReadonlyArray, resolve: MessageResolver, -) => { - const baseOptions: ReadonlyArray> = [ - { - Icon: CursorIcon, - value: "cursor", - kind: "brand", - }, - { - Icon: TraeIcon, - value: "trae", - kind: "brand", - }, - { - Icon: KiroIcon, - value: "kiro", - kind: "brand", - }, - { - Icon: VisualStudioCode, - value: "vscode", - kind: "brand", - }, - { - Icon: VisualStudioCodeInsiders, - value: "vscode-insiders", - kind: "brand", - }, - { - Icon: VSCodium, - value: "vscodium", - kind: "brand", - }, - { - Icon: Zed, - value: "zed", - kind: "brand", - }, - { - Icon: AntigravityIcon, - value: "antigravity", - kind: "brand", - }, - { - Icon: IntelliJIdeaIcon, - value: "idea", - kind: "brand", - }, - { - Icon: AquaIcon, - value: "aqua", - kind: "brand", - }, - { - Icon: CLionIcon, - value: "clion", - kind: "brand", - }, - { - Icon: DataGripIcon, - value: "datagrip", - kind: "brand", - }, - { - Icon: DataSpellIcon, - value: "dataspell", - kind: "brand", - }, - { - Icon: GoLandIcon, - value: "goland", - kind: "brand", - }, - { - Icon: PhpStormIcon, - value: "phpstorm", - kind: "brand", - }, - { - Icon: PyCharmIcon, - value: "pycharm", - kind: "brand", - }, - { - Icon: RiderIcon, - value: "rider", - kind: "brand", - }, - { - Icon: RubyMineIcon, - value: "rubymine", - kind: "brand", - }, - { - Icon: RustRoverIcon, - value: "rustrover", - kind: "brand", - }, - { - Icon: WebStormIcon, - value: "webstorm", - kind: "brand", - }, - { - Icon: isMacPlatform(platform) - ? FinderIcon - : isWindowsPlatform(platform) - ? FileExplorerIcon - : FolderClosedIcon, - value: "file-manager", - kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic", - }, - ]; +): ReadonlyArray => { const availableEditorSet = new Set(availableEditors); - return baseOptions + return editorIconOptions(platform) .filter((option) => availableEditorSet.has(option.value)) .map((option) => ({ ...option, diff --git a/apps/web/src/components/editorIcons.ts b/apps/web/src/components/editorIcons.ts new file mode 100644 index 0000000000000..e9183e82d8e1b --- /dev/null +++ b/apps/web/src/components/editorIcons.ts @@ -0,0 +1,152 @@ +import type { EditorId } from "@t3tools/contracts"; +import { FolderClosedIcon } from "lucide-react"; + +import { isMacPlatform, isWindowsPlatform } from "~/lib/utils"; +import { + AntigravityIcon, + CursorIcon, + FileExplorerIcon, + FinderIcon, + type Icon, + KiroIcon, + TraeIcon, + VisualStudioCode, + VisualStudioCodeInsiders, + VSCodium, + Zed, +} from "./Icons"; +import { + AquaIcon, + CLionIcon, + DataGripIcon, + DataSpellIcon, + GoLandIcon, + IntelliJIdeaIcon, + PhpStormIcon, + PyCharmIcon, + RiderIcon, + RubyMineIcon, + RustRoverIcon, + WebStormIcon, +} from "./JetBrainsIcons"; + +export interface EditorIconOption { + readonly Icon: Icon; + readonly value: EditorId; + readonly kind: "brand" | "generic"; +} + +/** Editor logos in picker order. */ +export function editorIconOptions(platform: string): ReadonlyArray { + return [ + { + Icon: CursorIcon, + value: "cursor", + kind: "brand", + }, + { + Icon: TraeIcon, + value: "trae", + kind: "brand", + }, + { + Icon: KiroIcon, + value: "kiro", + kind: "brand", + }, + { + Icon: VisualStudioCode, + value: "vscode", + kind: "brand", + }, + { + Icon: VisualStudioCodeInsiders, + value: "vscode-insiders", + kind: "brand", + }, + { + Icon: VSCodium, + value: "vscodium", + kind: "brand", + }, + { + Icon: Zed, + value: "zed", + kind: "brand", + }, + { + Icon: AntigravityIcon, + value: "antigravity", + kind: "brand", + }, + { + Icon: IntelliJIdeaIcon, + value: "idea", + kind: "brand", + }, + { + Icon: AquaIcon, + value: "aqua", + kind: "brand", + }, + { + Icon: CLionIcon, + value: "clion", + kind: "brand", + }, + { + Icon: DataGripIcon, + value: "datagrip", + kind: "brand", + }, + { + Icon: DataSpellIcon, + value: "dataspell", + kind: "brand", + }, + { + Icon: GoLandIcon, + value: "goland", + kind: "brand", + }, + { + Icon: PhpStormIcon, + value: "phpstorm", + kind: "brand", + }, + { + Icon: PyCharmIcon, + value: "pycharm", + kind: "brand", + }, + { + Icon: RiderIcon, + value: "rider", + kind: "brand", + }, + { + Icon: RubyMineIcon, + value: "rubymine", + kind: "brand", + }, + { + Icon: RustRoverIcon, + value: "rustrover", + kind: "brand", + }, + { + Icon: WebStormIcon, + value: "webstorm", + kind: "brand", + }, + { + Icon: isMacPlatform(platform) + ? FinderIcon + : isWindowsPlatform(platform) + ? FileExplorerIcon + : FolderClosedIcon, + value: "file-manager", + kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic", + }, + ]; +} diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 399ec73301814..4609a8bacd089 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -235,7 +235,12 @@ export default function FileBrowserPanel({ const position = pointerIsFresh ? { x: pointer.x, y: pointer.y } : { x: anchorRect.left, y: anchorRect.bottom }; - const fileTarget = { environmentId, filePath: relativePath, workspaceRoot: cwd }; + const fileTarget = { + environmentId, + filePath: relativePath, + workspaceRoot: cwd, + isDirectory: item.kind === "directory", + }; const fileMenuItems = fileContextMenu.buildItems(fileTarget); // The app menu owns focus; the tree's outside-click handler would dismiss it before click. context.close({ restoreFocus: !pointerIsFresh }); diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 0002e68d114a2..7754e191f4722 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -469,6 +469,12 @@ export function showContextMenuFallback( spacer.setAttribute("aria-hidden", "true"); button.appendChild(spacer); } + } else if (typeof item.iconImage === "string") { + const image = document.createElement("img"); + image.src = item.iconImage; + image.alt = ""; + image.className = "size-4.5 shrink-0 sm:size-4"; + button.appendChild(image); } else if (typeof item.icon === "string") { const icon = createIconElement(item.icon, isLeafDestructive ? "destructive" : "neutral"); if (icon) { diff --git a/apps/web/src/editorMenuIcons.tsx b/apps/web/src/editorMenuIcons.tsx new file mode 100644 index 0000000000000..adbabbcabecb6 --- /dev/null +++ b/apps/web/src/editorMenuIcons.tsx @@ -0,0 +1,95 @@ +import type { EditorId } from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { Atom } from "effect/reactivity"; +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; + +import { editorIconOptions } from "./components/editorIcons"; +import { useTheme } from "./hooks/useTheme"; + +const ICON_PIXELS = 32; +const SVG_NS = "http://www.w3.org/2000/svg"; +const NO_ICONS: ReadonlyMap = new Map(); + +// Logos are styled by Tailwind and the theme, so render them in the document and inline the +// computed paint before rasterizing; native menus only accept bitmaps. +async function rasterizeEditorIcon(editor: EditorId): Promise { + const option = editorIconOptions(navigator.platform).find(({ value }) => value === editor); + if (option === undefined) return null; + const host = document.createElement("div"); + host.setAttribute("aria-hidden", "true"); + host.style.cssText = "position:fixed;left:-10000px;top:0;width:16px;height:16px;"; + document.body.append(host); + const root = createRoot(host); + try { + flushSync(() => + root.render( + , + ), + ); + const svg = host.querySelector("svg"); + if (svg === null) return null; + const clone = svg.cloneNode(true) as SVGSVGElement; + const sources = [svg, ...svg.querySelectorAll("*")]; + const targets = [clone, ...clone.querySelectorAll("*")]; + sources.forEach((source, index) => { + const computed = getComputedStyle(source); + const target = targets[index]; + target?.setAttribute( + "style", + `${target.getAttribute("style") ?? ""};fill:${computed.fill};stroke:${computed.stroke}`, + ); + }); + clone.removeAttribute("class"); + clone.setAttribute("xmlns", SVG_NS); + clone.setAttribute("width", String(ICON_PIXELS)); + clone.setAttribute("height", String(ICON_PIXELS)); + const image = new Image(); + image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(clone))}`; + await image.decode(); + const canvas = document.createElement("canvas"); + canvas.width = ICON_PIXELS; + canvas.height = ICON_PIXELS; + const context = canvas.getContext("2d"); + if (context === null) return null; + context.drawImage(image, 0, 0, ICON_PIXELS, ICON_PIXELS); + return canvas.toDataURL("image/png"); + } catch { + return null; + } finally { + root.unmount(); + host.remove(); + } +} + +// Keyed by theme and editor list; both change rarely, and each key rasterizes once. +const editorMenuIconsAtom = Atom.family((key: string) => + Atom.make((get): ReadonlyMap => { + const editors = key + .slice(key.indexOf("|") + 1) + .split(",") + .filter(Boolean) as EditorId[]; + // Render outside the reading component's render pass. + void Promise.resolve().then(async () => { + const icons = new Map(); + for (const editor of editors) { + const icon = await rasterizeEditorIcon(editor); + if (icon !== null) icons.set(editor, icon); + } + if (icons.size > 0) get.setSelf(icons); + }); + return NO_ICONS; + }).pipe(Atom.keepAlive, Atom.withLabel(`editor-menu-icons:${key}`)), +); + +/** PNG data URLs of editor logos for context menus; empty until rendered. */ +export function useEditorMenuIcons( + editors: ReadonlyArray, +): ReadonlyMap { + const { resolvedTheme } = useTheme(); + return useAtomValue(editorMenuIconsAtom(`${resolvedTheme}|${editors.join(",")}`)); +} diff --git a/apps/web/src/fileContextMenu.test.ts b/apps/web/src/fileContextMenu.test.ts index a5c74929d48ad..903c8c7bff7a4 100644 --- a/apps/web/src/fileContextMenu.test.ts +++ b/apps/web/src/fileContextMenu.test.ts @@ -1,7 +1,39 @@ import { EnvironmentId } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; -import { resolveFileContextMenuAbsolutePath } from "./fileContextMenu"; +import { resolveFileContextMenuAbsolutePath, useFileContextMenu } from "./fileContextMenu"; +import type { RemoteOpenResolution } from "./remoteOpen"; + +const state = vi.hoisted(() => ({ + remoteOpen: { state: { mode: "local-exec" }, isResolved: true } as RemoteOpenResolution, + openInEditor: vi.fn(async () => ({ _tag: "Success" })), + openRemoteEditorUrl: vi.fn(async (_url: string) => true), +})); + +vi.mock("@effect/atom-react", () => ({ + useAtomValue: () => ({ + availableEditors: ["cursor", "file-manager"], + shellRevealInFileManager: true, + shellRevealInFileManagerKind: "xdg-open", + environment: { platform: { os: "linux" } }, + }), +})); +vi.mock("gt-react", async (importOriginal) => ({ + ...(await importOriginal()), + useMessages: () => (text: string) => text, +})); +vi.mock(import("./state/session"), async (original) => ({ + ...(await original()), + useEnvironmentScope: () => true, +})); +vi.mock("./editorMenuIcons", () => ({ useEditorMenuIcons: () => new Map() })); +vi.mock("./state/use-atom-command", () => ({ useAtomCommand: () => state.openInEditor })); +vi.mock(import("./remoteOpen"), async (original) => ({ + ...(await original()), + useRemoteOpenResolution: () => state.remoteOpen, + useRemoteCapableEditors: () => ["vscode"], + openRemoteEditorUrl: state.openRemoteEditorUrl, +})); const BASE_TARGET = { environmentId: EnvironmentId.make("environment-local"), @@ -42,3 +74,62 @@ describe("resolveFileContextMenuAbsolutePath", () => { ).toBeNull(); }); }); + +describe("useFileContextMenu", () => { + it.each<[string, RemoteOpenResolution]>([ + ["remote-unavailable", { state: { mode: "remote-unavailable" }, isResolved: true }], + ["unresolved", { state: { mode: "local-exec" }, isResolved: false }], + ])("offers no open actions when remote open is %s", async (_mode, resolution) => { + state.remoteOpen = resolution; + state.openInEditor.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET)).toEqual([]); + await menu.activate("open", BASE_TARGET); + await menu.activate("editor:vscode", BASE_TARGET); + expect(state.openInEditor).not.toHaveBeenCalled(); + }); + + it("opens files over SSH remote links instead of on the server host", async () => { + state.remoteOpen = { + state: { mode: "remote-links", host: { kind: "ssh-alias", host: "box", username: "me" } }, + isResolved: true, + }; + state.openInEditor.mockClear(); + state.openRemoteEditorUrl.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET)).toEqual([ + { + id: "open-with", + label: "Open with", + children: [{ id: "editor:vscode", label: "VS Code" }], + }, + ]); + await menu.activate("open", BASE_TARGET); + await menu.activate("editor:vscode", BASE_TARGET); + await menu.activate("editor:vscode", { ...BASE_TARGET, filePath: "src", isDirectory: true }); + expect(state.openInEditor).not.toHaveBeenCalled(); + expect(state.openRemoteEditorUrl.mock.calls).toEqual([ + ["vscode://vscode-remote/ssh-remote+me%40box/workspace/project/src/index.ts:1:1"], + ["vscode://vscode-remote/ssh-remote+me%40box/workspace/project/src?windowId=_blank"], + ]); + }); + + it("opens files on the server host when remote open is local-exec", async () => { + state.remoteOpen = { state: { mode: "local-exec" }, isResolved: true }; + state.openInEditor.mockClear(); + const menu = useFileContextMenu(BASE_TARGET.environmentId); + + expect(menu.buildItems(BASE_TARGET).map((item) => item.id)).toEqual([ + "open", + "reveal-in-folder", + "open-with", + ]); + await menu.activate("open", BASE_TARGET); + expect(state.openInEditor).toHaveBeenCalledWith({ + environmentId: BASE_TARGET.environmentId, + input: { cwd: "/workspace/project/src/index.ts", editor: "file-manager" }, + }); + }); +}); diff --git a/apps/web/src/fileContextMenu.ts b/apps/web/src/fileContextMenu.ts index 58e17bff25367..28b1b4d2c950b 100644 --- a/apps/web/src/fileContextMenu.ts +++ b/apps/web/src/fileContextMenu.ts @@ -1,4 +1,6 @@ import { + AuthOrchestrationOperateScope, + buildRemoteOpenUrl, EDITORS, type ContextMenuItem, type EditorId, @@ -12,8 +14,15 @@ import { revealInFileExplorerLabelForKind, revealInFileExplorerLabelForOs, } from "~/components/preview/fileExplorerLabel"; +import { useEditorMenuIcons } from "./editorMenuIcons"; import { readLocalApi } from "./localApi"; +import { + openRemoteEditorUrl, + useRemoteCapableEditors, + useRemoteOpenResolution, +} from "./remoteOpen"; import { serverEnvironment } from "./state/server"; +import { useEnvironmentScope } from "./state/session"; import { shellEnvironment } from "./state/shell"; import { useAtomCommand } from "./state/use-atom-command"; import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; @@ -36,6 +45,7 @@ export interface FileContextMenuTarget { readonly filePath: string; readonly workspaceRoot: string | undefined; readonly repositoryRoot?: string | undefined; + readonly isDirectory?: boolean; } export function resolveFileContextMenuAbsolutePath(target: FileContextMenuTarget): string | null { @@ -64,6 +74,7 @@ export interface FileContextMenuCapabilities { function buildFileContextMenuItems(input: { readonly hasAbsolutePath: boolean; readonly capabilities: FileContextMenuCapabilities; + readonly editorIcons: ReadonlyMap; readonly resolve: MessageResolver; }): readonly ContextMenuItem[] { if (!input.hasAbsolutePath) return []; @@ -87,10 +98,14 @@ function buildFileContextMenuItems(input: { items.push({ id: "open-with", label: input.resolve(msg("Open with")), - children: editorIds.map((editorId) => ({ - id: `editor:${editorId}` as FileContextMenuAction, - label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId, - })), + children: editorIds.map((editorId) => { + const iconImage = input.editorIcons.get(editorId); + return { + id: `editor:${editorId}` as FileContextMenuAction, + label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId, + ...(iconImage === undefined ? {} : { iconImage }), + }; + }), }); } return items; @@ -101,20 +116,40 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const resolve = useMessages(); - const availableEditors = serverConfig?.availableEditors ?? []; + const remoteOpen = useRemoteOpenResolution(environmentId); + const remoteCapableEditors = useRemoteCapableEditors(); + const mode = environmentId !== null && remoteOpen.isResolved ? remoteOpen.state.mode : null; + // Shell actions run on the server host, which is the viewer's machine only in local-exec. + const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const isLocalExec = mode === "local-exec" && canOperateHost; + const remoteHost = remoteOpen.state.mode === "remote-links" ? remoteOpen.state.host : null; + + const availableEditors = isLocalExec + ? (serverConfig?.availableEditors ?? []) + : mode === "remote-links" + ? remoteCapableEditors + : []; const capabilities: FileContextMenuCapabilities = { // WSL can reveal in Windows Explorer despite reporting Linux; use server wording. revealLabel: - environmentId !== null && + isLocalExec && serverConfig?.shellRevealInFileManager === true && serverConfig.availableEditors.includes("file-manager") ? serverConfig.shellRevealInFileManagerKind === undefined ? revealInFileExplorerLabelForOs(serverConfig.environment.platform.os, resolve) : revealInFileExplorerLabelForKind(serverConfig.shellRevealInFileManagerKind, resolve) : undefined, - canOpenDefault: availableEditors.includes("file-manager"), + canOpenDefault: isLocalExec && availableEditors.includes("file-manager"), editorIds: availableEditors, }; + const editorIcons = useEditorMenuIcons(availableEditors); + + const editorFailureTitle = (editor: EditorId) => + resolve( + msg("Could not open in {editor}", { + editor: EDITOR_LABEL_BY_ID.get(editor) ?? editor, + }), + ); const activate = async ( action: FileContextMenuAction, @@ -128,8 +163,26 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { action === "open" || reveal ? ("file-manager" as const) : (action.slice("editor:".length) as EditorId); + if (action === "open" && !capabilities.canOpenDefault) return; + if (reveal && capabilities.revealLabel === undefined) return; if (action !== "open" && !reveal && !capabilities.editorIds.includes(editor)) return; + if (remoteHost !== null) { + const url = buildRemoteOpenUrl({ + editor, + ...remoteHost, + absolutePath, + isFile: target.isDirectory !== true, + }); + if (url !== undefined && (await openRemoteEditorUrl(url))) return; + toastManager.add({ + type: "error", + title: editorFailureTitle(editor), + description: absolutePath, + }); + return; + } + const result = await openInEditor({ environmentId, input: { cwd: absolutePath, editor, ...(reveal ? { reveal: true } : {}) }, @@ -142,11 +195,7 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { ? resolve(msg("Could not open file")) : reveal ? resolve(msg("Unable to reveal file")) - : resolve( - msg("Could not open in {editor}", { - editor: EDITOR_LABEL_BY_ID.get(editor) ?? editor, - }), - ), + : editorFailureTitle(editor), description: absolutePath, }); }; @@ -160,6 +209,7 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { const items = buildFileContextMenuItems({ hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null, capabilities, + editorIcons, resolve, }); if (items.length === 0 || api === undefined) return; @@ -173,6 +223,7 @@ export function useFileContextMenu(environmentId: EnvironmentId | null) { buildFileContextMenuItems({ hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null, capabilities, + editorIcons, resolve, }), capabilities, diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 45f55bde2b2d8..d323c9a26de26 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -29,6 +29,8 @@ export interface ContextMenuItem { disabled?: boolean; header?: boolean; icon?: string; + /** PNG data URL; takes precedence over `icon`. */ + iconImage?: string; separatorBefore?: boolean; checked?: boolean; children?: readonly ContextMenuItem[]; @@ -46,6 +48,7 @@ export interface ContextMenuItemSchemaType { readonly disabled?: boolean; readonly header?: boolean; readonly icon?: string; + readonly iconImage?: string; readonly separatorBefore?: boolean; readonly checked?: boolean; readonly children?: readonly ContextMenuItemSchemaType[]; @@ -59,6 +62,7 @@ export const ContextMenuItemSchema: Schema.Codec = Sc disabled: Schema.optionalKey(Schema.Boolean), header: Schema.optionalKey(Schema.Boolean), icon: Schema.optionalKey(Schema.String), + iconImage: Schema.optionalKey(Schema.String), separatorBefore: Schema.optionalKey(Schema.Boolean), checked: Schema.optionalKey(Schema.Boolean), children: Schema.optionalKey( From 74382f25300d5cfd0f5c7ad2fd9f948139588802 Mon Sep 17 00:00:00 2001 From: Ruphy <20857801+RaphaelMitas@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:59:39 +0100 Subject: [PATCH 147/221] fix(server): a foreground Claude subagent shows the model it ran on, not its parent's (#39729) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 127 ++++++++++++------ .../Adapters/ClaudeAdapterV2.ts | 9 +- 2 files changed, 93 insertions(+), 43 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 297527393aaa1..455e95441d50e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -21837,27 +21837,13 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("records a forked skill's model from its transcript instead of the parent's", () => - Effect.gen(function* () { - const harness = yield* makeWakeHarnessWithOptions({ - subagentModel: "claude-haiku-4-5-20251001", - }); - const now = yield* DateTime.now; - const parentModel = "claude-opus-4-6"; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-forked-skill-model"), - text: "/fork-probe go", - attachments: [], - modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: parentModel }, - }), - ); + it.effect.each([ + { + launch: "forked skill", + text: "/fork-probe go", // A `context: fork` skill has no Agent call and streams none of its own replies: // task_started carries no tool_use_id, and only its prompt echo names the fork. - for (const frame of [ + frames: [ claudeSdkFrame({ type: "system", subtype: "task_started", @@ -21888,28 +21874,93 @@ describe("ClaudeAdapterV2 background wake turns", () => { uuid: "00000000-0000-4000-8000-000000000233", session_id: WAKE_NATIVE_SESSION, }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.take(harness.terminalReceipts); + ], + }, + { + launch: "foreground Agent call with no streamed reply", + text: "Ask a subagent one thing.", + frames: [ + claudeSdkFrame({ + type: "assistant", + parent_tool_use_id: null, + message: { + model: "claude-opus-4-6", + id: "msg_unstreamed_model_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: "toolu-unstreamed-model", + name: "Agent", + input: { description: "One thing", prompt: "Check one thing." }, + }, + ], + }, + uuid: "00000000-0000-4000-8000-000000000235", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "task-unstreamed-model", + tool_use_id: "toolu-unstreamed-model", + description: "One thing", + task_type: "local_agent", + uuid: "00000000-0000-4000-8000-000000000236", + session_id: WAKE_NATIVE_SESSION, + }), + makeSubagentNotificationFrame({ + taskId: "task-unstreamed-model", + toolUseId: "toolu-unstreamed-model", + summary: "OK", + uuid: "00000000-0000-4000-8000-000000000237", + }), + ], + }, + ])( + "records the model of a $launch from its transcript instead of the parent's", + ({ text, frames }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + subagentModel: "claude-haiku-4-5-20251001", + }); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-transcript-model"), + text, + attachments: [], + modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: "claude-opus-4-6" }, + }), + ); + for (const frame of [ + ...frames, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.take(harness.terminalReceipts); - const fork = harness.events - .filter((event) => event.type === "subagent.updated") - .at(-1)?.subagent; - assert.equal(fork?.status, "completed"); - assert.equal(fork?.model, "claude-haiku-4-5"); - assert.equal(fork?.modelSelection?.model, "claude-haiku-4-5"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + const subagent = harness.events + .filter((event) => event.type === "subagent.updated") + .at(-1)?.subagent; + assert.equal(subagent?.status, "completed"); + assert.equal(subagent?.model, "claude-haiku-4-5"); + assert.equal(subagent?.modelSelection?.model, "claude-haiku-4-5"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), - ), ); it.effect.each([ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f5993b8a1824a..ab601a9d255e2 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -7650,9 +7650,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); - // A `context: fork` skill has no Agent call and streams none of its own frames; - // only its transcript records the model, written after the fork reports its outcome. - const forkedSkillModel = Effect.fnUntraced(function* ( + // A `context: fork` skill, or a foreground subagent whose replies were never streamed, + // leaves no model on any frame; only its transcript records it, written once it finishes. + const transcriptModel = Effect.fnUntraced(function* ( context: ActiveClaudeTurnContext, nativeThreadId: string, taskId: string, @@ -7660,7 +7660,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const registered = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId); if ( registered === undefined || - registered.runToolUseId !== null || registered.task.model !== null || registered.task.status === "running" ) { @@ -12424,7 +12423,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return next; }); for (const taskId of context.subagentsByTaskId.keys()) { - const model = yield* forkedSkillModel(context, liveQuery.nativeThreadId, taskId); + const model = yield* transcriptModel(context, liveQuery.nativeThreadId, taskId); const status = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId)?.task.status; if ( model !== undefined && From 30c5df09713d2acd10a587a0f649f507e08fc19c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:03:12 -0800 Subject: [PATCH 148/221] fix(server): a commit's diff is read only for commits the change request lists (#41863) Co-authored-by: Claude Fable 5.2 --- .../pullRequest/PullRequestService.test.ts | 63 +++++++++++++++++++ .../src/pullRequest/PullRequestService.ts | 63 ++++++++++++++----- 2 files changed, 112 insertions(+), 14 deletions(-) diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 5f25633b96047..8852e5f1fe058 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -5173,6 +5173,66 @@ it.effect("authorizes cold source reads with paginated paths without fetching pa }), ); +const activityListing = (...oids: ReadonlyArray) => ({ + getChangeRequestActivity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: oids.map((oid) => ({ + oid, + messageHeadline: "Change", + committedDate: "2026-01-01T00:00:00.000Z", + })), + }), +}); + +it.effect("reads a commit's diff only for a commit the change request lists", () => + Effect.gen(function* () { + const listed = "a".repeat(40); + const read: Array = []; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + ...activityListing(listed, "b".repeat(40)), + getDiff: (input) => + Effect.sync(() => { + read.push(input.commit); + return { + patch: "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n+x\n", + truncated: false, + nextCursor: null, + }; + }), + getDiffFileContents: (input) => + Effect.sync(() => { + read.push(input.commit); + return { oldContents: "old", newContents: "new" }; + }), + }), + ], + }); + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const file = { changeType: "change" as const, oldPath: "a.ts", newPath: "a.ts" }; + + for (const commit of ["c".repeat(40), "abcdef", "A".repeat(41), ""]) { + const diff = yield* service.diff({ ...ref, commit }).pipe(Effect.flip); + const contents = yield* service + .diffFileContents({ ...ref, ...file, commit }) + .pipe(Effect.flip); + assert.strictEqual(diff.reason, "not-found"); + assert.strictEqual(contents.reason, "not-found"); + } + assert.deepStrictEqual(read, []); + + yield* service.diff({ ...ref, commit: "AAAAAAA" }); + yield* service.diffFileContents({ ...ref, ...file, commit: "aaaaaaa" }); + assert.deepStrictEqual(read, [listed, listed]); + }), +); + it.effect.each(["commit", "credential", "expiry", "refresh"] as const)( "keeps cold metadata membership in its original scope through an in-flight %s", (boundary) => @@ -5192,6 +5252,7 @@ it.effect.each(["commit", "credential", "expiry", "refresh"] as const)( Effect.suspend(() => use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }), ), + ...activityListing("a".repeat(40)), getDiff: () => Effect.die("Membership must not fetch patch hunks"), getDiffFilePaths: (input) => Effect.gen(function* () { @@ -5356,6 +5417,7 @@ it.effect.each(["commit", "credential"] as const)( Effect.suspend(() => use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }), ), + ...activityListing("a".repeat(40)), getDiff: () => Effect.sync(() => ({ patch: @@ -5413,6 +5475,7 @@ it.effect.each(["expiry", "commit expiry", "cache hit", "commit cache hit", "ref ], providers: [ fakePullRequestProvider(SourceControlProviderKind.make("github"), { + ...activityListing("a".repeat(40)), getDiff: () => Effect.gen(function* () { if (++diffReads !== 1) return { patch: "", truncated: false, nextCursor: null }; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index e7d1b8abae5de..f3ac5cbe0d3d0 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -3723,10 +3723,40 @@ export const make = Effect.gen(function* () { ); return { key, read }; }; - const diff: PullRequestService["Service"]["diff"] = (input) => { - const { key, read } = readDiff(input); - return staleDiff.serve(key, read.pipe(Effect.map((read) => read.value))); + // A host reads a commit's diff from the repository, not from the change request, so a named + // commit is forwarded only as the one oid the change request's own commit list gives for it. + const withListedCommit = ( + operation: string, + input: I, + read: (input: I) => Effect.Effect, + ): Effect.Effect => { + const wanted = input.commit?.toLowerCase(); + if (wanted === undefined) return Effect.succeed(input); + return read(input).pipe( + Effect.flatMap(({ commits }) => { + const listed = /^[0-9a-f]{7,64}$/.test(wanted) + ? commits.filter((commit) => commit.oid.toLowerCase().startsWith(wanted)) + : []; + const [commit] = listed; + return commit !== undefined && listed.length === 1 + ? Effect.succeed({ ...input, commit: commit.oid }) + : Effect.fail( + new PullRequestOperationError({ + operation, + detail: "This commit is not part of the change request.", + reason: "not-found", + }), + ); + }), + ); }; + const diff: PullRequestService["Service"]["diff"] = (input) => + withListedCommit("diff", input, activity).pipe( + Effect.flatMap((input) => { + const { key, read } = readDiff(input); + return staleDiff.serve(key, read.pipe(Effect.map((read) => read.value))); + }), + ); const filesViewedCache = yield* Cache.makeWith( (key: string) => { @@ -4146,18 +4176,23 @@ export const make = Effect.gen(function* () { return walk(undefined); }; // PR read access does not grant arbitrary repository reads with the project credential; restrict to changed files. + const listedActivity = credentialCached(activity); const diffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) => - changesFile(input).pipe( - Effect.flatMap((changed) => - changed - ? readDiffFileContents(input) - : Effect.fail( - new PullRequestOperationError({ - operation: "diffFileContents", - detail: "This file is not part of the change request.", - reason: "not-found", - }), - ), + withListedCommit("diffFileContents", input, listedActivity).pipe( + Effect.flatMap((input) => + changesFile(input).pipe( + Effect.flatMap((changed) => + changed + ? readDiffFileContents(input) + : Effect.fail( + new PullRequestOperationError({ + operation: "diffFileContents", + detail: "This file is not part of the change request.", + reason: "not-found", + }), + ), + ), + ), ), ); From aab127d7fba5ca7ce185a956089b699994322166 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:04:35 -0800 Subject: [PATCH 149/221] fix(shared): repository keys for one-segment URL remotes name only the repository (#41862) Co-authored-by: Claude Fable 5.2 --- packages/shared/src/git.test.ts | 22 ++++++++++++++++++++++ packages/shared/src/git.ts | 9 ++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.ts index e454a989fb7b6..2ea8a26379086 100644 --- a/packages/shared/src/git.test.ts +++ b/packages/shared/src/git.test.ts @@ -85,6 +85,28 @@ describe("normalizeGitRemoteUrl", () => { expect(normalizeGitRemoteUrl("C:/repos/project")).toBe("c:/repos/project"); expect(normalizeGitRemoteUrl("git@x:team/project.git")).toBe("x/team/project"); }); + + it("keys a one-segment URL remote by what names the repository", () => { + expect(normalizeGitRemoteUrl("https://deploy:s3cr3ttok@git.example.com/Repo.git")).toBe( + "https://git.example.com/repo", + ); + expect(normalizeGitRemoteUrl("https://0123abcd@git.example.com/repo.git?key=0123abcd#x")).toBe( + "https://git.example.com/repo", + ); + expect(normalizeGitRemoteUrl("ftp://deploy:s3cr3ttok@git.example.com/team/repo.git")).toBe( + "ftp://git.example.com/team/repo", + ); + expect(normalizeGitRemoteUrl("ssh://git:s3cr3ttok@git.example.com:2222/repo.git")).toBe( + "ssh://git@git.example.com:2222/repo", + ); + expect(normalizeGitRemoteUrl("ssh://git@git.example.com/repo.git")).toBe( + "ssh://git@git.example.com/repo", + ); + expect(normalizeGitRemoteUrl("https://git.example.com/repo.git")).toBe( + "https://git.example.com/repo", + ); + expect(normalizeGitRemoteUrl("/srv/git/Repo.git")).toBe("/srv/git/repo"); + }); }); describe("isBareGitConfig", () => { diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index 7ef56875e34b5..c942d2976c2d1 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -198,7 +198,14 @@ export function parseGitRemoteRepository( */ export function normalizeGitRemoteUrl(value: string): string { const repository = parseGitRemoteRepository(value); - return repository === null ? lowerCaseRemote(value) : `${repository.host}/${repository.path}`; + if (repository !== null) return `${repository.host}/${repository.path}`; + // The key is shown to clients and persisted, so a URL it cannot parse keeps only what names the + // repository: no password, query or fragment, and a user only over SSH, where it is a login name. + const remote = lowerCaseRemote(value); + const url = /^([a-z][a-z0-9+.-]*):\/\/(?:([^/?#:@]*)(?::[^/?#]*)?@)?([^?#]*)/.exec(remote); + if (url === null) return remote; + const [, scheme = "", user = "", rest = ""] = url; + return lowerCaseRemote(`${scheme}://${scheme === "ssh" && user ? `${user}@` : ""}${rest}`); } function* gitConfigLines(configText: string) { From ae926f65790cea48e398adf6531bc117928d9ad5 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:04:46 +0100 Subject: [PATCH 150/221] fix(web): Cmd/Ctrl+F opens the browser find bar while a pull request is maximized (#41852) Co-authored-by: only21mil <263261067+only21mil@users.noreply.github.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../PullRequestsColumn.browser.test.tsx | 59 +++++++++++++++++++ .../pullRequest/PullRequestsColumn.tsx | 3 +- .../src/shortcuts/chatRouteCommands.test.ts | 17 ++++++ apps/web/src/shortcuts/chatRouteCommands.ts | 8 ++- 4 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx diff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx new file mode 100644 index 0000000000000..1e4de32289e69 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx @@ -0,0 +1,59 @@ +import { createRef, type RefObject } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../../test/render"; +import { PullRequestsColumn } from "./PullRequestsColumn"; + +function createColumn(maximizedAway: boolean, scrollRef: RefObject) { + return ( + {}} + searchValue="" + involvement="all" + state="open" + host={undefined} + hostMenuOptions={[]} + onInvolvement={() => {}} + onState={() => {}} + onHost={() => {}} + searchInput={} + sortMenu={null} + filtersMenu={null} + savedViewsMenu={null} + rightPanelControl={null} + titlebarControls={null} + rightPanelOpen={maximizedAway} + maximizedAway={maximizedAway} + listBody={null} + scrollRef={scrollRef} + /> + ); +} + +function dispatchFindShortcut() { + const event = new KeyboardEvent("keydown", { + key: "f", + ctrlKey: true, + bubbles: true, + cancelable: true, + }); + window.dispatchEvent(event); + return event; +} + +describe("PullRequestsColumn find shortcut", () => { + it("leaves Cmd/Ctrl+F to the browser while the detail panel is maximized", async () => { + const scrollRef = createRef(); + await using screen = await render(createColumn(false, scrollRef)); + + await screen.rerender(createColumn(true, scrollRef)); + expect(dispatchFindShortcut().defaultPrevented).toBe(false); + + await screen.rerender(createColumn(false, scrollRef)); + expect(dispatchFindShortcut().defaultPrevented).toBe(true); + await expect + .element(screen.getByRole("textbox", { name: "Search pull requests" })) + .toHaveFocus(); + }); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx index fdfe825790ba6..d4ca6d0d3b7e2 100644 --- a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx @@ -138,6 +138,7 @@ export function PullRequestsColumn({ const searchExpanded = searchOpen || searchValue.length > 0; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener focuses the visible search input on Cmd/Ctrl+F useEffect(() => { + if (maximizedAway) return; const onKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented) return; if (event.key.toLowerCase() !== "f" || !(event.metaKey || event.ctrlKey)) return; @@ -151,7 +152,7 @@ export function PullRequestsColumn({ }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [condensed]); + }, [condensed, maximizedAway]); if (!condensed && searchOpen) setSearchOpen(false); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves DOM focus to the in-flow search when the topbar search it was typed in unmounts useEffect(() => { diff --git a/apps/web/src/shortcuts/chatRouteCommands.test.ts b/apps/web/src/shortcuts/chatRouteCommands.test.ts index 3979368ff9032..db332610cd923 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.test.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.test.ts @@ -105,4 +105,21 @@ describe("preview commands", () => { expect(dispatch).toHaveBeenCalledWith(action); }); + + it("preview.find leaves the key unclaimed on non-thread chat routes", () => { + using dispatch = vi.spyOn(previewActions, "dispatchPreviewAction").mockImplementation(() => {}); + using register = vi.spyOn(dispatcher, "registerCommands").mockReturnValue(() => {}); + const router = { + state: { matches: [{ routeId: "/_chat/pull-requests", params: {} }] }, + } as unknown as AnyRouter; + using stack = new DisposableStack(); + stack.defer(installChatRouteCommands(router)); + const event = { preventDefault: vi.fn(), stopPropagation: vi.fn() } as unknown as KeyboardEvent; + + const result = register.mock.calls[0]![0]["preview.find"]!(event); + + expect(result).toBe(false); + expect(event.preventDefault).not.toHaveBeenCalled(); + expect(dispatch).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/shortcuts/chatRouteCommands.ts b/apps/web/src/shortcuts/chatRouteCommands.ts index 7cca45fbd81db..90ccf9fc2023f 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.ts @@ -186,7 +186,13 @@ export function installChatRouteCommands(router: AnyRouter): () => void { "preview.zoomIn": zoomCommand("zoom-in"), "preview.zoomOut": zoomCommand("zoom-out"), "preview.resetZoom": zoomCommand("reset-zoom"), - "preview.find": previewCommand("find"), + // Unclaimed, the browser's own find runs when no thread handles panel find. + "preview.find": (event) => { + const environmentId = readRouteEnvironmentId(); + if (!environmentId || !canOperatePreview(environmentId)) return false; + claim(event); + dispatchPreviewAction("find"); + }, }, { when: () => From 693117121770bc1c4441e032598ebee9ae2f3ae7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:05:58 -0800 Subject: [PATCH 151/221] fix(server): snapshot and transcript reads report a deleted thread as missing (#41866) Co-authored-by: Claude Fable 5.2 --- .../orchestration-v2/ProjectionStore.test.ts | 29 +++++++++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 5 ++++ 2 files changed, 34 insertions(+) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 636e69e7574b0..8de65435fda24 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -2854,6 +2854,31 @@ const recordsThreadCreated = (threadId: ThreadId) => }, }) as never; +const snapshotsReadDeletedThreadAsMissing = Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:records:deleted-snapshot"); + const created: { readonly payload: object } = recordsThreadCreated(threadId); + yield* store.apply(created as never); + assert.equal((yield* store.getThreadSnapshot(threadId)).projection.thread.id, threadId); + yield* store.apply({ + id: EventId.make(`event:${threadId}:deleted`), + type: "thread.deleted", + threadId, + providerInstanceId, + occurredAt: recordsAt(1), + payload: { ...created.payload, deletedAt: recordsAt(1) }, + } as never); + + for (const read of [ + store.getThreadSnapshot(threadId), + store.getThreadSnapshotWindow(threadId, { rowLimit: 10 }), + ]) { + assert.equal((yield* Effect.flip(read))._tag, "ProjectionStoreThreadNotFoundError"); + } + // Forks of the thread still read its rows. + assert.equal((yield* store.getThreadProjection(threadId)).thread.id, threadId); +}); + const queryPlan = Effect.fn("queryPlan")(function* (statement: string | undefined) { assert.isDefined(statement); const sql = yield* SqlClient.SqlClient; @@ -3941,6 +3966,10 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { "SQL recovery selects unfinished runless native subagents", () => runlessNativeSubagentNeedsRecovery, ); + it.effect( + "snapshot reads report a deleted thread as missing", + () => snapshotsReadDeletedThreadAsMissing, + ); it.effect( "worktree path and title lookups skip deleted threads, and can include archived ones", () => threadWorktreePathsIncludeArchivedOnRequest, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 69848d6a44f74..b0fa371bbba33 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -7079,6 +7079,9 @@ export const layer: Layer.Layer = .withTransaction( Effect.gen(function* () { const projection = yield* getThreadProjection(threadId); + // Deletion keeps the rows for surviving forks; a client reads the thread as gone. + if (projection.thread.deletedAt !== null) + return yield* new ProjectionStoreThreadNotFoundError({ threadId }); const rows = yield* sql<{ readonly snapshot_sequence: number | null }>` SELECT MAX(sequence) AS snapshot_sequence FROM orchestration_events @@ -8264,6 +8267,8 @@ export const layer: Layer.Layer = : {}), ...(historyAnchor === undefined ? {} : { historyAnchor }), }); + if (projection.thread.deletedAt !== null) + return yield* new ProjectionStoreThreadNotFoundError({ threadId }); // Pending requests outlive their turn's window; clients read their prompt from the card. const retainedIds = new Set(projection.turnItems.map((item) => item.id)); const pendingCards = (yield* decodeRows( From 860da094fd1e1762113047a445522a9909a51442 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:06:17 -0800 Subject: [PATCH 152/221] fix(server): ACP Registry listing and preparation follow agent readiness and provider policy (#41867) Co-authored-by: Claude Fable 5.2 --- apps/server/src/ws.test.ts | 128 ++++++++++++++++++++++++++++++++++++- apps/server/src/ws.ts | 26 +++++++- 2 files changed, 150 insertions(+), 4 deletions(-) diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 806a045898ddc..d12488a1b0db7 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -11,6 +11,8 @@ import { type AuthEnvironmentScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + AuthProvidersManageScope, + type ManagedPolicySummary, type WorkflowRun, type WorkflowStep, AuthSessionId, @@ -2378,6 +2380,7 @@ const acpSessionTags = [ WS_METHODS.serverListAcpRegistrySessions, WS_METHODS.serverImportAcpRegistrySession, WS_METHODS.serverDeleteAcpRegistrySession, + WS_METHODS.serverPrepareAcpRegistryAgent, ] as const; const acpSessionRpcs = WsRpcGroup.omit( ...[...WsRpcGroup.requests.keys()].filter( @@ -2513,7 +2516,9 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i const instance = { driverKind: acpDriver, snapshot: { - getSnapshot: Effect.succeed({ nativeSessions: { canLoad: true, canDelete: true } }), + getSnapshot: Effect.succeed({ + nativeSessions: { canList: true, canLoad: true, canDelete: true }, + }), }, acpSessionManagement: { listSessions: () => @@ -2750,6 +2755,127 @@ const layerWorkflowRpcTest = Layer.mergeAll( Layer.mock(ServerBrowser.ServerBrowser)({}), ); +/** A client for the ACP Registry RPCs; `calls` records what reached the agent or the catalog. */ +const makeAcpRegistryClient = Effect.fn("test.makeAcpRegistryClient")(function* ( + calls: Array, + options: { + readonly nativeSessions?: { readonly canList: boolean }; + readonly managedPolicy?: ManagedPolicySummary; + }, +) { + const scopes = [AuthOrchestrationReadScope, AuthProvidersManageScope]; + const instance = { + driverKind: acpDriver, + snapshot: { getSnapshot: Effect.succeed({ nativeSessions: options.nativeSessions }) }, + } as unknown as ProviderInstance; + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + ServerSettings.layerTest({}, options.managedPolicy), + Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({ + prepare: ({ agentId }) => + Effect.sync(() => calls.push(`prepare:${agentId}`)).pipe( + Effect.as({ agentId, version: "1.0.0", distribution: "npx", prepared: true } as const), + ), + }), + Layer.mock(AcpRegistrySessions.AcpRegistrySessions)({ + project: () => Effect.succeed({ workspaceRoot: "/workspace/acp" } as never), + sessionManager: () => + Effect.succeed({ + instance, + manager: { + listSessions: () => + Effect.sync(() => calls.push("listSessions")).pipe( + Effect.as({ sessions: [], nextCursor: null }), + ), + } as unknown as NonNullable, + }), + }), + ); + return yield* RpcTest.makeClient(acpSessionRpcs).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("acp-test"), + subject: "acp-test", + method: "browser-session-cookie", + scopes, + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe(Layer.provide(services), Layer.merge(RpcAuthorization.layer(scopes))), + ), + ); +}); + +it.effect("listing ACP sessions reaches only an agent that advertises listing", () => + Effect.gen(function* () { + const calls: Array = []; + const input = { instanceId: acpInstanceId, projectId: acpProjectId }; + + const unprobed = yield* makeAcpRegistryClient(calls, {}); + const refused = yield* unprobed[WS_METHODS.serverListAcpRegistrySessions](input).pipe( + Effect.flip, + ); + assert.strictEqual( + refused._tag === "AcpRegistryOperationError" ? refused.reason : refused._tag, + "session_list_unsupported", + ); + assert.deepEqual(calls, []); + + const probed = yield* makeAcpRegistryClient(calls, { nativeSessions: { canList: true } }); + yield* probed[WS_METHODS.serverListAcpRegistrySessions](input); + assert.deepEqual(calls, ["listSessions"]); + }).pipe(Effect.provide(layerWorkflowRpcTest)), +); + +it.effect("preparing an ACP Registry agent follows the policy's allowed providers", () => + Effect.gen(function* () { + const calls: Array = []; + const policy = (...allowedDrivers: ReadonlyArray): ManagedPolicySummary => ({ + organization: "Example Corp", + lockedSettings: [], + limits: { + providers: { + allowedDrivers: [ + ProviderDriverKind.make("codex"), + ...allowedDrivers.map((driver) => ProviderDriverKind.make(driver)), + ], + lockedInstanceFields: {}, + }, + }, + }); + + const excluded = yield* makeAcpRegistryClient(calls, { managedPolicy: policy() }); + const refused = yield* excluded[WS_METHODS.serverPrepareAcpRegistryAgent]({ + agentId: "example-agent", + }).pipe(Effect.flip); + assert.strictEqual( + refused._tag === "AcpRegistryOperationError" ? refused.message : refused._tag, + "Example Corp's policy does not allow the ACP Registry provider.", + ); + assert.deepEqual(calls, []); + + const included = yield* makeAcpRegistryClient(calls, { + managedPolicy: policy("acpRegistry"), + }); + yield* included[WS_METHODS.serverPrepareAcpRegistryAgent]({ agentId: "example-agent" }); + const unmanaged = yield* makeAcpRegistryClient(calls, {}); + yield* unmanaged[WS_METHODS.serverPrepareAcpRegistryAgent]({ agentId: "example-agent" }); + assert.deepEqual(calls, ["prepare:example-agent", "prepare:example-agent"]); + }).pipe(Effect.provide(layerWorkflowRpcTest)), +); + it.effect("workflow RPCs read a run and pass an answer, a resume and a cancel to the service", () => Effect.gen(function* () { const calls: Array = []; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b6922b9e90996..f0f746eb8041f 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -36,6 +36,7 @@ import { AuthOrchestrationOperateScope, AuthProvidersManageScope, type AuthEnvironmentScope, + ProviderDriverKind, type ScheduledTaskListResult, WorkflowRequestError, AuthSessionId, @@ -198,6 +199,7 @@ import * as NpmRelease from "./cloud/npmRelease.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as ManagedProviders from "./policy/managedProviders.ts"; import * as ServerSettings from "./serverSettings.ts"; import { invalidateSettingsSecrets } from "./sourceControl/sourceControlHostSecrets.ts"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; @@ -1644,6 +1646,14 @@ export const layerWsRpc = ( ) { const project = yield* acpRegistrySessions.project(input.projectId); const { instance, manager } = yield* acpRegistrySessions.sessionManager(input.instanceId); + // Only a probed agent advertises listing, so a read never installs or first-starts one. + const snapshot = yield* instance.snapshot.getSnapshot; + if (snapshot.nativeSessions?.canList !== true) { + return yield* new AcpRegistryOperationError({ + reason: "session_list_unsupported", + message: "The ACP agent does not advertise session listing.", + }); + } const listed = yield* manager.listSessions({ cwd: project.workspaceRoot, ...(input.cursor === undefined ? {} : { cursor: input.cursor }), @@ -2441,9 +2451,19 @@ export const layerWsRpc = ( [WS_METHODS.serverPrepareAcpRegistryAgent]: (input) => Effect.annotateCurrentSpan({ "acp_registry.agent_id": input.agentId }).pipe( Effect.andThen( - acpRegistryCatalog - .prepare(input) - .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)), + Effect.suspend(() => { + const blocked = ManagedProviders.disallowedDriverReason( + serverSettings.managedPolicy, + ProviderDriverKind.make("acpRegistry"), + ); + return blocked === undefined + ? acpRegistryCatalog + .prepare(input) + .pipe(Effect.mapError(AcpRegistrySupport.toAcpRegistryOperationError)) + : Effect.fail( + new AcpRegistryOperationError({ reason: "install_failed", message: blocked }), + ); + }), ), ), [WS_METHODS.serverUninstallAcpRegistryManagedBinary]: (input) => From b1c83e180f5ca1906df1a1a050a6ed689f88c56a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:06:33 -0800 Subject: [PATCH 153/221] fix(server): guests get failed file edits without their text (#41865) Co-authored-by: Claude Fable 5.2 --- .../src/guest/GuestShareService.test.ts | 59 ++++++++++++++++++- apps/server/src/guest/GuestShareService.ts | 32 +++++++--- 2 files changed, 79 insertions(+), 12 deletions(-) diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.ts index 363c9d84d4e2c..cb68cece707d8 100644 --- a/apps/server/src/guest/GuestShareService.test.ts +++ b/apps/server/src/guest/GuestShareService.test.ts @@ -546,6 +546,52 @@ it.effect("gives the guest a command's detail and output, but no file diffs", () }).pipe(Effect.provide(layerTest)), ); +it.effect("gives the guest a failed edit without the text it tried to write", () => + Effect.gen(function* () { + const { orchestrator, guestShares, credential } = yield* shareThread; + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" }); + const failedEdit = (id: string) => + writeItem(id, { + type: "file_change", + status: "failed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }); + const before = yield* failedEdit("item:failed-before"); + + const events = yield* guestShares.stream(session); + const during = yield* failedEdit("item:failed-during"); + const detail = (yield* guestShares.item(session, before)).item; + yield* orchestrator.dispatch({ + type: "thread.guest-share.close", + commandId: CommandId.make("close-after-failed-edit"), + threadId, + }); + const received = Array.from(yield* Stream.runCollect(events)); + const changes = received.flatMap((event) => { + if (event.type !== "thread") return []; + if (event.item.kind === "snapshot") { + return [ + ...event.item.projection.turnItems, + ...event.item.projection.visibleTurnItems.map((row) => row.item), + ]; + } + return event.item.kind === "event" && event.item.event.type === "turn-item.updated" + ? [event.item.event.payload] + : []; + }); + const failed = changes.filter((item) => item.type === "file_change"); + assert.includeMembers( + failed.map((item) => item.id), + [before, during], + ); + for (const change of [...failed, detail]) { + assert.deepInclude(change, { status: "failed", fileName: "src/auth.ts" }); + assert.doesNotHaveAnyKeys(change, ["diffStr", "oldStr", "newStr"]); + } + }).pipe(Effect.provide(layerTest)), +); + it.effect("gives a fork's guest the commands the fork shows from its source thread", () => Effect.gen(function* () { const { orchestrator, guestShares } = yield* shareThread; @@ -656,13 +702,19 @@ it.effect("pages the guest back through turns older than the stream's snapshot", }); yield* eventSink.write({ events: [ - turnItem("item:old-image", 1, { + turnItem("item:old-edit", 1, { + type: "file_change", + status: "failed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }), + turnItem("item:old-image", 2, { type: "assistant_message", text: `![Old](${shot})`, streaming: false, }), ...Array.from({ length: 30 }, (_, index) => - turnItem(`item:ask-${index}`, index + 2, { + turnItem(`item:ask-${index}`, index + 3, { type: "user_message", text: `Ask ${index}`, createdBy: "user", @@ -694,9 +746,10 @@ it.effect("pages the guest back through turns older than the stream's snapshot", while (cursor !== null) { const page: OrchestrationV2ThreadHistoryPage = yield* guestShares.history(session, cursor); older.push(...ids(page.items)); + for (const { item } of page.items) assert.notProperty(item, "diffStr"); cursor = page.hasMoreHistory ? page.nextCursor : null; } - assert.include(older, "item:old-image"); + assert.includeMembers(older, ["item:old-image", "item:old-edit"]); assert.deepStrictEqual(yield* guestShares.media(session, shot), { path: shot, mimeType: "image/png", diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index b5b21a7af2ae7..5ff7ae22770e2 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -52,7 +52,6 @@ import { coalesceThreadLiveStream } from "../orchestration-v2/ThreadLiveEventCoa import { buildBoundedThreadStreamSnapshot } from "../orchestration-v2/ThreadStream.ts"; import { projectTurnItemForDetail, - projectTurnItemForWire, threadStreamEventItem, } from "../orchestration-v2/WireProjection.ts"; import * as DocumentText from "../provider/DocumentText.ts"; @@ -218,6 +217,16 @@ const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | } }; +/** A guest sees that a file changed, never the text of the change, whatever its status. */ +const withoutFileText = (item: OrchestrationV2TurnItem): OrchestrationV2TurnItem => { + if (item.type !== "file_change") return item; + const { diffStr: _diff, oldStr: _old, newStr: _new, ...shown } = item; + return shown; +}; +const rowWithoutFileText = ( + row: Row, +): Row => ({ ...row, item: withoutFileText(row.item) }); + const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const commandOutputs = yield* CommandOutputHub.CommandOutputHub; @@ -566,12 +575,16 @@ const make = Effect.gen(function* () { if (item.kind !== "event") return []; if (endsShare(item.event)) return [ended]; if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]); + const shown = + item.event.type === "turn-item.updated" + ? { ...item, event: { ...item.event, payload: withoutFileText(item.event.payload) } } + : item; const updated = threadOf(item.event); const view = updated === null ? null : viewOf(updated); return view === null - ? [{ type: "thread", item }] + ? [{ type: "thread", item: shown }] : [ - { type: "thread", item }, + { type: "thread", item: shown }, { type: "view", view }, ]; }), @@ -585,7 +598,11 @@ const make = Effect.gen(function* () { ); const openingSnapshot = buildBoundedThreadStreamSnapshot({ snapshotSequence: snapshot.snapshotSequence, - projection: snapshot.projection, + projection: { + ...snapshot.projection, + turnItems: snapshot.projection.turnItems.map(withoutFileText), + visibleTurnItems: snapshot.projection.visibleTurnItems.map(rowWithoutFileText), + }, }); const opening: ReadonlyArray = [ { type: "view", view: initialView }, @@ -669,10 +686,7 @@ const make = Effect.gen(function* () { const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) { const { item } = yield* threadItem(session, itemId); - return { - item: - item.type === "file_change" ? projectTurnItemForWire(item) : projectTurnItemForDetail(item), - }; + return { item: projectTurnItemForDetail(withoutFileText(item)) }; }); const history = Effect.fn("GuestShareService.history")(function* ( @@ -687,7 +701,7 @@ const make = Effect.gen(function* () { share.id, page.items.map((row) => row.item), ); - return page; + return { ...page, items: page.items.map(rowWithoutFileText) }; }); const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* ( From 4508c706813f6457599f3ea260e0ae278ad9480e Mon Sep 17 00:00:00 2001 From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:07:52 -0500 Subject: [PATCH 154/221] fix(web): opening a thread lands at its end instead of jumping there (#41843) Co-authored-by: Julius Marminge --- .../chat/MessagesTimeline.browser.test.tsx | 45 ++++ .../src/components/chat/MessagesTimeline.tsx | 6 +- patches/@legendapp__list@3.7.3.patch | 238 +++++++++++++++++- pnpm-lock.yaml | 8 +- 4 files changed, 288 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index f0fe30716818e..a38a51feab4c7 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -815,6 +815,51 @@ describe("MessagesTimeline messages", () => { expectItemOrder(); }); + it("opens a working parent thread at its end without landing short", async () => { + setup(); + const props = baseProps(); + const parent = Array.from({ length: 30 }, (_, index) => + message( + `Parent turn ${index}:\n\n${"x ".repeat(200)}`, + { role: index % 2 === 0 ? "user" : "assistant" }, + `parent-${index}`, + ), + ); + await using screen = await renderElement( + {} }} + timelineEntries={[message("Short child reply.", { role: "assistant" }, "child-0")]} + />, + ); + expect(screen.text()).toContain("Subagent of"); + const viewport = props.listRef.current!.getScrollableNode()!; + const end = () => viewport.scrollHeight - viewport.clientHeight; + // Distance from the end as each scroll lands, against the content height at that moment. + const shortfalls: number[] = []; + viewport.addEventListener("scroll", () => + shortfalls.push(Math.round(end() - viewport.scrollTop)), + ); + + // A working parent's footer (queued turns, its subagents) is taller than the child's. + await screen.rerender( + Waiting on 4 subagents
} + isWorking + />, + ); + await vi.waitFor(() => { + expect(screen.text()).toContain("Parent turn 29:"); + expect(end() - viewport.scrollTop).toBeLessThanOrEqual(1); + }); + + expect(shortfalls.length).toBeGreaterThan(0); + expect(shortfalls).toEqual(shortfalls.map(() => 0)); + }); + it("puts rows back in item order soon after a continuous scroll stops", async () => { setup(); const props = baseProps(); diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 7b0a883139635..575000a55e598 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1505,10 +1505,10 @@ const ConversationTimeline = memo(function ConversationTimeline({ ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH : TIMELINE_MAINTAIN_SCROLL_AT_END } + // A restore owns the scroll position until it lands. Anchoring would + // move it for the previous thread's header as the list swaps threads. maintainVisibleContentPosition={ - findActive || - citationPositioning || - (restoringThreadPosition && rememberedPosition?.atEnd === false) + findActive || citationPositioning || restoringThreadPosition ? false : maintainVisibleContentPosition } diff --git a/patches/@legendapp__list@3.7.3.patch b/patches/@legendapp__list@3.7.3.patch index 2afc400b04435..a947d0b614372 100644 --- a/patches/@legendapp__list@3.7.3.patch +++ b/patches/@legendapp__list@3.7.3.patch @@ -1,5 +1,5 @@ diff --git a/react-native.js b/react-native.js -index 440b0ad..fd5d18d 100644 +index 440b0ad0d8af34e5dc4ae9b2a21a7addd2d71efb..fd5d18d8d184036d140f543285c9b5738513baa7 100644 --- a/react-native.js +++ b/react-native.js @@ -1344,7 +1344,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { @@ -13,7 +13,7 @@ index 440b0ad..fd5d18d 100644 set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); set$( diff --git a/react-native.mjs b/react-native.mjs -index b95e1f8..e2b013a 100644 +index b95e1f86d2cd76d5dbaf1340fdc37f3f1990e9ee..e2b013a0969d512d7c9b5e6fe7d348761f286bed 100644 --- a/react-native.mjs +++ b/react-native.mjs @@ -1323,7 +1323,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { @@ -26,3 +26,237 @@ index b95e1f8..e2b013a 100644 set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); set$( +diff --git a/react.js b/react.js +index 24cc6054d3fa59742c7f50457a18adf451128bbb..32e59a03a4da96776f2690085ff3eebb452be397 100644 +--- a/react.js ++++ b/react.js +@@ -6376,7 +6376,8 @@ function useOnLayoutSync({ + onLayoutProp, + onLayoutChange, + webLayoutResync, +- webExternalScroll = false ++ webExternalScroll = false, ++ measureNowRef + }, deps) { + const callbacks = useLatestRef({ onLayoutChange, onLayoutProp, webLayoutResync }); + const onExternalLayout = React3.useCallback( +@@ -6409,7 +6410,7 @@ function useOnLayoutSync({ + emit(toLayout(rect), true); + prevRect = rect; + } +- return createResizeObserver(element, (entry) => { ++ const disconnectResizeObserver = createResizeObserver(element, (entry) => { + var _a4, _b2, _c; + const target = entry.target instanceof HTMLElement ? entry.target : void 0; + const borderBoxSize = Array.isArray(entry.borderBoxSize) ? entry.borderBoxSize[0] : entry.borderBoxSize; +@@ -6427,7 +6428,30 @@ function useOnLayoutSync({ + emit(toLayout(rectObserved), false); + } + }); +- }, [callbacks, measureInLayoutEffect, webExternalScroll, ...deps || []]); ++ if (!measureNowRef) return disconnectResizeObserver; ++ // T3 patch: measure on demand through the observer's own baseline, so a ++ // forced read and a later observer delivery never disagree about the size. ++ const measureNow = () => { ++ const rect = element.getBoundingClientRect(); ++ if (rect.height === 0 && rect.width === 0) return; ++ const previousRect = prevRect != null ? prevRect : getContainerLayoutBaseline(element); ++ if (previousRect !== void 0 && rect.width === previousRect.width && rect.height === previousRect.height) return; ++ prevRect = rect; ++ emit(toLayout(rect), true); ++ // The browser only reports sizes that differ from its last delivery. Re-observe so a ++ // return to that size is still reported against the baseline this read just moved. ++ if (typeof ResizeObserver !== "undefined" && callbackMap.has(element)) { ++ const observer = getGlobalResizeObserver(); ++ observer.unobserve(element); ++ observer.observe(element, { box: "border-box" }); ++ } ++ }; ++ measureNowRef.current = measureNow; ++ return () => { ++ if (measureNowRef.current === measureNow) measureNowRef.current = void 0; ++ disconnectResizeObserver(); ++ }; ++ }, [callbacks, measureInLayoutEffect, measureNowRef, webExternalScroll, ...deps || []]); + return webExternalScroll ? { onLayout: onExternalLayout } : {}; + } + function toLayout(rect) { +@@ -7801,10 +7825,10 @@ function useStableRenderComponent(renderComponent, mapProps) { + [mapPropsRef, renderComponentRef] + ); + } +-var LayoutView = ({ onLayoutChange, refView, children, ...rest }) => { ++var LayoutView = ({ onLayoutChange, refView, measureRef, children, ...rest }) => { + const localRef = React3.useRef(null); + const ref = refView != null ? refView : localRef; +- useOnLayoutSync({ onLayoutChange, ref }); ++ useOnLayoutSync({ onLayoutChange, ref, measureNowRef: measureRef }); + return /* @__PURE__ */ React3__namespace.createElement("div", { ...rest, ref }, children); + }; + var subscribeScreenReader = () => () => { +@@ -7881,6 +7905,16 @@ var ListComponent = typedMemo(function ListComponent2({ + ); + const ScrollComponent = renderScrollComponent ? CustomScrollComponent : ListComponentScrollView; + const SnapOrScroll = snapToIndices ? SnapWrapper : ScrollComponent; ++ // T3 patch: header and footer sizes otherwise arrive from a resize observer ++ // after layout, so a scroll to the end right after a commit that changed them ++ // (a thread switch) computed its target from the previous sizes. ++ const measureHeaderRef = React3.useRef(void 0); ++ const measureFooterRef = React3.useRef(void 0); ++ ctx.state.measureHeaderAndFooter = () => { ++ var _a3, _b; ++ (_a3 = measureHeaderRef.current) == null ? void 0 : _a3.call(measureHeaderRef); ++ (_b = measureFooterRef.current) == null ? void 0 : _b.call(measureFooterRef); ++ }; + const updateFooterSize = React3.useCallback( + (size, afterSizeUpdate) => { + var _a3; +@@ -7956,7 +7990,7 @@ var ListComponent = typedMemo(function ListComponent2({ + style: autoOtherAxisStyle ? [autoOtherAxisStyle, style] : style + }, + Platform.OS !== "web", +- ListHeaderComponent && /* @__PURE__ */ React3__namespace.createElement(LayoutView, { onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)), ++ ListHeaderComponent && /* @__PURE__ */ React3__namespace.createElement(LayoutView, { measureRef: measureHeaderRef, onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)), + ListEmptyComponent && getComponent(ListEmptyComponent), + shouldRenderAlignItemsAtEndSpacer && /* @__PURE__ */ React3__namespace.createElement(AlignItemsAtEndSpacer, { horizontal }), + canRender && !ListEmptyComponent && /* @__PURE__ */ React3__namespace.createElement( +@@ -7970,7 +8004,7 @@ var ListComponent = typedMemo(function ListComponent2({ + stickyHeaderConfig + } + ), +- ListFooterComponent && /* @__PURE__ */ React3__namespace.createElement(LayoutView, { onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)), ++ ListFooterComponent && /* @__PURE__ */ React3__namespace.createElement(LayoutView, { measureRef: measureFooterRef, onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)), + /* @__PURE__ */ React3__namespace.createElement(ScrollAdjust, null), + IS_DEV && ENABLE_DEVMODE + ); +@@ -8853,7 +8887,12 @@ function createImperativeHandle(ctx, scheduleImperativeScrollCommit) { + runScrollRequest( + pendingScroll.token, + state.pendingScrollResolve, +- () => state.props.data.length === 0 ? "unreachable" : scrollToEnd(ctx, pendingScroll.options), ++ () => { ++ var _a3; ++ if (state.props.data.length === 0) return "unreachable"; ++ (_a3 = state.measureHeaderAndFooter) == null ? void 0 : _a3.call(state); ++ return scrollToEnd(ctx, pendingScroll.options); ++ }, + () => isScrollToIndexReady(state.props.data.length - 1, true) + ); + } +diff --git a/react.mjs b/react.mjs +index 2cf1995d97cd101244b08b2b055265add859e064..af2a2817af1873ab5b5f0d8df85187521c39518a 100644 +--- a/react.mjs ++++ b/react.mjs +@@ -6355,7 +6355,8 @@ function useOnLayoutSync({ + onLayoutProp, + onLayoutChange, + webLayoutResync, +- webExternalScroll = false ++ webExternalScroll = false, ++ measureNowRef + }, deps) { + const callbacks = useLatestRef({ onLayoutChange, onLayoutProp, webLayoutResync }); + const onExternalLayout = useCallback( +@@ -6388,7 +6389,7 @@ function useOnLayoutSync({ + emit(toLayout(rect), true); + prevRect = rect; + } +- return createResizeObserver(element, (entry) => { ++ const disconnectResizeObserver = createResizeObserver(element, (entry) => { + var _a4, _b2, _c; + const target = entry.target instanceof HTMLElement ? entry.target : void 0; + const borderBoxSize = Array.isArray(entry.borderBoxSize) ? entry.borderBoxSize[0] : entry.borderBoxSize; +@@ -6406,7 +6407,30 @@ function useOnLayoutSync({ + emit(toLayout(rectObserved), false); + } + }); +- }, [callbacks, measureInLayoutEffect, webExternalScroll, ...deps || []]); ++ if (!measureNowRef) return disconnectResizeObserver; ++ // T3 patch: measure on demand through the observer's own baseline, so a ++ // forced read and a later observer delivery never disagree about the size. ++ const measureNow = () => { ++ const rect = element.getBoundingClientRect(); ++ if (rect.height === 0 && rect.width === 0) return; ++ const previousRect = prevRect != null ? prevRect : getContainerLayoutBaseline(element); ++ if (previousRect !== void 0 && rect.width === previousRect.width && rect.height === previousRect.height) return; ++ prevRect = rect; ++ emit(toLayout(rect), true); ++ // The browser only reports sizes that differ from its last delivery. Re-observe so a ++ // return to that size is still reported against the baseline this read just moved. ++ if (typeof ResizeObserver !== "undefined" && callbackMap.has(element)) { ++ const observer = getGlobalResizeObserver(); ++ observer.unobserve(element); ++ observer.observe(element, { box: "border-box" }); ++ } ++ }; ++ measureNowRef.current = measureNow; ++ return () => { ++ if (measureNowRef.current === measureNow) measureNowRef.current = void 0; ++ disconnectResizeObserver(); ++ }; ++ }, [callbacks, measureInLayoutEffect, measureNowRef, webExternalScroll, ...deps || []]); + return webExternalScroll ? { onLayout: onExternalLayout } : {}; + } + function toLayout(rect) { +@@ -7780,10 +7804,10 @@ function useStableRenderComponent(renderComponent, mapProps) { + [mapPropsRef, renderComponentRef] + ); + } +-var LayoutView = ({ onLayoutChange, refView, children, ...rest }) => { ++var LayoutView = ({ onLayoutChange, refView, measureRef, children, ...rest }) => { + const localRef = useRef(null); + const ref = refView != null ? refView : localRef; +- useOnLayoutSync({ onLayoutChange, ref }); ++ useOnLayoutSync({ onLayoutChange, ref, measureNowRef: measureRef }); + return /* @__PURE__ */ React3.createElement("div", { ...rest, ref }, children); + }; + var subscribeScreenReader = () => () => { +@@ -7860,6 +7884,16 @@ var ListComponent = typedMemo(function ListComponent2({ + ); + const ScrollComponent = renderScrollComponent ? CustomScrollComponent : ListComponentScrollView; + const SnapOrScroll = snapToIndices ? SnapWrapper : ScrollComponent; ++ // T3 patch: header and footer sizes otherwise arrive from a resize observer ++ // after layout, so a scroll to the end right after a commit that changed them ++ // (a thread switch) computed its target from the previous sizes. ++ const measureHeaderRef = useRef(void 0); ++ const measureFooterRef = useRef(void 0); ++ ctx.state.measureHeaderAndFooter = () => { ++ var _a3, _b; ++ (_a3 = measureHeaderRef.current) == null ? void 0 : _a3.call(measureHeaderRef); ++ (_b = measureFooterRef.current) == null ? void 0 : _b.call(measureFooterRef); ++ }; + const updateFooterSize = useCallback( + (size, afterSizeUpdate) => { + var _a3; +@@ -7935,7 +7969,7 @@ var ListComponent = typedMemo(function ListComponent2({ + style: autoOtherAxisStyle ? [autoOtherAxisStyle, style] : style + }, + Platform.OS !== "web", +- ListHeaderComponent && /* @__PURE__ */ React3.createElement(LayoutView, { onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)), ++ ListHeaderComponent && /* @__PURE__ */ React3.createElement(LayoutView, { measureRef: measureHeaderRef, onLayoutChange: onLayoutHeader, style: ListHeaderComponentStyle }, getComponent(ListHeaderComponent)), + ListEmptyComponent && getComponent(ListEmptyComponent), + shouldRenderAlignItemsAtEndSpacer && /* @__PURE__ */ React3.createElement(AlignItemsAtEndSpacer, { horizontal }), + canRender && !ListEmptyComponent && /* @__PURE__ */ React3.createElement( +@@ -7949,7 +7983,7 @@ var ListComponent = typedMemo(function ListComponent2({ + stickyHeaderConfig + } + ), +- ListFooterComponent && /* @__PURE__ */ React3.createElement(LayoutView, { onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)), ++ ListFooterComponent && /* @__PURE__ */ React3.createElement(LayoutView, { measureRef: measureFooterRef, onLayoutChange: onLayoutFooterInternal, style: ListFooterComponentStyle }, getComponent(ListFooterComponent)), + /* @__PURE__ */ React3.createElement(ScrollAdjust, null), + IS_DEV && ENABLE_DEVMODE + ); +@@ -8832,7 +8866,12 @@ function createImperativeHandle(ctx, scheduleImperativeScrollCommit) { + runScrollRequest( + pendingScroll.token, + state.pendingScrollResolve, +- () => state.props.data.length === 0 ? "unreachable" : scrollToEnd(ctx, pendingScroll.options), ++ () => { ++ var _a3; ++ if (state.props.data.length === 0) return "unreachable"; ++ (_a3 = state.measureHeaderAndFooter) == null ? void 0 : _a3.call(state); ++ return scrollToEnd(ctx, pendingScroll.options); ++ }, + () => isScrollToIndexReady(state.props.data.length - 1, true) + ); + } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 472e1d1a6c864..51da3feaaa23c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -370,7 +370,7 @@ patchedDependencies: '@effect/vitest@4.1.5': dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 - '@legendapp/list@3.7.3': 85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4 + '@legendapp/list@3.7.3': c4bf72fc2117c7357839807722ed379370cdd91dffd4edaa6b836236597d83ae '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': 7edcdd484a99c7ec0b2667499c4cb21d113ec9bea1f8570c0b0a030d33bbf1cd '@react-native-menu/menu@2.0.0': 6872ba71b9847c5a0210b1b896923dadc3860faedfe28d9f062bcedfe786ef1d @@ -577,7 +577,7 @@ importers: version: 5.4.6 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 3.7.3(patch_hash=c4bf72fc2117c7357839807722ed379370cdd91dffd4edaa6b836236597d83ae)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@material/material-color-utilities': specifier: 0.3.0 version: 0.3.0 @@ -1101,7 +1101,7 @@ importers: version: 5.3.0 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 3.7.3(patch_hash=c4bf72fc2117c7357839807722ed379370cdd91dffd4edaa6b836236597d83ae)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@noble/hashes': specifier: 'catalog:' version: 1.8.0 @@ -15630,7 +15630,7 @@ snapshots: '@koromix/koffi-win32-x64@3.3.6': optional: true - '@legendapp/list@3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': + '@legendapp/list@3.7.3(patch_hash=c4bf72fc2117c7357839807722ed379370cdd91dffd4edaa6b836236597d83ae)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': dependencies: react: 19.3.0 use-sync-external-store: 1.7.0(react@19.3.0) From 14ea095b0a8e821e72b244185a7de4f49bcb6dd5 Mon Sep 17 00:00:00 2001 From: maria Date: Tue, 24 Nov 2026 00:09:14 -0300 Subject: [PATCH 155/221] feat(web): add an HTML preview width setting separate from chat width (#41663) --- apps/web/src/appInit.tsx | 3 ++ apps/web/src/components/chat/ChatCanvas.tsx | 20 +++++++- .../src/components/chat/MessagesTimeline.tsx | 3 +- .../components/chat/TimelineAssistantRows.tsx | 2 +- .../src/components/chat/canvasStore.test.ts | 1 + apps/web/src/components/chat/canvasStore.ts | 4 ++ .../components/chat/chatCanvasLayout.test.ts | 47 ++++++++++++++++++ .../src/components/chat/chatCanvasLayout.ts | 18 ++++++- .../settings/AppearanceSettingsPanel.tsx | 49 +++++++++++++++++++ .../components/settings/SettingsPanels.tsx | 4 ++ .../src/components/settings/settingsSearch.ts | 6 +++ apps/web/src/i18n/translations/de.json | 6 +++ apps/web/src/i18n/translations/en.json | 6 +++ apps/web/src/i18n/translations/es.json | 6 +++ apps/web/src/i18n/translations/fr.json | 6 +++ apps/web/src/i18n/translations/ja.json | 6 +++ apps/web/src/i18n/translations/ko.json | 6 +++ apps/web/src/i18n/translations/pt-BR.json | 6 +++ apps/web/src/i18n/translations/ru.json | 6 +++ apps/web/src/i18n/translations/sv.json | 6 +++ apps/web/src/i18n/translations/zh.json | 6 +++ apps/web/src/index.css | 17 +++++++ packages/contracts/src/settings.ts | 8 +++ 23 files changed, 237 insertions(+), 5 deletions(-) diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index cce59f08f6d12..76e7bc9e5cff1 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -90,6 +90,9 @@ function startClientAppearance(): void { if (previous?.chatWidth !== settings.chatWidth) { root.dataset.chatWidth = settings.chatWidth; } + if (previous?.htmlPreviewWidth !== settings.htmlPreviewWidth) { + root.dataset.htmlPreviewWidth = settings.htmlPreviewWidth; + } if (previous?.appearanceContrast !== settings.appearanceContrast) { applyAppearanceContrast(root, settings.appearanceContrast); } diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index 7848009308750..c1fa62bdd5668 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -61,6 +61,7 @@ export function ChatCanvas({ }) { const elementRef = useRef(null); const widthProbeRef = useRef(null); + const htmlPreviewWidthProbeRef = useRef(null); const [timelineElement, registerTimeline] = useState(null); const measurements = useStore(store, (state) => state.measurements); const detailsCardMeasurement = useStore(store, (state) => state.detailsCardMeasurement); @@ -68,7 +69,8 @@ export function ChatCanvas({ useLayoutEffect(() => { const element = elementRef.current; const probe = widthProbeRef.current; - if (!element || !probe) return; + const htmlPreviewProbe = htmlPreviewWidthProbeRef.current; + if (!element || !probe || !htmlPreviewProbe) return; const findBar = detailsCardTopInset > 0 ? element.querySelector("[data-thread-find-bar]") : null; let disposed = false; @@ -116,6 +118,7 @@ export function ChatCanvas({ height: element.clientHeight, padding: Number.parseFloat(styles.paddingLeft), maxChatWidth: Number.parseFloat(styles.width), + maxHtmlPreviewWidth: Number.parseFloat(getComputedStyle(htmlPreviewProbe).width), minChatWidth: Number.parseFloat(styles.minWidth), composerHeight: composerOverlayElement?.getBoundingClientRect().height ?? 0, timelineGutter: timelineElement @@ -124,7 +127,7 @@ export function ChatCanvas({ }); }; measure(); - const observed: Element[] = [element, probe]; + const observed: Element[] = [element, probe, htmlPreviewProbe]; if (findBar) observed.push(findBar); if (composerOverlayElement) observed.push(composerOverlayElement); if (timelineElement) observed.push(timelineElement); @@ -158,6 +161,13 @@ export function ChatCanvas({ detailsCardPlacement: model.detailsCardPlacement, }; const { layout } = context; + const htmlPreviewLane = + layout.htmlPreview.width > layout.chat.width + ? { + "--html-preview-lane-offset": `${layout.htmlPreview.left - layout.chat.left}px`, + "--html-preview-lane-width": `${layout.htmlPreview.width}px`, + } + : null; return (
@@ -179,6 +190,11 @@ export function ChatCanvas({ aria-hidden className="pointer-events-none invisible absolute h-0 w-(--chat-content-max-width) min-w-[40rem] box-content ps-3 sm:ps-12" /> +
{children}
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 575000a55e598..b809c40dfdb53 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1398,7 +1398,8 @@ const ConversationTimeline = memo(function ConversationTimeline({ >
diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index f22b1338aab91..9692bbedad62a 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -367,7 +367,7 @@ export function HtmlRenderTimelineRow({ return
{ctx.renderHtmlRender(row)}
; } return ( -
+
({ height, padding: 48, maxChatWidth: 768, + maxHtmlPreviewWidth: 768, minChatWidth: 640, composerHeight: 180, timelineGutter: 0, diff --git a/apps/web/src/components/chat/canvasStore.ts b/apps/web/src/components/chat/canvasStore.ts index 6b350cf95f22f..88811d1a41706 100644 --- a/apps/web/src/components/chat/canvasStore.ts +++ b/apps/web/src/components/chat/canvasStore.ts @@ -17,6 +17,7 @@ export interface ChatCanvasMeasurements { readonly height: number; readonly padding: number; readonly maxChatWidth: number; + readonly maxHtmlPreviewWidth: number; readonly minChatWidth: number; readonly composerHeight: number; readonly timelineGutter: number; @@ -36,6 +37,7 @@ const INITIAL_MEASUREMENTS: ChatCanvasMeasurements = { height: 0, padding: 48, maxChatWidth: 768, + maxHtmlPreviewWidth: 768, minChatWidth: 640, composerHeight: 0, timelineGutter: 0, @@ -52,6 +54,7 @@ const sameMeasurements = (a: ChatCanvasMeasurements, b: ChatCanvasMeasurements) a.height === b.height && a.padding === b.padding && a.maxChatWidth === b.maxChatWidth && + a.maxHtmlPreviewWidth === b.maxHtmlPreviewWidth && a.minChatWidth === b.minChatWidth && a.composerHeight === b.composerHeight && a.timelineGutter === b.timelineGutter && @@ -135,6 +138,7 @@ export function resolveChatCanvasModel({ preview, padding: measurements.padding, maxChatWidth: measurements.maxChatWidth, + maxHtmlPreviewWidth: measurements.maxHtmlPreviewWidth, minChatWidth: measurements.minChatWidth, composerHeight: measurements.composerHeight, detailsCard, diff --git a/apps/web/src/components/chat/chatCanvasLayout.test.ts b/apps/web/src/components/chat/chatCanvasLayout.test.ts index 2f9e82a9e600b..53ee3f6b1ac7b 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.test.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.test.ts @@ -326,6 +326,53 @@ describe("chat canvas layout", () => { }); }); +describe("html preview lane", () => { + const wide = ( + width: number, + options: Partial[0]> = {}, + maxHtmlPreviewWidth = 1152, + ) => + resolveChatCanvasLayout({ + container: { width, height: 900 }, + preview: null, + maxChatWidth: 736, + maxHtmlPreviewWidth, + composerHeight: 180, + ...options, + }); + it("matches the chat column unless the setting allows more", () => { + const result = wide(1600, {}, 736); + expect(result.htmlPreview).toEqual({ left: result.chat.left, width: result.chat.width }); + }); + it("widens around a chat column that stays where it was", () => { + const result = wide(1600); + expect(result.chat).toEqual(wide(1600, {}, 736).chat); + expect(result.htmlPreview).toEqual({ left: 224, width: 1152 }); + expect(wide(1200).htmlPreview).toEqual({ left: 48, width: 1104 }); + expect(wide(1600, {}, 1600).htmlPreview).toEqual({ left: 48, width: 1504 }); + }); + it("is never narrower than the chat column", () => { + const result = wide(1600, { maxChatWidth: 1600 }, 1152); + expect(result.htmlPreview).toEqual({ left: result.chat.left, width: result.chat.width }); + }); + it("stops short of the details card", () => { + const detailsCard = { left: 1308, right: 1588, bottom: 400 }; + const result = wide(1600, { detailsCard }); + expect(result.chat).toEqual(wide(1600, { detailsCard }, 736).chat); + expect(result.htmlPreview).toEqual({ left: 124, width: 1152 }); + expect(wide(1600, { detailsCard }, 1600).htmlPreview).toEqual({ left: 48, width: 1228 }); + }); + it("stops short of a mini player beside the chat and matches chat under one over it", () => { + const beside = wide(1900, { preview: { ...preview, position: { x: 1500, y: 600 } } }); + expect(beside.overlapsChat).toBe(false); + expect(beside.htmlPreview.left + beside.htmlPreview.width).toBe(beside.frame!.x - 12); + expect(beside.htmlPreview.width).toBeGreaterThan(beside.chat.width); + const over = wide(1000, { preview: { ...preview, position: { x: 12, y: 700 } } }); + expect(over.overlapsChat).toBe(true); + expect(over.htmlPreview).toEqual({ left: over.chat.left, width: over.chat.width }); + }); +}); + describe("workspace card beside chat", () => { const withCard = (width: number, player: ChatCanvasPreview | null = null, maxChatWidth = 736) => resolveChatCanvasLayout({ diff --git a/apps/web/src/components/chat/chatCanvasLayout.ts b/apps/web/src/components/chat/chatCanvasLayout.ts index 77e276ee817f4..a1fc0b54b4ab1 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.ts @@ -26,6 +26,7 @@ export function resolveChatCanvasLayout({ preview, padding = 48, maxChatWidth = 768, + maxHtmlPreviewWidth = maxChatWidth, minChatWidth = 640, composerHeight = 0, detailsCard = null, @@ -35,6 +36,7 @@ export function resolveChatCanvasLayout({ preview: ChatCanvasPreview | null; padding?: number; maxChatWidth?: number; + maxHtmlPreviewWidth?: number; minChatWidth?: number; composerHeight?: number; detailsCard?: PreviewMiniPlayerObstacles["detailsCard"]; @@ -176,5 +178,19 @@ export function resolveChatCanvasLayout({ frame.x + frame.width > detailsCard.left && frame.y < detailsCard.bottom, ); - return { chat, frame, overlapsChat, overlapsDetailsCard }; + // A wider HTML preview stays centered on the chat column while that fits, and + // clear of the details card and a mini player the chat column sits beside. + const laneEnd = frame ? Math.min(laneRight, frame.x - GAP) : laneRight; + const htmlPreviewWidth = overlapsChat ? 0 : Math.min(maxHtmlPreviewWidth, laneEnd - padding); + const htmlPreview = + htmlPreviewWidth > chat.width + ? { + left: Math.max( + padding, + Math.min(chat.left + (chat.width - htmlPreviewWidth) / 2, laneEnd - htmlPreviewWidth), + ), + width: htmlPreviewWidth, + } + : { left: chat.left, width: chat.width }; + return { chat, htmlPreview, frame, overlapsChat, overlapsDetailsCard }; } diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index 72fda9150a7b2..1bb96d39c9794 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -5,6 +5,7 @@ import { DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE, DEFAULT_UNIFIED_SETTINGS, type ChatWidth, + type HtmlPreviewWidth, type EffortDisplay, type EnvironmentIdentificationMode, MAX_APPEARANCE_CONTRAST, @@ -80,6 +81,12 @@ const CHAT_WIDTH_LABELS: Record = { full: msg("Full", { $context: "chat width" }), }; +const HTML_PREVIEW_WIDTH_LABELS: Record = { + chat: msg("Match chat", { $context: "HTML preview width" }), + wide: CHAT_WIDTH_LABELS.wide, + full: CHAT_WIDTH_LABELS.full, +}; + const EFFORT_DISPLAY_LABELS: Record = { label: msg("Word", { $context: "show effort as a word" }), bars: msg("Bars", { $context: "show effort as bars" }), @@ -294,6 +301,48 @@ export function AppearanceSettingsPanel() {
} /> + + updateSettings({ htmlPreviewWidth: DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth }) + } + /> + ) : null + } + control={ +
+ +
+ } + /> void) { ? [gt("Diff colors")] : []), ...(settings.chatWidth !== DEFAULT_UNIFIED_SETTINGS.chatWidth ? [gt("Chat width")] : []), + ...(settings.htmlPreviewWidth !== DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth + ? [gt("HTML preview width")] + : []), ...(settings.effortDisplay !== DEFAULT_UNIFIED_SETTINGS.effortDisplay ? [gt("Effort display")] : []), @@ -709,6 +712,7 @@ export function useSettingsRestore(onRestored?: () => void) { appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast, diffColorScheme: DEFAULT_UNIFIED_SETTINGS.diffColorScheme, chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, + htmlPreviewWidth: DEFAULT_UNIFIED_SETTINGS.htmlPreviewWidth, effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay, mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, language: DEFAULT_UNIFIED_SETTINGS.language, diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 1f38ed958d368..fa933349eb400 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -380,6 +380,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/appearance", searchTerms: [msg("wide full width column layout messages composer monitor")], }, + { + id: "html-preview-width", + title: msg("HTML preview width"), + to: "/settings/appearance", + searchTerms: [msg("wide full width inline page render chart dashboard artifact centered")], + }, { id: "thread-details-items", title: msg("Thread details"), diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index bafbe7d7cb731..493f5021da2b1 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -7560,6 +7560,11 @@ "03338c6aec8edacd": "Lege fest, wie breit Nachrichten und das Eingabefeld auf großen Bildschirmen werden können.", "92785adb251da88c": "Chatbreite auf Standard zurücksetzen", "4d457bcce0c0e272": "Chatbreite", + "7d7f65967cc821e3": "Breite der HTML-Vorschau", + "70ce0af7f78d5957": "Lässt HTML-Vorschauen in einem Chat breiter werden als die Nachrichten, die zentriert bleiben.", + "f2b119bf02ae2558": "Breite der HTML-Vorschau auf Standard zurücksetzen", + "6287212fed0deec6": "Wie Chat", + "dc8e85ea0364649c": "Wie Chat (Standard)", "81f3a196537bbee0": "Komfortabel (Standard)", "e79e5388f669495f": "Den Denkaufwand im Eingabefeld als Namen, etwa Hoch, oder als Balken anzeigen.", "7f0365c7e4e8bcbf": "Anzeige des Aufwands auf Standard zurücksetzen", @@ -11828,6 +11833,7 @@ "9cf8308531b4ff31": "transparent transparenz deckend menüs dialoge eingabefeld", "d8d6cfd630cff22d": "rot grün blau orange hinzufügungen löschungen änderungen anzahl palette farbenblind", "717e49895cfee1c7": "breit volle breite spalte layout nachrichten eingabefeld monitor", + "9d5c7430a7ff76cf": "breit volle breite inline seite rendern diagramm dashboard artefakt zentriert", "88365077fd80787b": "anpassen anzeigen ausblenden panel karte umgebung editor skripte branch pull request git änderungen server automatisierungen herkunft nutzung limits 5 stunden wöchentlich kontingent tokens kontextfenster", "d561f74efa5f3920": "reasoning aufwand denken balken grafik wort bezeichnung stufe eingabefeld", "6113c17109ee0d57": "latex tex katex gleichungen formeln markdown", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index cde4bbb9458fa..15101ae706800 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -7568,6 +7568,11 @@ "03338c6aec8edacd": "Set how wide messages and the composer can grow on large screens.", "92785adb251da88c": "Reset chat width to default", "4d457bcce0c0e272": "Chat width", + "7d7f65967cc821e3": "HTML preview width", + "70ce0af7f78d5957": "Let HTML previews in a chat grow wider than its messages, which stay centered.", + "f2b119bf02ae2558": "Reset HTML preview width to default", + "6287212fed0deec6": "Match chat", + "dc8e85ea0364649c": "Match chat (default)", "81f3a196537bbee0": "Comfortable (default)", "e79e5388f669495f": "Show reasoning effort in the composer as its name, such as High, or as bars.", "7f0365c7e4e8bcbf": "Reset effort display to default", @@ -11836,6 +11841,7 @@ "9cf8308531b4ff31": "transparent transparency solid menus dialogs composer", "d8d6cfd630cff22d": "red green blue orange additions deletions changes counts palette colorblind", "717e49895cfee1c7": "wide full width column layout messages composer monitor", + "9d5c7430a7ff76cf": "wide full width inline page render chart dashboard artifact centered", "88365077fd80787b": "customize show hide panel card environment editor scripts branch pull request git changes servers automations lineage usage limits 5 hour weekly quota tokens context window", "d561f74efa5f3920": "reasoning effort thinking bars graph word label level composer", "6113c17109ee0d57": "latex tex katex equations formulas markdown", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index ee4496f0bfbc5..41ea55b0cce5e 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -7561,6 +7561,11 @@ "03338c6aec8edacd": "Define cuánto pueden crecer los mensajes y el cuadro de mensaje en pantallas grandes.", "92785adb251da88c": "Restablecer el ancho del chat al valor predeterminado", "4d457bcce0c0e272": "Ancho del chat", + "7d7f65967cc821e3": "Ancho de la vista previa HTML", + "70ce0af7f78d5957": "Permite que las vistas previas HTML de un chat sean más anchas que sus mensajes, que siguen centrados.", + "f2b119bf02ae2558": "Restablecer el ancho de la vista previa HTML al valor predeterminado", + "6287212fed0deec6": "Igual que el chat", + "dc8e85ea0364649c": "Igual que el chat (predeterminado)", "81f3a196537bbee0": "Cómodo (predeterminado)", "e79e5388f669495f": "Muestra el esfuerzo de razonamiento en el cuadro de mensaje por su nombre, como Alto, o con barras.", "7f0365c7e4e8bcbf": "Restablecer la visualización del esfuerzo al valor predeterminado", @@ -11821,6 +11826,7 @@ "9cf8308531b4ff31": "transparente transparencia sólido menús diálogos cuadro mensaje compositor", "d8d6cfd630cff22d": "rojo verde azul naranja adiciones eliminaciones cambios recuentos paleta daltonismo", "717e49895cfee1c7": "ancho ancho completo columna diseño mensajes cuadro mensaje compositor monitor", + "9d5c7430a7ff76cf": "ancho ancho completo en línea página renderizar gráfico panel artefacto centrado", "88365077fd80787b": "personalizar mostrar ocultar panel tarjeta entorno editor scripts rama pull request git cambios servidores automatizaciones linaje uso límites 5 horas semanal cuota tokens ventana de contexto", "d561f74efa5f3920": "esfuerzo de razonamiento pensamiento barras gráfico palabra etiqueta nivel cuadro mensaje compositor", "6113c17109ee0d57": "latex tex katex ecuaciones fórmulas markdown", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index dfb02854b6c38..3d27667384fdd 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -7562,6 +7562,11 @@ "03338c6aec8edacd": "Définissez la largeur maximale des messages et de la zone de saisie sur les grands écrans.", "92785adb251da88c": "Réinitialiser la largeur de la discussion à la valeur par défaut", "4d457bcce0c0e272": "Largeur de la discussion", + "7d7f65967cc821e3": "Largeur des aperçus HTML", + "70ce0af7f78d5957": "Permet aux aperçus HTML d’une discussion d’être plus larges que ses messages, qui restent centrés.", + "f2b119bf02ae2558": "Réinitialiser la largeur des aperçus HTML à la valeur par défaut", + "6287212fed0deec6": "Comme la discussion", + "dc8e85ea0364649c": "Comme la discussion (par défaut)", "81f3a196537bbee0": "Confortable (par défaut)", "e79e5388f669495f": "Afficher l’effort de raisonnement dans la zone de saisie par son nom, comme Élevé, ou sous forme de barres.", "7f0365c7e4e8bcbf": "Réinitialiser l’affichage de l’effort à la valeur par défaut", @@ -11826,6 +11831,7 @@ "9cf8308531b4ff31": "transparent transparence opaque menus boîtes de dialogue zone de saisie", "d8d6cfd630cff22d": "rouge vert bleu orange ajouts suppressions modifications compteurs palette daltonien", "717e49895cfee1c7": "large pleine largeur colonne mise en page messages zone de saisie écran", + "9d5c7430a7ff76cf": "large pleine largeur intégré page rendu graphique tableau de bord artefact centré", "88365077fd80787b": "personnaliser afficher masquer panneau carte environnement éditeur scripts branche pull request modifications git serveurs automatisations lignée utilisation limites 5 heures hebdomadaire quota jetons fenêtre de contexte", "d561f74efa5f3920": "effort de raisonnement réflexion barres graphique mot libellé niveau zone de saisie", "6113c17109ee0d57": "latex tex katex équations formules markdown", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index bba2c66a1adf0..27a9f41f8b7b9 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -7527,6 +7527,11 @@ "03338c6aec8edacd": "大きな画面でメッセージと入力欄を広げられる幅を設定します。", "92785adb251da88c": "チャットの幅をデフォルトにリセット", "4d457bcce0c0e272": "チャットの幅", + "7d7f65967cc821e3": "HTML プレビューの幅", + "70ce0af7f78d5957": "チャット内の HTML プレビューをメッセージより広く表示します。メッセージは中央のままです。", + "f2b119bf02ae2558": "HTML プレビューの幅をデフォルトにリセット", + "6287212fed0deec6": "チャットに合わせる", + "dc8e85ea0364649c": "チャットに合わせる (デフォルト)", "81f3a196537bbee0": "標準 (デフォルト)", "e79e5388f669495f": "入力欄での推論レベルの表示を、名前 (High など) またはバーから選択します。", "7f0365c7e4e8bcbf": "推論レベルの表示をデフォルトにリセット", @@ -11777,6 +11782,7 @@ "9cf8308531b4ff31": "透明 透過 不透明 メニュー ダイアログ 入力欄 transparency", "d8d6cfd630cff22d": "赤 緑 青 オレンジ 追加 削除 変更 件数 パレット 色覚 colorblind", "717e49895cfee1c7": "幅 全幅 列 レイアウト メッセージ 入力欄 モニター wide width", + "9d5c7430a7ff76cf": "幅 全幅 インライン ページ レンダリング グラフ ダッシュボード アーティファクト 中央 wide width", "88365077fd80787b": "カスタマイズ 表示 非表示 パネル カード 環境 エディター スクリプト ブランチ プルリクエスト Git 変更 サーバー オートメーション 系譜 使用量 上限 5 時間 週間 クォータ トークン コンテキストウィンドウ panel card", "d561f74efa5f3920": "推論レベル 思考 バー グラフ 単語 ラベル レベル 入力欄 reasoning effort", "6113c17109ee0d57": "LaTeX TeX KaTeX 数式 方程式 Markdown latex math", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 988724e7b1c8f..deb87364861ed 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -7528,6 +7528,11 @@ "03338c6aec8edacd": "큰 화면에서 메시지와 입력창이 넓어질 수 있는 폭을 설정합니다.", "92785adb251da88c": "채팅 너비 기본값으로 재설정", "4d457bcce0c0e272": "채팅 너비", + "7d7f65967cc821e3": "HTML 미리 보기 너비", + "70ce0af7f78d5957": "채팅의 HTML 미리 보기가 메시지보다 넓어질 수 있게 합니다. 메시지는 가운데에 유지됩니다.", + "f2b119bf02ae2558": "HTML 미리 보기 너비 기본값으로 재설정", + "6287212fed0deec6": "채팅에 맞춤", + "dc8e85ea0364649c": "채팅에 맞춤(기본값)", "81f3a196537bbee0": "보통(기본값)", "e79e5388f669495f": "입력창에서 추론 수준을 High 같은 이름 또는 막대로 표시합니다.", "7f0365c7e4e8bcbf": "추론 수준 표시 기본값으로 재설정", @@ -11773,6 +11778,7 @@ "9cf8308531b4ff31": "투명 투명도 불투명 메뉴 대화 상자 입력창", "d8d6cfd630cff22d": "빨간색 녹색 파란색 주황색 추가 삭제 변경 개수 팔레트 색맹", "717e49895cfee1c7": "넓게 전체 너비 열 레이아웃 메시지 입력창 모니터", + "9d5c7430a7ff76cf": "넓게 전체 너비 인라인 페이지 렌더링 차트 대시보드 아티팩트 가운데", "88365077fd80787b": "사용자 지정 표시 숨기기 패널 카드 환경 편집기 스크립트 브랜치 풀 리퀘스트 git 변경 사항 서버 자동화 계보 사용량 한도 5시간 주간 할당량 토큰 컨텍스트 창", "d561f74efa5f3920": "추론 수준 생각 막대 그래프 단어 레이블 수준 입력창", "6113c17109ee0d57": "latex tex katex 수식 공식 마크다운", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 286cde4c55168..9b3534dd3fd7d 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -7561,6 +7561,11 @@ "03338c6aec8edacd": "Define até que largura as mensagens e o editor de mensagens podem crescer em telas grandes.", "92785adb251da88c": "Redefinir a largura do chat para o padrão", "4d457bcce0c0e272": "Largura do chat", + "7d7f65967cc821e3": "Largura da pré-visualização HTML", + "70ce0af7f78d5957": "Permite que as pré-visualizações HTML de um chat fiquem mais largas que as mensagens, que continuam centralizadas.", + "f2b119bf02ae2558": "Redefinir a largura da pré-visualização HTML para o padrão", + "6287212fed0deec6": "Igual ao chat", + "dc8e85ea0364649c": "Igual ao chat (padrão)", "81f3a196537bbee0": "Confortável (padrão)", "e79e5388f669495f": "Mostra o esforço de raciocínio no editor de mensagens pelo nome, como Alto, ou como barras.", "7f0365c7e4e8bcbf": "Redefinir a exibição do esforço para o padrão", @@ -11826,6 +11831,7 @@ "9cf8308531b4ff31": "transparente transparência sólido menus caixas de diálogo editor de mensagens", "d8d6cfd630cff22d": "vermelho verde azul laranja adições exclusões alterações contagens paleta daltonismo", "717e49895cfee1c7": "largo largura total coluna layout mensagens editor de mensagens monitor", + "9d5c7430a7ff76cf": "largo largura total em linha página renderizar gráfico painel artefato centralizado", "88365077fd80787b": "personalizar mostrar ocultar painel cartão ambiente editor scripts branch pull request git alterações servidores automações linhagem uso limites 5 horas semanal cota tokens janela de contexto", "d561f74efa5f3920": "esforço de raciocínio pensamento barras gráfico palavra rótulo nível editor de mensagens", "6113c17109ee0d57": "latex tex katex equações fórmulas markdown", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4fbe93bc7f506..bfc04739cb8ad 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -7561,6 +7561,11 @@ "03338c6aec8edacd": "Задайте, насколько широкими могут быть сообщения и поле ввода на больших экранах.", "92785adb251da88c": "Сбросить ширину чата к значению по умолчанию", "4d457bcce0c0e272": "Ширина чата", + "7d7f65967cc821e3": "Ширина предпросмотра HTML", + "70ce0af7f78d5957": "Позволяет предпросмотрам HTML в чате быть шире сообщений, которые остаются по центру.", + "f2b119bf02ae2558": "Сбросить ширину предпросмотра HTML к значению по умолчанию", + "6287212fed0deec6": "Как у чата", + "dc8e85ea0364649c": "Как у чата (по умолчанию)", "81f3a196537bbee0": "Удобная (по умолчанию)", "e79e5388f669495f": "Показывать усилие рассуждения в поле ввода названием, например «Высокое», или полосками.", "7f0365c7e4e8bcbf": "Сбросить отображение усилия к значению по умолчанию", @@ -11827,6 +11832,7 @@ "9cf8308531b4ff31": "прозрачный прозрачность сплошной меню диалоги поле ввода", "d8d6cfd630cff22d": "красный зелёный синий оранжевый добавления удаления изменения счётчики палитра дальтонизм", "717e49895cfee1c7": "широкий полная ширина колонка раскладка сообщения поле ввода монитор", + "9d5c7430a7ff76cf": "широкий полная ширина встроенная страница рендер график дашборд артефакт по центру", "88365077fd80787b": "настроить показать скрыть панель карточка окружение редактор скрипты ветка пул-реквест git изменения серверы автоматизации происхождение использование лимиты 5 часов неделя квота токены контекстное окно", "d561f74efa5f3920": "усилие рассуждений размышление полосы график слово метка уровень поле ввода", "6113c17109ee0d57": "latex tex katex уравнения формулы markdown", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6759119ee8a98..4de2ac04990a3 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -7567,6 +7567,11 @@ "03338c6aec8edacd": "Ange hur breda meddelanden och inmatningsfältet kan bli på stora skärmar.", "92785adb251da88c": "Återställ chattbredd till standard", "4d457bcce0c0e272": "Chattbredd", + "7d7f65967cc821e3": "Bredd för HTML-förhandsvisning", + "70ce0af7f78d5957": "Låter HTML-förhandsvisningar i en chatt bli bredare än meddelandena, som förblir centrerade.", + "f2b119bf02ae2558": "Återställ bredd för HTML-förhandsvisning till standard", + "6287212fed0deec6": "Samma som chatten", + "dc8e85ea0364649c": "Samma som chatten (standard)", "81f3a196537bbee0": "Bekväm (standard)", "e79e5388f669495f": "Visa resonemangsnivån i inmatningsfältet som sitt namn, till exempel Hög, eller som staplar.", "7f0365c7e4e8bcbf": "Återställ visning av ansträngning till standard", @@ -11834,6 +11839,7 @@ "9cf8308531b4ff31": "transparent genomskinlighet solid menyer dialoger inmatningsfält", "d8d6cfd630cff22d": "röd grön blå orange tillägg borttagningar ändringar antal palett färgblind", "717e49895cfee1c7": "bred full bredd kolumn layout meddelanden inmatningsfält skärm", + "9d5c7430a7ff76cf": "bred full bredd inbäddad sida rendera diagram instrumentpanel artefakt centrerad", "88365077fd80787b": "anpassa visa dölj panel kort miljö redigerare skript gren pull request git ändringar servrar automatiseringar härkomst användning gränser 5 timmar vecka kvot token kontextfönster", "d561f74efa5f3920": "resonemang ansträngning tänkande staplar diagram ord etikett nivå inmatningsfält", "6113c17109ee0d57": "latex tex katex ekvationer formler markdown", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 3e4d7229881f3..7689205ddb802 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -7576,6 +7576,11 @@ "03338c6aec8edacd": "设置大屏幕上消息和输入框的最大宽度。", "92785adb251da88c": "重置聊天宽度为默认值", "4d457bcce0c0e272": "聊天宽度", + "7d7f65967cc821e3": "HTML 预览宽度", + "70ce0af7f78d5957": "让聊天中的 HTML 预览比消息更宽,消息仍保持居中。", + "f2b119bf02ae2558": "重置 HTML 预览宽度为默认值", + "6287212fed0deec6": "与聊天一致", + "dc8e85ea0364649c": "与聊天一致(默认)", "81f3a196537bbee0": "适中(默认)", "e79e5388f669495f": "在输入框中用名称(如 High)或条形显示推理强度。", "7f0365c7e4e8bcbf": "重置推理强度显示为默认值", @@ -11851,6 +11856,7 @@ "9cf8308531b4ff31": "透明 透明度 实色 菜单 对话框 输入框", "d8d6cfd630cff22d": "红 绿 蓝 橙 新增 删除 更改 计数 调色板 色盲", "717e49895cfee1c7": "宽 全宽 列 布局 消息 输入框 显示器", + "9d5c7430a7ff76cf": "宽 全宽 内嵌 页面 渲染 图表 仪表板 工件 居中", "88365077fd80787b": "自定义 显示 隐藏 面板 卡片 环境 编辑器 脚本 分支 PR git 更改 服务器 自动化 谱系 用量 限制 5 小时 每周 配额 token 上下文窗口", "d561f74efa5f3920": "推理强度 思考 条形 图表 文字 标签 级别 输入框", "6113c17109ee0d57": "latex tex katex 方程 公式 markdown", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 272c0269d9e28..4441b65f8143f 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -129,6 +129,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --workspace-titlebar-control-gap: 0.75rem; --workspace-titlebar-scroll-fade-height: 1.5rem; --chat-content-max-width: 46rem; + --html-preview-max-width: var(--chat-content-max-width); --thread-details-panel-width: 17.5rem; /* The prompt on phones: iOS zooms into any input under 16px on focus. */ --font-size-prompt-touch: max(var(--font-size-prompt, 1rem), 16px); @@ -982,6 +983,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil max-width: var(--chat-content-max-width); } + /* ChatCanvas sets these only while HTML previews run wider than the chat column. */ + .html-preview-lane { + width: var(--html-preview-lane-width, auto); + margin-inline-start: var(--html-preview-lane-offset, 0px); + } + .messages-timeline-row-frame { padding-inline: 0; } @@ -2366,6 +2373,16 @@ code { --chat-content-max-width: 100%; } +/* HTML preview width setting. ChatCanvas measures this and never lays a + preview out narrower than the chat column. */ +:root[data-html-preview-width="wide"] { + --html-preview-max-width: 72rem; +} + +:root[data-html-preview-width="full"] { + --html-preview-max-width: 100%; +} + :root[data-diff-color-scheme="blue-orange"] { --diff-addition: light-dark(var(--color-blue-600), var(--color-blue-400)); --diff-deletion: light-dark(var(--color-orange-600), var(--color-orange-400)); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index e7887f88f0369..5b6ce48c88833 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -352,6 +352,10 @@ export const DiffColorScheme = Schema.Literals(["red-green", "blue-orange"]); export const ChatWidth = Schema.Literals(["comfortable", "wide", "full"]); export type ChatWidth = typeof ChatWidth.Type; +/** How wide inline HTML previews grow: "chat" keeps them in the chat column. */ +export const HtmlPreviewWidth = Schema.Literals(["chat", "wide", "full"]); +export type HtmlPreviewWidth = typeof HtmlPreviewWidth.Type; + /** How the composer shows reasoning effort: the level's name, or rising bars. */ export const EffortDisplay = Schema.Literals(["label", "bars"]); export type EffortDisplay = typeof EffortDisplay.Type; @@ -418,6 +422,9 @@ export const ClientSettingsSchema = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed("red-green" as const)), ), chatWidth: ChatWidth.pipe(Schema.withDecodingDefault(Effect.succeed("comfortable" as const))), + htmlPreviewWidth: HtmlPreviewWidth.pipe( + Schema.withDecodingDefault(Effect.succeed("chat" as const)), + ), effortDisplay: EffortDisplay.pipe(Schema.withDecodingDefault(Effect.succeed("label" as const))), loadBalancingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), loadBalancingWeights: LoadBalancingWeights.pipe(Schema.withDecodingDefault(Effect.succeed({}))), @@ -2075,6 +2082,7 @@ export const ClientSettingsPatch = Schema.Struct({ inAppNotificationsEnabled: Schema.optionalKey(Schema.Boolean), diffColorScheme: Schema.optionalKey(DiffColorScheme), chatWidth: Schema.optionalKey(ChatWidth), + htmlPreviewWidth: Schema.optionalKey(HtmlPreviewWidth), effortDisplay: Schema.optionalKey(EffortDisplay), loadBalancingEnabled: Schema.optionalKey(Schema.Boolean), loadBalancingWeights: Schema.optionalKey(LoadBalancingWeights), From 6f8282c2c8a463487f883b7154a6066a883b8a7a Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 21:10:10 -0600 Subject: [PATCH 156/221] fix(web): an IME Escape no longer blurs the file editor (#41837) Co-authored-by: Julius Marminge --- .../fileEditorDismissal.browser.test.tsx | 57 +++++++++++++++++++ .../components/files/fileEditorDismissal.ts | 3 +- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx b/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx index 38c8e53156ecc..730ebb2d7cc5c 100644 --- a/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx +++ b/apps/web/src/components/files/fileEditorDismissal.browser.test.tsx @@ -64,6 +64,63 @@ describe("installFileEditorDismissal", () => { expect(window.getSelection()?.toString()).toBe("Assistant reply"); }); + it("leaves the editor focused when Escape belongs to an IME composition", async () => { + let editor: Editor<"file" | "file-diff", undefined, undefined> | undefined; + const createEditor: EditorFactory = (...args) => + (editor = new Editor(...args)); + await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] }); + await using screen = await render( +
+ + + +
, + ); + const shadowRoot = screen.container.querySelector("diffs-container")?.shadowRoot; + const content = shadowRoot?.querySelector("[data-content]"); + expect(content).toBeTruthy(); + content!.focus(); + const range = { start: { line: 0, character: 6 }, end: { line: 0, character: 12 } }; + editor!.setSelections([{ ...range, direction: "forward" }]); + const onDismiss = vi.fn(); + const onAppKeyDown = vi.fn(); + window.addEventListener("keydown", onAppKeyDown); + using _appKeyDown = { + [Symbol.dispose]: () => window.removeEventListener("keydown", onAppKeyDown), + }; + using _dismissal = { + [Symbol.dispose]: installFileEditorDismissal({ + root: screen.getByTestId("file-surface").element() as HTMLElement, + editor: editor!, + isBlocked: () => false, + onDismiss, + }), + }; + const pressEscape = (init: KeyboardEventInit) => { + const event = new KeyboardEvent("keydown", { + key: "Escape", + bubbles: true, + composed: true, + cancelable: true, + ...init, + }); + content!.dispatchEvent(event); + return event; + }; + + expect(pressEscape({ isComposing: true, keyCode: 27 }).defaultPrevented).toBe(false); + expect(pressEscape({ keyCode: 229 }).defaultPrevented).toBe(false); + + expect(onDismiss).not.toHaveBeenCalled(); + expect(onAppKeyDown).not.toHaveBeenCalled(); + expect(editor!.getViewState().selections).toMatchObject([range]); + expect(shadowRoot!.activeElement).toBe(content); + + expect(pressEscape({ keyCode: 27 }).defaultPrevented).toBe(true); + expect(onDismiss).toHaveBeenCalledOnce(); + expect(shadowRoot!.activeElement).toBeNull(); + }); + it("lets clicks beside the open search panel reach the file's code", async () => { let editor: Editor<"file" | "file-diff", undefined, undefined> | undefined; const createEditor: EditorFactory = (...args) => diff --git a/apps/web/src/components/files/fileEditorDismissal.ts b/apps/web/src/components/files/fileEditorDismissal.ts index 1291cfe9aeea0..9441893d15e91 100644 --- a/apps/web/src/components/files/fileEditorDismissal.ts +++ b/apps/web/src/components/files/fileEditorDismissal.ts @@ -39,8 +39,9 @@ export function installFileEditorDismissal({ }; const handleKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape" || isBlocked() || !isFileEditorFocused(root)) return; - event.preventDefault(); event.stopImmediatePropagation(); + if (event.isComposing || event.keyCode === 229) return; + event.preventDefault(); dismissFileEditorInteraction({ root, editor, onDismiss }); }; From 82af3cf2c364f549bfe1f11c756796c60dd83d80 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:15:03 -0800 Subject: [PATCH 157/221] fix(server): a thread resume replays a deleted thread from its deletion (#41874) Co-authored-by: Claude Fable 5.2 --- apps/server/src/ws.test.ts | 55 ++++++++++++++++++++++++++++++++++++++ apps/server/src/ws.ts | 6 ++++- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index d12488a1b0db7..2838be2a228a3 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -2168,6 +2168,61 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); +it.effect("thread resume replays a deleted thread's deletion and nothing recorded before it", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const now = "2026-10-13T00:00:00.000Z"; + const threadId = ThreadId.make("thread:deleted-resume"); + const insert = (version: number, type: string, payload: object) => sql` + INSERT INTO orchestration_events ( + event_id, aggregate_kind, stream_id, stream_version, event_type, + occurred_at, actor_kind, payload_json, metadata_json, application_event_version + ) VALUES ( + ${`deleted-resume:${version}`}, 'thread', ${threadId}, ${version}, ${type}, + ${now}, 'server', ${JSON.stringify(payload)}, '{}', 2 + ) + `; + const detached = { providerSessionId: "session:deleted-resume", detachedAt: now }; + yield* insert(0, "provider-session.detached", detached); + yield* insert(1, "provider-session.detached", detached); + yield* insert(2, "thread.deleted", { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: "project:deleted-resume", + title: "Deleted", + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "default" }, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: now, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + }); + + const items = yield* subscribeOrchestrationV2Thread({ threadId, afterSequence: 0 }).pipe( + Effect.flatMap(Stream.runCollect), + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + streamStoredEventsFrom: () => Stream.empty, + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + ); + assert.deepEqual( + Array.from(items).map((item) => item.kind === "event" && item.event.type), + ["thread.deleted"], + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + // A prune pass can delete replayed rows after the boundary check; the read must not be trusted. it.effect.each(["thread", "shell"] as const)( "%s resume loads a snapshot when pruning advances during the replay read", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index f0f746eb8041f..583b1919aa5e0 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1132,7 +1132,11 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs ) { return yield* snapshotThenLive(); } - const replay = coalesceLiveUpdatedEvents(replayed); + // A deleted thread reads as gone: its replay starts at the deletion. + const deletion = replayed.findLastIndex((item) => item.event.type === "thread.deleted"); + const replay = coalesceLiveUpdatedEvents( + deletion === -1 ? replayed : replayed.slice(deletion), + ); const plan = decideThreadResume({ afterSequence: input.afterSequence, highWater, From 036751b6f5556fcf221ef9483bec6ba358af22c8 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 21:15:33 -0600 Subject: [PATCH 158/221] fix(web): Esc in project icon search clears it without closing the dialog (#41856) Co-authored-by: Julius Marminge --- .../ProjectIconPickerDialog.browser.test.tsx | 50 +++++++++++++++++++ .../settings/ProjectIconPickerDialog.tsx | 15 +++++- 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx new file mode 100644 index 0000000000000..a45214f545ca6 --- /dev/null +++ b/apps/web/src/components/settings/ProjectIconPickerDialog.browser.test.tsx @@ -0,0 +1,50 @@ +import { page, userEvent } from "vite-plus/test/browser"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { ProjectIconPickerDialog } from "./ProjectIconPickerDialog"; + +import "~/index.css"; + +it("Escape in the icon search clears it without closing the dialog", async () => { + const onOpenChange = vi.fn(); + await using _screen = await render( + {}} + />, + ); + const search = page.getByRole("searchbox", { name: "Search Lucide icons" }); + await expect.element(search).toHaveAttribute("type", "text"); + await userEvent.fill(search, "rocket"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + search + .element() + .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true })); + }); + await expect.element(search).toHaveValue("rocket"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + await expect.element(search).toHaveFocus(); + // Holding Escape repeats the keydown, which must not also close the dialog. + await act(() => { + search + .element() + .dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true })); + }); + expect(onOpenChange).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + expect(onOpenChange.mock.calls.map(([open]) => open)).toEqual([false]); +}); diff --git a/apps/web/src/components/settings/ProjectIconPickerDialog.tsx b/apps/web/src/components/settings/ProjectIconPickerDialog.tsx index 44942c2ce0c47..258f975a31905 100644 --- a/apps/web/src/components/settings/ProjectIconPickerDialog.tsx +++ b/apps/web/src/components/settings/ProjectIconPickerDialog.tsx @@ -171,12 +171,25 @@ function ProjectIconPickerBody({ {mode === "lucide" ? ( <> + {/* Native search inputs clear on Escape even during IME composition. */} setQuery(event.currentTarget.value)} + onKeyDown={(event) => { + if ( + event.key !== "Escape" || + event.nativeEvent.isComposing || + event.keyCode === 229 + ) + return; + if (!query && !event.repeat) return; + event.stopPropagation(); + setQuery(""); + }} />
From 637cd28599b0364630f10745321f7ce78d03bc28 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:16:10 -0800 Subject: [PATCH 159/221] fix(client-runtime): Remove is no longer offered on a route the environment cannot lose (#41845) --- .../settings/EnvironmentRoutesSection.tsx | 6 ++---- .../EnvironmentRoutesList.browser.test.tsx | 20 +++++++++++++++++++ .../settings/EnvironmentRoutesList.tsx | 3 ++- .../client-runtime/src/connection/routes.ts | 14 +++++++++++++ 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx index 8e5cf5f500856..86641489f35cd 100644 --- a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx +++ b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx @@ -3,6 +3,7 @@ import { Button } from "../../components/ui/Button"; import * as Dialog from "../../components/ui/Dialog"; import { useAtomValue } from "@effect/atom-react"; import { + canRemoveRoute, type ConnectionRoute, type ConnectionRouteKind, connectionRouteAddress, @@ -225,10 +226,7 @@ export function EnvironmentRoutesSection({ if (!cancelled) move(index, dropIndex(index, translation)); }} onStep={(direction) => move(index, direction === "up" ? index - 1 : index + 1)} - // A learned route would be learned again, so it is only reordered. - onRemove={ - routes.length > 1 && !isLearned(route) ? () => confirmRemove(route) : undefined - } + onRemove={canRemoveRoute(routes, route) ? () => confirmRemove(route) : undefined} /> ); })} diff --git a/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx b/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx index 39b9cac03ede1..17689eb8581fb 100644 --- a/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx +++ b/apps/web/src/components/settings/EnvironmentRoutesList.browser.test.tsx @@ -3,6 +3,7 @@ import { BearerConnectionTarget, type ConnectionCatalogEntry, type ConnectionRoute, + mergeLearnedRoutes, } from "@t3tools/client-runtime/connection"; import { EnvironmentId } from "@t3tools/contracts"; import * as Option from "effect/Option"; @@ -91,3 +92,22 @@ it("shows a route added after a reorder was saved, once another route is removed .element(screen.getByRole("button", { name: "Remove desk.example.com route" })) .toBeVisible(); }); + +it("does not offer to remove the only route a found-automatically route depends on", async () => { + const paired: ConnectionCatalogEntry = { + target: LAN.target, + profile: LAN.profile, + alternateRoutes: [], + enabled: true, + }; + const learned = mergeLearnedRoutes({ + entry: paired, + activeRoute: LAN, + reported: [{ httpBaseUrl: "https://desk.tail1234.ts.net/", kind: "tailnet" }], + allowInsecure: true, + })!; + await using screen = await render(routesList(learned)); + await expect.element(screen.getByText(/found automatically/)).toBeVisible(); + + expect(screen.getByRole("button", { name: "Remove LAN route" }).elements()).toHaveLength(0); +}); diff --git a/apps/web/src/components/settings/EnvironmentRoutesList.tsx b/apps/web/src/components/settings/EnvironmentRoutesList.tsx index f559f85ce80f7..f4b9a1593b9d8 100644 --- a/apps/web/src/components/settings/EnvironmentRoutesList.tsx +++ b/apps/web/src/components/settings/EnvironmentRoutesList.tsx @@ -17,6 +17,7 @@ import { } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { + canRemoveRoute, type ConnectionRoute, connectionRouteAddress, connectionRouteId, @@ -121,7 +122,7 @@ export function EnvironmentRoutesList({ position={index + 1} inUse={connectionRouteId(route.target) === activeRouteId} refused={environment.refusedRouteIds.includes(connectionRouteId(route.target))} - removable={routes.length > 1 && !isLearned(route)} + removable={canRemoveRoute(routes, route)} onRemove={() => void confirmRemove(route)} /> ))} diff --git a/packages/client-runtime/src/connection/routes.ts b/packages/client-runtime/src/connection/routes.ts index 1ae8df56fc109..0a2c38445b1b6 100644 --- a/packages/client-runtime/src/connection/routes.ts +++ b/packages/client-runtime/src/connection/routes.ts @@ -477,6 +477,20 @@ export function routesAfterRemoving( }); } +/** + * A route is offered for removal only when removing it leaves a route behind. + * A learned route would be learned again, and the last route a learned route + * borrows from would take the whole environment with it. + */ +export function canRemoveRoute( + routes: ReadonlyArray, + route: ConnectionRoute, +): boolean { + return ( + !isLearned(route) && routesAfterRemoving(routes, connectionRouteId(route.target)).length > 0 + ); +} + /** * A dragged route order shows until the saved routes catch up with it. It is * stale, and returns null, once the saved order matches it or the saved routes From 7913360b2e61bb04086229c4ec283e512c8d7a9e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:17:25 -0800 Subject: [PATCH 160/221] fix(server): saving a voice key reference needs provider management (#41876) Co-authored-by: Claude Fable 5.2 --- .../features/settings/CloudVoiceSection.tsx | 3 +++ apps/server/src/speech/http.test.ts | 20 ++++++++++++++++--- apps/server/src/speech/http.ts | 10 ++++++++++ .../settings/CloudVoiceConfiguration.tsx | 3 +++ 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/settings/CloudVoiceSection.tsx b/apps/mobile/src/features/settings/CloudVoiceSection.tsx index 3e782d2457fa3..1e32e2585e072 100644 --- a/apps/mobile/src/features/settings/CloudVoiceSection.tsx +++ b/apps/mobile/src/features/settings/CloudVoiceSection.tsx @@ -8,6 +8,7 @@ import { secretRequestReference, } from "@t3tools/client-runtime/secret-request"; import { + AuthProvidersManageScope, AuthSettingsWriteScope, CLOUD_SPEECH_LABELS, CLOUD_SPEECH_PROVIDER_NAMES, @@ -188,6 +189,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const keys = useAtomValue(cloudVoiceKeysAtom(id)); const reload = useAtomRefresh(cloudVoiceKeysAtom(id)); const canManage = useEnvironmentScope(id, AuthSettingsWriteScope); + const canUseReferences = useEnvironmentScope(id, AuthProvidersManageScope); const [editing, setEditing] = useState<{ provider: CloudSpeechProvider; enable: boolean; @@ -199,6 +201,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const [model, setModel] = useState(""); const [sourceId, setSourceId] = useState(null); const sources = + canUseReferences && hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings.secretProviders, messages) diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index 8bbf2d81bc065..c6d5405cfa82c 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -7,6 +7,7 @@ import { expect, vi } from "vite-plus/test"; import { AuthSessionId, AuthOrchestrationOperateScope, + AuthProvidersManageScope, AuthSettingsWriteScope, type AuthEnvironmentScope, CloudSpeechError, @@ -37,17 +38,18 @@ import { speechHttpApiLayer } from "./http.ts"; const decodeSessionId = Schema.decodeUnknownSync(AuthSessionId); -const principal = (...scopes: AuthEnvironmentScope[]) => +const principalWith = (scopes: ReadonlySet) => Layer.succeed(EnvironmentAuthenticatedAuth, (effect) => effect.pipe( Effect.provideService(EnvironmentAuthenticatedPrincipal, { sessionId: decodeSessionId("voice-test"), subject: "test", method: "bearer-access-token", - scopes: new Set(scopes), + scopes, }), ), ); +const principal = (...scopes: AuthEnvironmentScope[]) => principalWith(new Set(scopes)); const dependencies = Layer.mergeAll( Layer.mock(CloudSpeech.CloudSpeech)({}), @@ -145,6 +147,10 @@ effectIt.effect( Effect.gen(function* () { let stored = false; const reference = { provider: "work", reference: "op://Work/Voice/key" }; + const scopes = new Set([ + AuthOrchestrationOperateScope, + AuthSettingsWriteScope, + ]); const save = vi.fn(); const transcribe = vi.fn(); const cloud = Layer.mock(CloudSpeech.CloudSpeech)({ @@ -182,7 +188,7 @@ effectIt.effect( const { handler, dispose } = HttpRouter.toWebHandler( HttpApiBuilder.layer(HttpApi.make("environment").add(EnvironmentVoiceHttpApi)).pipe( Layer.provide(speechHttpApiLayer), - Layer.provide(principal(AuthOrchestrationOperateScope, AuthSettingsWriteScope)), + Layer.provide(principalWith(scopes)), Layer.provide( Layer.mock(SpeechService.SpeechService)({ models: () => Effect.succeed({ models: [linkedModel] }), @@ -220,6 +226,14 @@ effectIt.effect( headers: { "content-type": "application/json" }, body: JSON.stringify({ key }), }); + // A reference needs the scope that saving it through settings would. + const refused = yield* setReference(reference); + expect(refused.status).toBe(403); + expect(yield* Effect.promise(() => refused.json())).toMatchObject({ + requiredPermission: AuthProvidersManageScope, + }); + expect(save).toHaveBeenCalledTimes(1); + scopes.add(AuthProvidersManageScope); expect((yield* setReference(reference)).status).toBe(204); expect(save).toHaveBeenLastCalledWith("xai", reference); expect((yield* setReference(reference.reference)).status).toBe(400); diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index 09c3d4dc23faa..f73640044be89 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -8,6 +8,7 @@ import { EnvironmentHttpApi, type EnvironmentSpeechModels, EnvironmentVoiceBodyLimit, + requiredScopesForServerSettingsPatch, SPEECH_MAX_OPTIONS_BYTES, TextGenerationError, } from "@t3tools/contracts"; @@ -15,6 +16,7 @@ import * as ByteSize from "effect/ByteSize"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; import * as Schema from "effect/Schema"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; @@ -102,6 +104,14 @@ export const speechHttpApiLayer = HttpApiBuilder.group( "setCloudKey", Effect.fn("environment.voice.setCloudKey")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); + // The key is a setting, so saving it needs what the same settings patch would. + const { key } = args.payload; + const value = key === null || Redacted.isRedacted(key) ? "" : key; + for (const scope of requiredScopesForServerSettingsPatch({ + cloudSpeechCredentials: { [args.params.provider]: value }, + })) { + yield* requireEnvironmentScope(scope); + } yield* cloud .setKey(args.params.provider, args.payload.key) .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error))); diff --git a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx index 0a992f4f93b61..3d41537abf182 100644 --- a/apps/web/src/components/settings/CloudVoiceConfiguration.tsx +++ b/apps/web/src/components/settings/CloudVoiceConfiguration.tsx @@ -13,6 +13,7 @@ import { } from "@t3tools/client-runtime/voice-input"; import { AuthOrchestrationOperateScope, + AuthProvidersManageScope, AuthSettingsWriteScope, CloudSpeechApiKey, CloudSpeechModelId, @@ -176,6 +177,7 @@ export function CloudVoiceConfiguration({ const prepared = Option.getOrNull(usePreparedConnection(id)); const canUse = useEnvironmentScope(id, AuthOrchestrationOperateScope); const canManage = useEnvironmentScope(id, AuthSettingsWriteScope); + const canUseReferences = useEnvironmentScope(id, AuthProvidersManageScope); const [presence, refresh] = useCloudRead(canUse ? prepared : null, getCloudSpeechKeys); const [models, refreshModels] = useCloudRead( routed && canUse ? prepared : null, @@ -194,6 +196,7 @@ export function CloudVoiceConfiguration({ const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined; const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider]; const sources = + canUseReferences && hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) From d36fb7d263ac2267496b21f21e1cdf081d396549 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:19:28 -0800 Subject: [PATCH 161/221] fix(web): Open in file manager waits for a file preview to load, then shows the file in its folder (#41877) Co-authored-by: Claude Fable 5.2 --- .../chat/OpenInPicker.browser.test.tsx | 33 +++++++++++++++++-- .../chat/OpenInPicker.logic.test.ts | 15 ++++++++- .../src/components/chat/OpenInPicker.logic.ts | 15 +++++++++ apps/web/src/components/chat/OpenInPicker.tsx | 24 +++++++++----- .../src/components/files/FilePreviewPanel.tsx | 15 +++++---- 5 files changed, 84 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index cc246a1f9967c..51d06370dd838 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -66,6 +66,7 @@ vi.mock(import("../../remoteOpen"), async (importOriginal) => ({ })); import { OpenInPicker } from "./OpenInPicker"; +import type { FileManagerAction } from "./OpenInPicker.logic"; import { registerOpenFavoriteEditorCommand, useOpenFavoriteEditorShortcut, @@ -98,7 +99,7 @@ async function setup() { async function renderPicker( availableEditors: readonly EditorId[] = editors, panel = false, - { openInCwd = "/work/project", revealFileManager = false } = {}, + { openInCwd = "/work/project", fileManagerAction = "open" as FileManagerAction } = {}, ) { await act(async () => { for (const listener of state.listeners) listener(); @@ -108,7 +109,7 @@ async function setup() { keybindings={DEFAULT_RESOLVED_KEYBINDINGS} availableEditors={availableEditors} openInCwd={openInCwd} - revealFileManager={revealFileManager} + fileManagerAction={fileManagerAction} displayMode={panel ? "panel" : "toolbar"} compact={!panel} /> @@ -189,6 +190,34 @@ describe("host editor access", () => { }); }); +describe("file manager", () => { + it("waits for the path's type, then shows a file in its folder", async () => { + await using fixture = await setup(); + const { renderPicker, primaryButton, click, pressOpenFavorite } = fixture; + state.allowed.add(selected); + const openInCwd = "/work/project/notes.md"; + await renderPicker(["file-manager"], false, { openInCwd, fileManagerAction: "unavailable" }); + + expect(primaryButton().disabled).toBe(true); + await click(primaryButton()); + expect((await pressOpenFavorite()).defaultPrevented).toBe(false); + expect(state.run).not.toHaveBeenCalled(); + + // A failed open is not announced, so no timer outlives the test. + state.run.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("No file manager")))); + await renderPicker(["file-manager"], false, { openInCwd, fileManagerAction: "reveal" }); + await click(primaryButton()); + expect(state.run.mock.calls).toEqual([ + [ + { + environmentId: selected, + input: { cwd: openInCwd, editor: "file-manager", reveal: true }, + }, + ], + ]); + }); +}); + describe("remote editor links", () => { it("opens the link from the fallback when the picker is not mounted", async () => { await using fixture = await setup(); diff --git a/apps/web/src/components/chat/OpenInPicker.logic.test.ts b/apps/web/src/components/chat/OpenInPicker.logic.test.ts index 10595e2f8cdbe..3b5536c78f396 100644 --- a/apps/web/src/components/chat/OpenInPicker.logic.test.ts +++ b/apps/web/src/components/chat/OpenInPicker.logic.test.ts @@ -1,7 +1,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { shouldShowOpenInPicker } from "./OpenInPicker.logic"; +import { fileManagerActionForPath, shouldShowOpenInPicker } from "./OpenInPicker.logic"; describe("shouldShowOpenInPicker", () => { it("shows both local environments when the primary has a separate WSL home", () => { @@ -24,3 +24,16 @@ describe("shouldShowOpenInPicker", () => { } }); }); + +describe("fileManagerActionForPath", () => { + it("opens only folders and shows a file once its read settled on a server that can", () => { + for (const [isFolder, isSettled, canReveal, action] of [ + [true, false, false, "open"], + [false, false, true, "unavailable"], + [false, true, false, "unavailable"], + [false, true, true, "reveal"], + ] as const) { + expect(fileManagerActionForPath({ isFolder, isSettled, canReveal })).toBe(action); + } + }); +}); diff --git a/apps/web/src/components/chat/OpenInPicker.logic.ts b/apps/web/src/components/chat/OpenInPicker.logic.ts index 5978a5986030a..8e49592e05866 100644 --- a/apps/web/src/components/chat/OpenInPicker.logic.ts +++ b/apps/web/src/components/chat/OpenInPicker.logic.ts @@ -18,3 +18,18 @@ export function shouldShowOpenInPicker(input: { } return input.remoteOpenMode !== "local-exec"; } + +export type FileManagerAction = "open" | "reveal" | "unavailable"; + +/** + * The file manager opens folders and shows files in their folder. A path whose read has not + * settled may be either, and a file needs the server's reveal support, so both wait. + */ +export function fileManagerActionForPath(input: { + readonly isFolder: boolean; + readonly isSettled: boolean; + readonly canReveal: boolean; +}): FileManagerAction { + if (input.isFolder) return "open"; + return input.isSettled && input.canReveal ? "reveal" : "unavailable"; +} diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index fc125bbd79cfa..a4b7322aa5dda 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -10,6 +10,7 @@ import { T, useGT, useMessages, Var } from "gt-react"; import { memo, use, useRef } from "react"; import { BackgroundThreadContext } from "./backgroundThread"; import { shortcutLabelForCommand } from "../../keybindings"; +import type { FileManagerAction } from "./OpenInPicker.logic"; import { OPEN_FAVORITE_EDITOR_ATTRIBUTE } from "./OpenInPickerShortcut"; import { usePreferredEditor } from "../../editorPreferences"; import { editorLabelForPlatform } from "../../editorLabels"; @@ -81,7 +82,7 @@ export const OpenInPicker = memo(function OpenInPicker({ compact = false, enableShortcut = true, displayMode = "toolbar", - revealFileManager = false, + fileManagerAction = "open", }: { environmentId: EnvironmentId; keybindings: ResolvedKeybindingsConfig; @@ -92,7 +93,7 @@ export const OpenInPicker = memo(function OpenInPicker({ compact?: boolean; enableShortcut?: boolean; displayMode?: "toolbar" | "panel"; - revealFileManager?: boolean; + fileManagerAction?: FileManagerAction; }) { const gt = useGT(); const messages = useMessages(); @@ -111,11 +112,13 @@ export const OpenInPicker = memo(function OpenInPicker({ // Remote editors run on the viewing machine; only desktop can probe that PATH. const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors; const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors); + const isEditorUnavailable = (editor: EditorId | null) => + editor === "file-manager" && fileManagerAction === "unavailable"; const openInEditor = async (editorId: EditorId | null): Promise => { if (!openInCwd) return false; const editor = editorId ?? preferredEditor; - if (!editor) return false; + if (!editor || isEditorUnavailable(editor)) return false; if (remote.mode === "remote-unavailable") return false; if (remote.mode === "remote-links") { const url = buildRemoteOpenUrl({ @@ -139,7 +142,7 @@ export const OpenInPicker = memo(function OpenInPicker({ input: { cwd: openInCwd, editor, - ...(revealFileManager && editor === "file-manager" ? { reveal: true } : {}), + ...(fileManagerAction === "reveal" && editor === "file-manager" ? { reveal: true } : {}), }, }); setPreferredEditor(editor); @@ -187,7 +190,11 @@ export const OpenInPicker = memo(function OpenInPicker({ {options.map(({ label, Icon, value, kind }) => ( { if (presentation === "menu") { @@ -223,8 +230,7 @@ export const OpenInPicker = memo(function OpenInPicker({ {primaryOption && ( openInEditor(preferredEditor)} > @@ -261,7 +267,9 @@ export const OpenInPicker = memo(function OpenInPicker({ variant={isPanel ? "ghost" : "outline"} part="primary" panel={isPanel} - disabled={!preferredEditor || !openInCwd || !canOpenEditor} + disabled={ + !preferredEditor || !openInCwd || !canOpenEditor || isEditorUnavailable(preferredEditor) + } {...(enableShortcut && !backgroundThread ? { [OPEN_FAVORITE_EDITOR_ATTRIBUTE]: "" } : {})} onClick={() => { if (!preferredEditor) return; diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 2ef4d67095e55..8a59d79db24d6 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -64,6 +64,7 @@ import { import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; import { OpenInPicker } from "~/components/chat/OpenInPicker"; +import { fileManagerActionForPath } from "~/components/chat/OpenInPicker.logic"; import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer"; import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions"; import { useRemoteOpenState } from "~/remoteOpen"; @@ -1311,12 +1312,12 @@ export default function FilePreviewPanel({ attachment === undefined && (file.isNotFile || (folderTrail !== undefined && file.data === null && file.error === null)); const hostFolderPath = isFolder && isHostFile ? relativePath : null; - // A chat-linked folder reads as a file until its read settles, and revealing a - // folder selects it in its parent instead of opening it, so reveal waits. - const revealsInFileManager = - !isFolder && - (file.data !== null || file.error !== null) && - serverConfig?.shellRevealInFileManager === true; + // A chat-linked folder reads as a file until its read settles, and a trail only implies a folder. + const fileManagerAction = fileManagerActionForPath({ + isFolder: relativePath === null || file.isNotFile, + isSettled: file.data !== null || file.error !== null, + canReveal: serverConfig?.shellRevealInFileManager === true, + }); // Everything preview-related keys off previewPath; a folder has no preview. const previewPath = isFolder ? null : relativePath; const [explorerOpen, setExplorerOpen] = useState(initialExplorerOpen); @@ -1613,7 +1614,7 @@ export default function FilePreviewPanel({ openInCwd={absolutePath} openInCwdIsFile={file.isFile} compact - revealFileManager={revealsInFileManager} + fileManagerAction={fileManagerAction} /> ) : null} {canToggleRendered && renderedMode ? ( From f981b42dc490aed87c2c91ddd88b5d497eb811fd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:20:51 -0800 Subject: [PATCH 162/221] fix(mobile): the default-branch confirmation describes the live checkout (#41880) Co-authored-by: Claude Fable 5.2 --- .../pull-requests/PullRequestRouteScreen.tsx | 4 +- .../pull-requests/usePullRequestDiff.test.tsx | 20 ++- .../pull-requests/usePullRequestDiff.ts | 14 ++ .../features/threads/ThreadGitControls.tsx | 2 - .../threads/git/GitConfirmSheet.test.tsx | 124 ++++++++++++++++++ .../features/threads/git/GitConfirmSheet.tsx | 66 +++++----- .../features/threads/git/GitOverviewSheet.tsx | 4 - apps/mobile/vite.config.ts | 1 + 8 files changed, 192 insertions(+), 43 deletions(-) create mode 100644 apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index 488ca226d64c9..c0a644321a66f 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -116,6 +116,7 @@ import { usePullRequestVerticalControls, } from "./PullRequestControls"; import { + pullRequestParams, pullRequestTarget as requestTarget, usePullRequestDiff, usePullRequestDiffEntry, @@ -408,7 +409,8 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps pullRequestParams(route.params), [route.params]); usePullRequestEnvironmentFallback(params); const connected = usePullRequestConnected(params.environmentId); const [chosenSection, setSection] = useState<"overview" | "activity" | "guide">(() => { diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx index 7d4244a5c04a5..282a18ca2443b 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx +++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx @@ -10,7 +10,11 @@ import { expect, it, vi } from "vite-plus/test"; const mocks = vi.hoisted(() => ({ diff: vi.fn() })); vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { diff: mocks.diff } })); -import { usePullRequestDiff, usePullRequestDiffEntry } from "./usePullRequestDiff"; +import { + pullRequestParams, + usePullRequestDiff, + usePullRequestDiffEntry, +} from "./usePullRequestDiff"; import * as reviewModel from "../review/reviewModel"; import { getCachedNativeReviewDiffData } from "../review/nativeReviewDiffAdapter"; @@ -290,3 +294,17 @@ it("holds further pages back until a pull to refresh has reread page one", async expect(screen.current.patch).toContain("+pushed"); expect(screen.current.canLoadMore).toBe(true); }); + +it("keeps only the pull request a route names", () => { + const pullRequest = { + environmentId: "environment", + projectId: "project", + repository: "owner/repo", + number: 1, + host: "git.example.com", + navigationUrl: "https://git.example.com/owner/repo/pull/1#discussion_r1", + navigationId: 2, + }; + const routeParams = { ...pullRequest, commit: "abc1234", path: "src/index.ts" }; + expect(pullRequestParams(routeParams)).toEqual(pullRequest); +}); diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts index 5cf121b7f5660..85527e491c93a 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts @@ -34,6 +34,20 @@ export type PullRequestParams = { export type PullRequestDiffParams = PullRequestParams & { readonly commit?: string }; +/** The pull request a route names, without whatever else arrived on that route. */ +export function pullRequestParams(params: PullRequestParams): PullRequestParams { + return { + environmentId: params.environmentId, + projectId: params.projectId, + repository: params.repository, + number: params.number, + ...(params.host === undefined ? {} : { host: params.host }), + ...(params.navigationUrl === undefined ? {} : { navigationUrl: params.navigationUrl }), + ...(params.navigationId === undefined ? {} : { navigationId: params.navigationId }), + ...(params.initialSummary === undefined ? {} : { initialSummary: params.initialSummary }), + }; +} + export function pullRequestTarget(params: PullRequestParams) { return { environmentId: EnvironmentId.make(params.environmentId), diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 5e67fb0181ad5..1a36d6b350e4a 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -237,8 +237,6 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) { environmentId: String(environmentId), threadId: String(threadId), confirmAction: confirmableAction, - branchName, - includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"), }); return; } diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx new file mode 100644 index 0000000000000..90b9580fd48bc --- /dev/null +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx @@ -0,0 +1,124 @@ +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +type ActionProps = { label: string; disabled?: boolean; onPress: () => void }; +type IntroProps = { title: string; description: string }; +const state = vi.hoisted(() => ({ + refName: null as string | null, + intro: null as IntroProps | null, + actions: [] as ActionProps[], + ran: [] as object[], +})); + +vi.mock("react-native", () => ({ + View: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("@react-navigation/native", () => ({ + useNavigation: () => ({ goBack: () => {} }), +})); +vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); +vi.mock("../../../components/ui/FitSheet", () => ({ + FitSheet: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../../components/ui/SheetIntro", () => ({ + SheetIntro: (props: IntroProps) => { + state.intro = props; + return null; + }, +})); +vi.mock("../../../state/query", () => ({ + useEnvironmentQuery: () => ({ + data: state.refName === null ? undefined : { refName: state.refName }, + }), +})); +vi.mock("../../../state/use-thread-selection", () => ({ + useThreadSelection: () => ({ + selectedThread: { environmentId: "environment" }, + selectedThreadProject: null, + }), +})); +vi.mock("../../../state/use-selected-thread-worktree", () => ({ + useSelectedThreadWorktree: () => ({ selectedThreadCwd: "/repo" }), +})); +vi.mock("../../../state/use-selected-thread-git-state", () => ({ + useSelectedThreadGitState: () => ({ selectedThreadBranches: [] }), +})); +vi.mock("../../../state/use-selected-thread-git-actions", () => ({ + useSelectedThreadGitActions: () => ({ + canWriteSourceControl: true, + canCreateFeatureBranch: true, + onRunSelectedThreadGitAction: (input: object) => { + state.ran.push(input); + return Promise.resolve(null); + }, + }), +})); +vi.mock("../../../state/vcs", () => ({ vcsEnvironment: { status: () => null } })); +vi.mock("../thread-inspector-navigation", () => ({ useReturnToThread: () => () => {} })); +vi.mock("./gitSheetComponents", () => ({ + SheetActionButton: (props: ActionProps) => { + state.actions.push(props); + return null; + }, +})); + +import { GitConfirmSheet } from "./GitConfirmSheet"; + +function setup(refName: string | null, params: Record) { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + state.refName = refName; + state.intro = null; + state.actions = []; + state.ran = []; + const root = createRoot(document.createElement("div")); + act(() => { + root.render( + , + ); + }); + // Each render registers Continue first, then the feature branch button. + const [continueButton, featureBranchButton] = state.actions.slice(-2); + return { + continueButton: continueButton!, + featureBranchButton: featureBranchButton!, + [Symbol.dispose]() { + act(() => root.unmount()); + }, + }; +} + +it("describes the action it runs on the branch that is checked out", async () => { + using screen = setup("main", { + confirmAction: "commit_push", + branchName: "docs", + includesCommit: "false", + commitMessage: "from the route", + filePaths: "a.ts,b.ts", + }); + expect(state.intro).toMatchObject({ + title: "Commit & push to default branch?", + description: expect.stringContaining('commit and push changes on "main"'), + }); + expect(screen.continueButton.label).toBe("Commit & push to main"); + await act(async () => screen.continueButton.onPress()); + await act(async () => screen.featureBranchButton.onPress()); + expect(state.ran).toEqual([ + { action: "commit_push" }, + { action: "commit_push", featureBranch: true }, + ]); +}); + +it.each([ + ["an action it does not confirm", "main", "commit"], + ["no checked out branch", null, "push"], +])("runs nothing for %s", async (_case, refName, confirmAction) => { + using screen = setup(refName, { confirmAction }); + expect(screen.continueButton.disabled).toBe(true); + expect(screen.featureBranchButton.disabled).toBe(true); + await act(async () => screen.continueButton.onPress()); + await act(async () => screen.featureBranchButton.onPress()); + expect(state.ran).toEqual([]); +}); diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index 1da0ec450a572..32a6fcbe22c2a 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -1,4 +1,7 @@ -import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime/state/vcs"; +import { + resolveDefaultBranchActionDialogCopy, + type DefaultBranchConfirmableAction, +} from "@t3tools/client-runtime/state/vcs"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; @@ -13,6 +16,7 @@ import { FitSheet } from "../../../components/ui/FitSheet"; import { SheetIntro } from "../../../components/ui/SheetIntro"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; +import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useEnvironmentQuery } from "../../../state/query"; import { @@ -28,13 +32,16 @@ type GitConfirmSheetProps = StaticScreenProps< readonly environmentId: string; readonly threadId: string; readonly confirmAction?: string; - readonly branchName?: string; - readonly includesCommit?: string; - readonly commitMessage?: string; - readonly filePaths?: string; } & GitRepositoryRouteParams >; +const CONFIRMABLE_ACTIONS: ReadonlyArray = [ + "push", + "create_pr", + "commit_push", + "commit_push_pr", +]; + export function GitConfirmSheet(props: GitConfirmSheetProps) { const gt = useGT(); const messages = useMessages(); @@ -45,37 +52,35 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const gitActions = useSelectedThreadGitActions(repository); const { canWriteSourceControl, canCreateFeatureBranch } = gitActions; const { selectedThread, selectedThreadProject } = useThreadSelection(); - // The overview that opened this sheet already holds the repository's status subscription. - const repositoryStatus = useEnvironmentQuery( - repository !== undefined && selectedThread !== null + const threadWorktree = useSelectedThreadWorktree(); + const selectedThreadCwd = repository?.cwd ?? threadWorktree.selectedThreadCwd; + // The Git controls that opened this sheet already hold the checkout's status subscription. + const gitStatus = useEnvironmentQuery( + selectedThread !== null && selectedThreadCwd !== null ? vcsEnvironment.status({ environmentId: selectedThread.environmentId, - input: { cwd: repository.cwd }, + input: { cwd: selectedThreadCwd }, }) : null, ); const terminology = sourceControlClients.get( repository === undefined ? selectedThreadProject?.repositoryIdentity?.provider - : repositoryStatus.data?.sourceControlProvider?.kind, + : gitStatus.data?.sourceControlProvider?.kind, ).changeRequest; const params = props.route.params; - const confirmAction = params.confirmAction as - | "push" - | "create_pr" - | "commit_push" - | "commit_push_pr" - | undefined; - const branchName = params.branchName ?? ""; - const includesCommit = params.includesCommit === "true"; + // The route only names the action; what the sheet says about it comes from the checkout. + const confirmAction = CONFIRMABLE_ACTIONS.find((action) => action === params.confirmAction); + const branchName = gitStatus.data?.refName ?? null; + const includesCommit = confirmAction === "commit_push" || confirmAction === "commit_push_pr"; const environmentId = params.environmentId ?? ""; const threadId = params.threadId ?? ""; const copy = useMemo( () => - confirmAction + confirmAction && branchName ? resolveDefaultBranchActionDialogCopy( { action: confirmAction, @@ -90,26 +95,17 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { ); const continuePendingAction = async () => { - if (!canWriteSourceControl || !confirmAction) return; + if (!canWriteSourceControl || !confirmAction || !copy) return; returnToThread({ environmentId, threadId }); - await gitActions.onRunSelectedThreadGitAction({ - action: confirmAction, - ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), - ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), - }); + await gitActions.onRunSelectedThreadGitAction({ action: confirmAction }); }; const movePendingActionToFeatureBranch = useCallback(async () => { - if (!canCreateFeatureBranch || !confirmAction) return; + if (!canCreateFeatureBranch || !confirmAction || !copy) return; returnToThread({ environmentId, threadId }); if (includesCommit) { - await gitActions.onRunSelectedThreadGitAction({ - action: confirmAction, - featureBranch: true, - ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), - ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), - }); + await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, featureBranch: true }); return; } @@ -129,10 +125,10 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { }, [ canCreateFeatureBranch, confirmAction, + copy, gitActions, gitState.selectedThreadBranches, includesCommit, - params, returnToThread, environmentId, threadId, @@ -153,13 +149,13 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { void continuePendingAction()} /> void movePendingActionToFeatureBranch()} /> diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index 0ab21904489e1..4c7225f5cbb4d 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -247,10 +247,6 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) { threadId: String(threadId), ...repositoryParams, confirmAction: confirmableAction, - branchName, - includesCommit: String( - input.action === "commit_push" || input.action === "commit_push_pr", - ), }), ); return; diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 436cea63f4f28..584ac4ae67968 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -8,6 +8,7 @@ const reactTests = [ "src/features/threads/ThreadGuestShareSheet.test.tsx", "src/features/threads/useSubmitAfterNativeImages.test.tsx", "src/features/threads/git/GitBranchesSheet.test.tsx", + "src/features/threads/git/GitConfirmSheet.test.tsx", "src/features/threads/new-task-flow-provider.test.tsx", "src/features/threads/NewTaskRouteScreen.test.tsx", "src/features/layout/workspace/workspace-tabs-state.test.ts", From cc2e4c1704a952df7cebc78d80a4c97a108cffa1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:29:52 -0800 Subject: [PATCH 163/221] fix(server): revoking all other sessions also ends sign-ins still in progress (#41884) Co-authored-by: Claude Fable 5.2 --- apps/server/src/auth/EnvironmentAuth.test.ts | 44 ++++ apps/server/src/auth/EnvironmentAuth.ts | 210 ++++++++++++------- apps/server/src/auth/McpOAuth.test.ts | 38 ++++ apps/server/src/auth/McpOAuth.ts | 21 +- 4 files changed, 226 insertions(+), 87 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 6eceb824a8cba..352ca586783d2 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -17,6 +17,7 @@ import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import * as PairingGrantStore from "./PairingGrantStore.ts"; import * as ServerSecretStore from "./ServerSecretStore.ts"; import * as SessionStore from "./SessionStore.ts"; @@ -916,6 +917,49 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( ), ); + it.effect("issues no session to an exchange that revoking all others overtook", () => + Effect.gen(function* () { + const pairingLinks = yield* PairingGrantStore.PairingGrantStore; + let afterSpend: Effect.Effect = Effect.void; + const serverAuth = yield* EnvironmentAuth.make.pipe( + Effect.provideService(PairingGrantStore.PairingGrantStore, { + ...pairingLinks, + consume: (credential, input) => + pairingLinks.consume(credential, input).pipe(Effect.tap(() => afterSpend)), + }), + Effect.provide( + Layer.merge( + ManagedPolicy.layerTest(), + ServerSecretStore.layer.pipe(Layer.provideMerge(layerServerConfig())), + ), + ), + ); + const owner = yield* serverAuth.issueSession(); + const succeeded = { onFailure: () => false, onSuccess: () => true }; + const exchanges = [ + (credential: string) => + serverAuth + .createBrowserSession(credential, requestMetadata) + .pipe(Effect.match(succeeded)), + (credential: string) => + serverAuth + .exchangeBootstrapCredentialForAccessToken(credential, undefined, requestMetadata) + .pipe(Effect.match(succeeded)), + ]; + for (const exchange of exchanges) { + const pairing = yield* serverAuth.issuePairingCredential(); + afterSpend = serverAuth.revokeOtherClientSessions(owner.sessionId).pipe(Effect.orDie); + const exchanged = yield* exchange(pairing.credential); + afterSpend = Effect.void; + + expect(exchanged).toBe(false); + expect((yield* serverAuth.listSessions()).map((session) => session.sessionId)).toEqual([ + owner.sessionId, + ]); + } + }).pipe(Effect.provide(layerEnvironmentAuth())), + ); + it.effect("accepts cookie sessions on socket upgrades only from the app's own origins", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 977840617d04c..46e207dcf8ead 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -35,6 +35,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; @@ -639,18 +640,25 @@ export class EnvironmentAuth extends Context.Service< readonly revokeMcpClientToken: ( token: string, ) => Effect.Effect; + /** How many times "revoke all others" has run since this server started. */ + readonly otherSessionRevocationCount: Effect.Effect; readonly issueMcpClientSession: (input: { readonly label: string; readonly access: AuthMcpClientAccess; readonly peerLink: boolean; readonly client: AuthClientMetadata; + /** + * `otherSessionRevocationCount` read before the sign-in was approved. The session is + * refused when "revoke all others" has run since. + */ + readonly approvedAtRevocationCount?: number; }) => Effect.Effect< { readonly sessionId: AuthSessionId; readonly token: string; readonly expiresAt: DateTime.DateTime; }, - ServerAuthInternalError + ServerAuthInvalidCredentialError | ServerAuthInternalError >; /** * Spends a code covering all granted scopes and returns the level it approves. A level-bound @@ -940,6 +948,28 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.getSessionState"), ); + // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints + // at once would open two requests with one code, and a revoke landing between an exchange + // spending its credential and trusting the key would be undone by that exchange. + const connectTrustLock = yield* Semaphore.make(1); + + // Counts "revoke all others" runs. An exchange or sign-in approval that began before a run + // issues its session here, under the lock the run holds, so it cannot leave a session behind. + const otherSessionRevocations = yield* Ref.make(0); + const issueUnlessOthersRevokedSince = (since: number, issue: Effect.Effect) => + Ref.get(otherSessionRevocations).pipe( + Effect.flatMap((count): Effect.Effect => + count === since + ? issue + : Effect.fail( + new ServerAuthInvalidCredentialError({ + diagnostic: "All other sessions were revoked before this one was issued.", + }), + ), + ), + connectTrustLock.withPermits(1), + ); + const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = Effect.fn( "EnvironmentAuth.createBrowserSession", )(function* (credential, requestMetadata, previousSessionToken) { @@ -967,6 +997,7 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.createBrowserSession"), ); } + const revocationsAtStart = yield* Ref.get(otherSessionRevocations); const previousSession = previousSessionToken === undefined ? undefined @@ -977,20 +1008,23 @@ export const make = Effect.gen(function* () { const grant = yield* bootstrapCredentials .consume(credential) .pipe(Effect.mapError(toBootstrapExchangeError)); - const session = yield* sessions - .issue({ - method: "browser-session-cookie", - subject: grant.subject, - scopes: grant.scopes, - ...(previousSession?.method === "browser-session-cookie" - ? { replaceSessionId: previousSession.sessionId } - : {}), - client: { - ...requestMetadata, - ...(grant.label ? { label: grant.label } : {}), - }, - }) - .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))); + const session = yield* issueUnlessOthersRevokedSince( + revocationsAtStart, + sessions + .issue({ + method: "browser-session-cookie", + subject: grant.subject, + scopes: grant.scopes, + ...(previousSession?.method === "browser-session-cookie" + ? { replaceSessionId: previousSession.sessionId } + : {}), + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))), + ); return { response: { authenticated: true, @@ -1062,11 +1096,6 @@ export const make = Effect.gen(function* () { ); }; - // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints - // at once would open two requests with one code, and a revoke landing between an exchange - // spending its credential and trusting the key would be undone by that exchange. - const connectTrustLock = yield* Semaphore.make(1); - const toAccessTokenResult = (session: SessionStore.IssuedSession) => DateTime.now.pipe( Effect.map( @@ -1106,63 +1135,71 @@ export const make = Effect.gen(function* () { const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] = (credential, requestedScopes, requestMetadata, input) => { - return resolveBootstrapGrant(credential, { - ...input, - requestMetadata, - ...(requestedScopes !== undefined ? { requestedScopes } : {}), - }).pipe( - // Every T3 Connect key that gets in is remembered, so turning approval on later - // keeps the devices already in use and lists them for review. - Effect.tap((grant) => - grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint - ? bootstrapCredentials - .trustConnectDevice(input.proofKeyThumbprint, requestMetadata) - .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))) - : Effect.void, - ), - Effect.flatMap((grant) => - Effect.gen(function* () { - const grantedScopes = - requestedScopes === undefined - ? grant.scopes - : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope)); - if (grantedScopes.length === 0) { - return yield* new ServerAuthScopeNotGrantedError({}); - } - // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep - // their own lifetimes, so unlinking Connect or rotating a credential still cuts off. - const renewable = - input?.proofKeyThumbprint !== undefined && - grant.method === "one-time-token" && - grant.subject === PAIRING_LINK_SUBJECT; - return yield* sessions - .issue({ - method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", - subject: grant.subject, - scopes: grantedScopes, - ...(input?.proofKeyThumbprint - ? { - proofKeyThumbprint: input.proofKeyThumbprint, - ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), - } - : {}), - ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), - replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", - client: { - ...requestMetadata, - ...(grant.label ? { label: grant.label } : {}), - }, - }) - .pipe( - Effect.mapError( - (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }), - ), - ); - }), - ), - Effect.flatMap(toAccessTokenResult), - (exchange) => - input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange, + const exchangeSince = (revocationsAtStart: number) => + resolveBootstrapGrant(credential, { + ...input, + requestMetadata, + ...(requestedScopes !== undefined ? { requestedScopes } : {}), + }).pipe( + // Every T3 Connect key that gets in is remembered, so turning approval on later + // keeps the devices already in use and lists them for review. + Effect.tap((grant) => + grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint + ? bootstrapCredentials + .trustConnectDevice(input.proofKeyThumbprint, requestMetadata) + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))) + : Effect.void, + ), + Effect.flatMap((grant) => + Effect.gen(function* () { + const grantedScopes = + requestedScopes === undefined + ? grant.scopes + : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope)); + if (grantedScopes.length === 0) { + return yield* new ServerAuthScopeNotGrantedError({}); + } + // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep + // their own lifetimes, so unlinking Connect or rotating a credential still cuts off. + const renewable = + input?.proofKeyThumbprint !== undefined && + grant.method === "one-time-token" && + grant.subject === PAIRING_LINK_SUBJECT; + const issue = sessions + .issue({ + method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", + subject: grant.subject, + scopes: grantedScopes, + ...(input?.proofKeyThumbprint + ? { + proofKeyThumbprint: input.proofKeyThumbprint, + ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), + } + : {}), + ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), + replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe( + Effect.mapError( + (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }), + ), + ); + // A proof-key exchange holds the lock from before it spends its credential. + return yield* input?.proofKeyThumbprint + ? issue + : issueUnlessOthersRevokedSince(revocationsAtStart, issue); + }), + ), + Effect.flatMap(toAccessTokenResult), + (exchange) => + input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange, + ); + return Ref.get(otherSessionRevocations).pipe( + Effect.flatMap(exchangeSince), Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"), ); }; @@ -1486,7 +1523,12 @@ export const make = Effect.gen(function* () { .revokeConnectDevicesExcept(Option.getOrNull(currentProofKey)) .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))); return yield* revokeOtherSessionsExcept(currentSessionId); - }).pipe(connectTrustLock.withPermits(1)); + }).pipe( + // Counted last, after unspent links and session rows are gone, so whatever reads the + // new count can no longer use either. + Effect.ensuring(Ref.update(otherSessionRevocations, (count) => count + 1)), + connectTrustLock.withPermits(1), + ); }); const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) => @@ -1659,8 +1701,8 @@ export const make = Effect.gen(function* () { return yield* revokeSession(session.value.sessionId); }); - const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => - sessions + const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => { + const issue = sessions .issue({ subject: MCP_CLIENT_SUBJECT, method: "bearer-access-token", @@ -1677,8 +1719,13 @@ export const make = Effect.gen(function* () { expiresAt: issued.expiresAt, })), Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })), - Effect.withSpan("EnvironmentAuth.issueMcpClientSession"), ); + return ( + input.approvedAtRevocationCount === undefined + ? issue + : issueUnlessOthersRevokedSince(input.approvedAtRevocationCount, issue) + ).pipe(Effect.withSpan("EnvironmentAuth.issueMcpClientSession")); + }; const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = ( code, @@ -1742,6 +1789,7 @@ export const make = Effect.gen(function* () { issueStartupPairingUrl, authenticateMcpClient, revokeMcpClientToken, + otherSessionRevocationCount: Ref.get(otherSessionRevocations), issueMcpClientSession, consumeMcpApprovalCode, }); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index c21b707bad889..ea321bcf0241c 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -538,6 +538,44 @@ it.live("signs in Gemini, which registers six user-bound redirect URIs for one c ), ); +it.live("issues no session for a sign-in approved before all other sessions were revoked", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const clientId = yield* registeredClientId(handler); + const params = authorizeParams(clientId); + const approved = yield* decide(handler, params, { + _tag: "pairing-code", + access: "approval-required", + code: (yield* auth.issuePairingCredential()).credential, + }); + const code = new URL(approved.redirectTo!).searchParams.get("code")!; + const owner = yield* auth.issueSession(); + yield* auth.revokeOtherClientSessions(owner.sessionId); + + const response = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code, + redirect_uri: params.redirect_uri, + client_id: clientId, + code_verifier: verifier, + }), + ), + ); + expect(response.status).toBe(400); + expect(yield* json(response)).toEqual({ + error: "invalid_grant", + error_description: "The authorization code is invalid or expired.", + }); + expect((yield* auth.listSessions()).map((session) => session.sessionId)).toEqual([ + owner.sessionId, + ]); + }), + ), +); + it.live("rejects a wrong PKCE verifier and spends the code", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index e63c600ae1b2d..7c6cdc677cc3c 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -197,6 +197,7 @@ interface PendingCode { readonly codeChallenge: string; readonly resource: string; readonly access: AuthMcpClientAccess; + readonly approvedAtRevocationCount: number; readonly expiresAtMs: number; } @@ -445,6 +446,7 @@ const make = Effect.gen(function* () { const mintCode = Effect.fn("McpOAuth.mintCode")(function* ( authorization: AuthorizationRequest, access: AuthMcpClientAccess, + approvedAtRevocationCount: number, ) { const now = yield* Clock.currentTimeMillis; const code = Buffer.from(yield* random.randomBytes(32)).toString("base64url"); @@ -458,6 +460,7 @@ const make = Effect.gen(function* () { codeChallenge: authorization.codeChallenge, resource: authorization.resource, access, + approvedAtRevocationCount, expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS, }); return next; @@ -467,6 +470,9 @@ const make = Effect.gen(function* () { const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) { const { decision } = input; + // Read before the approver is checked: "revoke all others" then ends this sign-in whether + // it lands before the check or after the code is handed out. + const approvedAtRevocationCount = yield* environmentAuth.otherSessionRevocationCount; let access = decision.access; if (decision._tag === "pairing-code") { // An approval code is for one app's sign-in, never for linking another environment. @@ -502,7 +508,7 @@ const make = Effect.gen(function* () { }); } } - const code = yield* mintCode(input.authorization, access); + const code = yield* mintCode(input.authorization, access, approvedAtRevocationCount); yield* Effect.logInfo("Approved an MCP client sign-in.", { client: input.authorization.client.name, access, @@ -567,14 +573,17 @@ const make = Effect.gen(function* () { access: pending.access, peerLink: pending.peerLink, client: deriveAuthClientMetadata({ request }), + approvedAtRevocationCount: pending.approvedAtRevocationCount, }) .pipe( Effect.catch((cause) => - Effect.logError("Could not issue an MCP client session.", { cause }).pipe( - Effect.andThen( - Effect.fail(fail("invalid_grant", "The session could not be issued.")), - ), - ), + cause._tag === "ServerAuthInvalidCredentialError" + ? Effect.fail(fail("invalid_grant", "The authorization code is invalid or expired.")) + : Effect.logError("Could not issue an MCP client session.", { cause }).pipe( + Effect.andThen( + Effect.fail(fail("invalid_grant", "The session could not be issued.")), + ), + ), ), ); return { From 8dc01892ad452038cd856e7d2447715ce23f286c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:31:37 -0800 Subject: [PATCH 164/221] fix(server): answering a secret request with a reference needs provider management (#41886) Co-authored-by: Claude Fable 5.2 --- .../features/threads/SecretRequestCard.tsx | 19 +++--- apps/server/src/auth/RpcAuthorization.test.ts | 61 +++++++++++++++++++ apps/server/src/auth/RpcAuthorization.ts | 10 +++ .../src/components/chat/SecretRequestCard.tsx | 14 +++-- docs/internals/04_environment-auth.md | 4 ++ docs/user/secrets.md | 3 +- 6 files changed, 98 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/features/threads/SecretRequestCard.tsx b/apps/mobile/src/features/threads/SecretRequestCard.tsx index e52fae8ce659f..24b0a1aa81d67 100644 --- a/apps/mobile/src/features/threads/SecretRequestCard.tsx +++ b/apps/mobile/src/features/threads/SecretRequestCard.tsx @@ -16,10 +16,11 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { - EnvironmentId, - OrchestrationV2ProjectedTurnItem, - SecretProviderId, +import { + AuthProvidersManageScope, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { useGT, useMessages } from "gt-react-native"; @@ -31,6 +32,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/ import { SecretTextInput } from "../../components/ui/SecretTextInput"; import type { SecretTextInputHandle } from "../../components/ui/SecretTextInput.types"; import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { Button } from "../../components/ui/Button"; @@ -91,10 +93,13 @@ function PendingSecretRequestForm(props: { const inputs = secretRequestInputs(item, m); const multiple = item.fields !== undefined; const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); + // The server accepts a reference answer only with this scope; without it the card is typed. + const canUseReferences = useEnvironmentScope(props.environmentId, AuthProvidersManageScope); // A reference answers one value, so a card with fields is always typed. - const sources = multiple - ? NO_SOURCES - : secretRequestSources(config, config?.settings.secretProviders ?? {}, m); + const sources = + multiple || !canUseReferences + ? NO_SOURCES + : secretRequestSources(config, config?.settings.secretProviders ?? {}, m); const [sourceId, setSourceId] = useState(null); const source = sources.find((candidate) => candidate.id === sourceId) ?? null; const [values, setValues] = useState>>({}); diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 15ddfb90b08a5..1aa2a5b182ffa 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -657,6 +657,67 @@ describe("settings mutation authorization", () => { ); }); +it.effect("answering a secret request with a reference needs provider management", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.secretsAnswerRequest + > => tag !== WS_METHODS.secretsAnswerRequest, + ), + ); + const handled: string[] = []; + const handler = group.toLayerHandler(WS_METHODS.secretsAnswerRequest, ({ answer }) => + Effect.sync(() => { + handled.push(answer.type); + }), + ); + const clientWith = (...scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handler, RpcAuthorization.layer(scopes))), + ); + const request = { threadId: ThreadId.make("thread"), turnItemId: TurnItemId.make("item") }; + const reference = { + type: "reference" as const, + reference: { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }, + }; + + const operate = yield* clientWith(AuthOrchestrationOperateScope); + expect( + yield* operate[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthProvidersManageScope }); + expect(handled).toEqual([]); + // Typed values stay with the scope that runs the thread, whatever the fields are called. + yield* operate[WS_METHODS.secretsAnswerRequest]({ + ...request, + answer: { type: "save", secret: "typed-value" }, + }); + yield* operate[WS_METHODS.secretsAnswerRequest]({ + ...request, + answer: { type: "save", values: { provider: "personal", reference: "typed-value" } }, + }); + expect(handled).toEqual(["save", "save"]); + + const manage = yield* clientWith(AuthOrchestrationOperateScope, AuthProvidersManageScope); + yield* manage[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }); + expect(handled).toEqual(["save", "save", "reference"]); + const manageOnly = yield* clientWith(AuthProvidersManageScope); + expect( + yield* manageOnly[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope }); + }), +); + it.effect("requires task permission before attaching a prepared worktree to a thread", () => Effect.gen(function* () { const group = WsRpcGroup.omit( diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index b276fafb2723a..f6dda3ad4d8f8 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -11,6 +11,7 @@ import { requiredScopesForServerSettingsPatch, requiredScopesForProjectMutation, ProjectMutation, + SecretRequestAnswerInput, AuthSettingsWriteScope, AuthProvidersManageScope, AuthEnvironmentMaintainScope, @@ -283,6 +284,7 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => { const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation); const decodeAssetCreateUrlInput = Schema.decodeUnknownSync(AssetCreateUrlInput); +const decodeSecretRequestAnswer = Schema.decodeUnknownSync(SecretRequestAnswerInput); /** * A queued edit that omits `attachments` keeps the queued ones, which a payload cannot show; @@ -338,6 +340,14 @@ const requiredScopesForRpcCall = ( ) { return [AuthSettingsWriteScope, AuthProvidersManageScope]; } + // A reference answer has the server read a secret the caller names, as a saved reference does. + // Typed values can use any field names, so the answer's type decides, not its shape. + if ( + method === WS_METHODS.secretsAnswerRequest && + decodeSecretRequestAnswer(payload).answer.type === "reference" + ) { + return [AuthOrchestrationOperateScope, AuthProvidersManageScope]; + } if (method === WS_METHODS.projectsMutate) { return requiredScopesForProjectMutation(decodeProjectMutation(payload)); } diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index 25c1fe59d5e6b..49dff6b6a1c16 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -18,10 +18,11 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { - EnvironmentId, - OrchestrationV2ProjectedTurnItem, - SecretProviderId, +import { + AuthProvidersManageScope, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; @@ -38,6 +39,7 @@ import { import { useId, useRef, useState, type FormEvent } from "react"; import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -80,7 +82,9 @@ const NO_SOURCES: ReadonlyArray = []; function useSecretRequestSources(environmentId: EnvironmentId) { const config = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const messages = useMessages(); - return hasFeatureFlag(config, "secretProviders") + // The server accepts a reference answer only with this scope; without it the card is typed. + const canUseReferences = useEnvironmentScope(environmentId, AuthProvidersManageScope); + return canUseReferences && hasFeatureFlag(config, "secretProviders") ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages) : NO_SOURCES; } diff --git a/docs/internals/04_environment-auth.md b/docs/internals/04_environment-auth.md index 8b80c65860d60..1b22ab16e4d6d 100644 --- a/docs/internals/04_environment-auth.md +++ b/docs/internals/04_environment-auth.md @@ -29,6 +29,10 @@ model. over authenticated HTTP so long-lived tokens never appear in socket URLs. DPoP RPC tickets stay proof-key bound at upgrade. A successful handshake grants no extra authority: every RPC declares and checks its required scope in [`RpcAuthorization.ts`](../../apps/server/src/auth/RpcAuthorization.ts). +- **Secret references need `providers:manage`.** A request that names a secret for the server to + read needs `providers:manage` on top of its method's scope, whether the reference is saved in + settings or used once, as in a secret request answered with a reference. Typed values need only + the method's scope. Clients hide the secret provider picker from sessions without it. - **Backward-compatible scope evolution.** Token exchange intersects requested scopes with the pairing grant, dropping retired/unknown names and failing before consuming a link if none remain. Stored grants are never expanded when scopes split. Auth responses preserve legacy `scopes` diff --git a/docs/user/secrets.md b/docs/user/secrets.md index e7e899f197aeb..4f2a4b0de138c 100644 --- a/docs/user/secrets.md +++ b/docs/user/secrets.md @@ -55,7 +55,8 @@ you to paste it into the chat. Type or paste the value and select **Save securel **Decline**. You can answer from web, desktop, or mobile. If the environment has a secret provider, the card also lets you pick it and enter a reference -instead of the value. T3 Code reads the secret once, when you answer. If 1Password is locked, the +instead of the value. Answering with a reference needs permission to manage providers, as saving a +reference in Settings does; a session without it sees only the value field. T3 Code reads the secret once, when you answer. If 1Password is locked, the card says so and the request stays open: unlock it and try again, or enter the value. The value never appears in the conversation. Most requests keep it from the agent too: T3 Code From f133ec7cac2903596454421ba29673930ad430e0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 19:33:10 -0800 Subject: [PATCH 165/221] perf(scripts): the soak drives forge polling and thread churn, and names what grew (#41831) Co-authored-by: Claude Opus 5.5 --- docs/internals/16_performance-regressions.md | 3 +- scripts/server-metrics-forge.ts | 614 +++++++++++++++++++ scripts/server-metrics-report.ts | 267 +++++++- scripts/server-metrics.test.ts | 83 +++ scripts/server-metrics.ts | 244 ++++++-- 5 files changed, 1160 insertions(+), 51 deletions(-) create mode 100644 scripts/server-metrics-forge.ts diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index 863ccc0c7b697..1319174766471 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -36,7 +36,8 @@ heap, and first-request latency against a fake Anthropic API and the real `claud - Always compare refs with `ab ` on the same machine rather than comparing isolated runs. - Use `scaling` to separate per-thread cost from fixed server overhead, and `--soak ` to - spot rising heap slopes (leaks). + spot rising heap slopes (leaks). A leak only shows in code the soak drives, so give a new + subsystem with long-lived state a part in its workload. - Steer server work by `working`: many worktree threads editing files at once with one client subscribed to all of them. Turns per minute that stay flat as threads are added mean the server, not the agents, is the bottleneck. diff --git a/scripts/server-metrics-forge.ts b/scripts/server-metrics-forge.ts new file mode 100644 index 0000000000000..1422bc25f6436 --- /dev/null +++ b/scripts/server-metrics-forge.ts @@ -0,0 +1,614 @@ +// A fake GitHub Enterprise host for the server-metrics soak: the GitHub API the server polls for a +// web client, and a git remote it fetches from, both over HTTPS on loopback. +// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http2 server; the proxy is raw. +import * as NodeHttp from "node:http"; +import * as NodeHttp2 from "node:http2"; +import * as NodeNet from "node:net"; + +import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type { + PullRequestListInput, + PullRequestListResult, + PullRequestRef, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Console from "effect/Console"; +import * as Duration from "effect/Duration"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; + +import { run, ScenarioError } from "./scenarios/shell.ts"; + +const OWNER = "bench"; +const REPO = "project"; +const TOKEN = "ghp_bench_fake"; +/** + * The host the project's origin names. It carries no port because pull request listings key a + * GitHub host without one, so the server reaches it on 443 through a proxy that tunnels it here. + */ +const HOST = "bench.test"; + +export interface ForgeRequest { + readonly at: number; + readonly method: string; + readonly path: string; + /** The GraphQL operation name, for GraphQL requests. */ + readonly operation: string | undefined; + readonly status: number; +} + +const GraphQlRequest = Schema.Struct({ + query: Schema.optional(Schema.String), + operationName: Schema.optional(Schema.NullOr(Schema.String)), + variables: Schema.optional(Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown))), +}); +const decodeGraphQl = Schema.decodeUnknownEffect(Schema.fromJsonString(GraphQlRequest)); + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +/** FNV-1a, enough to tell bodies apart. */ +const hash = (text: string) => { + let value = 0x811c9dc5; + for (let index = 0; index < text.length; index++) { + value = Math.imul(value ^ text.charCodeAt(index), 0x01000193) >>> 0; + } + return value.toString(16); +}; + +interface Failure { + readonly message: string; +} + +interface FakePullRequest { + readonly number: number; + readonly head: string; + oid: string; +} + +/** Serves the fake host until the scope closes. */ +export const serveFakeGitHub = Effect.fn("serverMetrics.serveFakeGitHub")(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-forge-" }); + const keyFile = path.join(dir, "key.pem"); + const certFile = path.join(dir, "cert.pem"); + yield* run("openssl", [ + "req", + "-x509", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:prime256v1", + "-nodes", + "-days", + "2", + "-subj", + `/CN=${HOST}`, + "-addext", + `subjectAltName=DNS:${HOST}`, + "-keyout", + keyFile, + "-out", + certFile, + ]); + const bare = path.join(dir, `${REPO}.git`); + yield* run("git", ["init", "-q", "--bare", bare]); + const requests: ForgeRequest[] = []; + const host = HOST; + const pullRequests: Array = [ + { number: 1, head: "bench/feature", oid: "0".repeat(40) }, + ...[2, 3, 4, 5].map((number) => ({ + number, + head: `bench/other-${number}`, + oid: "0".repeat(40), + })), + ]; + + const actor = { __typename: "User", id: "U_bench", login: OWNER, name: "Bench", avatarUrl: "" }; + /** Every field any of the polled reads selects; decoders ignore the ones a read did not ask for. */ + const pullRequestNode = (pr: FakePullRequest, now: number) => { + const minute = Math.floor(now / 60_000); + const at = (offsetMinutes: number) => + DateTime.formatIso(DateTime.makeUnsafe((minute - offsetMinutes) * 60_000)); + // The branch PR's CI reruns every other minute, so checks and their rollup keep changing. + const running = pr.number === 1 && minute % 2 === 0; + return { + __typename: "PullRequest", + id: `PR_bench_${pr.number}`, + number: pr.number, + title: `Bench change ${pr.number}`, + url: `https://${host}/${OWNER}/${REPO}/pull/${pr.number}`, + body: "A pull request the soak polls.", + baseRefName: "main", + headRefName: pr.head, + headRefOid: pr.oid, + state: "OPEN", + isDraft: false, + mergeable: "MERGEABLE", + mergeStateStatus: running ? "BLOCKED" : "CLEAN", + reviewDecision: null, + additions: 1, + deletions: 0, + changedFiles: 1, + createdAt: at(600 + pr.number), + updatedAt: at(0), + mergedAt: null, + mergeCommit: null, + mergedBy: null, + closedAt: null, + isCrossRepository: false, + maintainerCanModify: false, + headRepository: { name: REPO, nameWithOwner: `${OWNER}/${REPO}`, viewerPermission: "ADMIN" }, + headRepositoryOwner: { __typename: "User", login: OWNER }, + headRef: { id: `REF_bench_${pr.number}` }, + repository: { nameWithOwner: `${OWNER}/${REPO}` }, + author: actor, + autoMergeRequest: null, + viewerCanUpdate: true, + viewerDidAuthor: true, + viewerCanUpdateBranch: false, + baseRef: { compare: { behindBy: 0 } }, + reviewRequests: { nodes: [] }, + latestReviews: { nodes: [] }, + labels: { nodes: [] }, + commits: { + nodes: [ + { + commit: { + statusCheckRollup: { + state: running ? "PENDING" : "SUCCESS", + contexts: { + nodes: [ + { + __typename: "CheckRun", + name: "test", + status: running ? "IN_PROGRESS" : "COMPLETED", + conclusion: running ? null : "SUCCESS", + startedAt: at(1), + completedAt: running ? null : at(0), + detailsUrl: `https://${host}/${OWNER}/${REPO}/actions/runs/${minute}`, + checkSuite: { + workflowRun: { + event: "pull_request", + runNumber: minute, + workflow: { id: "W_bench", name: "CI" }, + }, + }, + }, + { + __typename: "StatusContext", + context: "lint", + state: "SUCCESS", + targetUrl: null, + createdAt: at(5), + description: "Lint passed", + }, + ], + pageInfo: { hasNextPage: false, endCursor: null }, + }, + }, + }, + }, + ], + }, + }; + }; + const repositorySettings = { + mergeCommitAllowed: true, + squashMergeAllowed: true, + rebaseMergeAllowed: true, + autoMergeAllowed: false, + viewerPermission: "ADMIN", + }; + const page = (nodes: ReadonlyArray) => ({ + pageInfo: { hasNextPage: false, endCursor: null }, + nodes, + }); + + /** The `data` of a GraphQL answer, each aliased slice (`_0_repository`) answered on its own. */ + const answer = ( + operation: string, + variables: Readonly>, + now: number, + ): Record | undefined => { + const prefixes = new Set( + Object.keys(variables).map((name) => /^(_\d+_)?/.exec(name)?.[1] ?? ""), + ); + if (prefixes.size === 0) prefixes.add(""); + const data: Record = {}; + for (const prefix of prefixes) { + const variable = (name: string) => variables[`${prefix}${name}`]; + const byNumber = pullRequests.find((pr) => pr.number === variable("number")); + const single = byNumber === undefined ? null : pullRequestNode(byNumber, now); + const all = pullRequests.map((pr) => pullRequestNode(pr, now)); + switch (operation) { + case "PullRequestsByHead": + case "PullRequestHeads": + data[`${prefix}repository`] = { + pullRequests: page(all.filter((pr) => pr.headRefName === variable("head"))), + }; + break; + case "PullRequestList": + data[`${prefix}repository`] = { pullRequests: page(all) }; + break; + case "PullRequestSearch": + data[`${prefix}search`] = page(all); + break; + case "PullRequestByNumber": + case "PullRequestSummary": + case "PullRequestStats": + case "PullRequestCheckContexts": + data[`${prefix}repository`] = { pullRequest: single }; + break; + case "PullRequestCore": + data[`${prefix}repository`] = { ...repositorySettings, pullRequest: single }; + break; + case "RoutingIdentityViewer": + data[`${prefix}viewer`] = { databaseId: 1, login: OWNER }; + break; + case "ActorAvatars": { + const ids = variable("ids"); + data[`${prefix}nodes`] = (Array.isArray(ids) ? ids : []).map(() => actor); + break; + } + default: + return undefined; + } + } + return data; + }; + + /** REST answers by path under /api/v3; the body moves each minute where real polling sees change. */ + const restAnswer = (path: string, now: number): unknown => { + const minute = Math.floor(now / 60_000); + const repository = `repos/${OWNER}/${REPO}`; + if (path === "user") + return { login: OWNER, id: 1, name: "Bench", avatar_url: "", type: "User" }; + if (path === repository) { + return { + id: 1, + node_id: "R_bench", + name: REPO, + full_name: `${OWNER}/${REPO}`, + private: false, + default_branch: "main", + html_url: `https://${host}/${OWNER}/${REPO}`, + owner: { login: OWNER, id: 1, type: "User" }, + permissions: { admin: true, maintain: true, push: true, triage: true, pull: true }, + }; + } + if (path === `${repository}/actions/runs`) { + return { + total_count: minute % 2 === 0 ? 1 : 0, + workflow_runs: + minute % 2 === 0 + ? [ + { + id: minute, + name: "CI", + html_url: `https://${host}/${OWNER}/${REPO}/actions/runs/${minute}`, + status: "in_progress", + }, + ] + : [], + }; + } + return undefined; + }; + + const serveGit = Effect.fn("serverMetrics.fakeGitHub.git")(function* (relative: string) { + if (relative.split("/").includes("..")) return HttpServerResponse.empty({ status: 404 }); + const file = path.join(bare, relative); + const body = yield* fs.readFile(file).pipe(Effect.option); + return body._tag === "Some" + ? HttpServerResponse.uint8Array(body.value, { contentType: "application/octet-stream" }) + : HttpServerResponse.empty({ status: 404 }); + }); + + const app = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = new URL(request.url, "https://127.0.0.1"); + const gitPrefix = `/${OWNER}/${REPO}.git/`; + let operation: string | undefined; + let response: HttpServerResponse.HttpServerResponse; + if (url.pathname.startsWith(gitPrefix)) { + // Dumb HTTP: a static info/refs makes git fall back to reading the bare repository's files. + response = yield* serveGit(url.pathname.slice(gitPrefix.length)); + } else if (url.pathname === "/api/graphql") { + const raw = yield* request.text; + const body = yield* decodeGraphQl(raw).pipe( + Effect.orElseSucceed((): typeof GraphQlRequest.Type => ({})), + ); + operation = + body.operationName ?? + /\b(?:query|mutation)\s+(\w+)/.exec(body.query ?? "")?.[1] ?? + "anonymous"; + const data = answer(operation, body.variables ?? {}, yield* Clock.currentTimeMillis); + response = + data === undefined + ? HttpServerResponse.jsonUnsafe({ message: "Not Found" }, { status: 404 }) + : HttpServerResponse.jsonUnsafe({ data }); + } else { + const body = url.pathname.startsWith("/api/v3/") + ? restAnswer(url.pathname.slice("/api/v3/".length), yield* Clock.currentTimeMillis) + : undefined; + if (body === undefined) { + response = HttpServerResponse.jsonUnsafe( + { message: "Not Found", documentation_url: "https://docs.github.com/rest" }, + { status: 404 }, + ); + } else { + // A weak validator of the body, so an unchanged answer revalidates as a 304. + const text = encodeJson(body); + const etag = `W/"${text.length.toString(16)}-${hash(text)}"`; + response = + request.headers["if-none-match"] === etag + ? HttpServerResponse.empty({ status: 304, headers: { etag } }) + : HttpServerResponse.text(text, { + contentType: "application/json", + headers: { etag }, + }); + } + } + requests.push({ + at: yield* Clock.currentTimeMillis, + method: request.method, + path: url.pathname + url.search, + operation, + status: response.status, + }); + return response; + }).pipe(Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500 }))); + + const key = yield* fs.readFileString(keyFile); + const cert = yield* fs.readFileString(certFile); + const context = yield* Layer.build( + NodeHttpServer.layer(() => NodeHttp2.createSecureServer({ key, cert, allowHTTP1: true }), { + port: 0, + host: "127.0.0.1", + }), + ); + const port = yield* Effect.gen(function* () { + yield* HttpServer.serveEffect(Effect.interruptible(app)); + const { address } = yield* HttpServer.HttpServer; + return address._tag === "UnixPathAddress" ? 0 : address.port; + }).pipe(Effect.provide(context)); + // Tunnels only the fake host, so nothing the server sends through it reaches the internet. + const tunnels = new Set(); + const proxy = NodeHttp.createServer((_request, response) => { + response.writeHead(405).end(); + }); + proxy.on("connect", (request: NodeHttp.IncomingMessage, client: NodeNet.Socket) => { + if (request.url !== `${HOST}:443`) { + client.end("HTTP/1.1 403 Forbidden\r\n\r\n"); + return; + } + const upstream = NodeNet.connect(port, "127.0.0.1", () => { + client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + upstream.pipe(client); + client.pipe(upstream); + }); + for (const socket of [client, upstream]) { + tunnels.add(socket); + socket.on("close", () => tunnels.delete(socket)); + socket.on("error", () => { + client.destroy(); + upstream.destroy(); + }); + } + }); + const proxyPort = yield* Effect.acquireRelease( + Effect.callback((resume) => { + proxy.once("error", (error) => + resume( + Effect.fail(new ScenarioError({ message: `the fake GitHub proxy: ${error.message}` })), + ), + ); + proxy.listen(0, "127.0.0.1", () => { + const address = proxy.address(); + resume(Effect.succeed(typeof address === "object" && address !== null ? address.port : 0)); + }); + }), + () => + Effect.callback((resume) => { + for (const socket of tunnels) socket.destroy(); + proxy.closeAllConnections(); + proxy.close(() => resume(Effect.void)); + }), + ); + const proxyUrl = `http://127.0.0.1:${proxyPort}`; + + /** Publishes the project to the fake remote and checks out a branch with an open PR. */ + const setupProject = Effect.fn("serverMetrics.fakeGitHub.setupProject")(function* ( + project: string, + ) { + const git = (args: ReadonlyArray) => run("git", args, { cwd: project }); + yield* git(["switch", "-q", "-c", "bench/feature"]); + yield* fs.writeFileString(path.join(project, "FEATURE.md"), "# feature\n"); + yield* git(["add", "."]); + yield* git([ + "-c", + "user.email=bench@t3.codes", + "-c", + "user.name=bench", + "commit", + "-qm", + "feature", + ]); + yield* git(["push", "-q", bare, "main", "bench/feature"]); + yield* run("git", ["--git-dir", bare, "update-server-info"]); + yield* git(["remote", "add", "origin", `https://${host}/${OWNER}/${REPO}.git`]); + yield* git(["config", "http.sslCAInfo", certFile]); + yield* git(["config", "http.proxy", proxyUrl]); + // A developer's NO_PROXY could send this past the proxy, which is the only route to the host. + const hostEnvironment = yield* HostProcess.Environment; + yield* run("git", ["fetch", "-q", "origin"], { + cwd: project, + env: { + ...Object.fromEntries( + Object.entries(hostEnvironment).filter( + (entry): entry is [string, string] => entry[1] !== undefined, + ), + ), + NO_PROXY: "", + no_proxy: "", + GIT_SSL_CAINFO: certFile, + }, + }); + yield* git(["branch", "-q", "--set-upstream-to", "origin/bench/feature"]); + const [feature, main] = (yield* git(["rev-parse", "HEAD", "main"])).stdout.trim().split("\n"); + for (const pr of pullRequests) pr.oid = (pr.number === 1 ? feature : main) ?? pr.oid; + setupRequests = requests.length; + publishedMain = main; + }); + + let pushes = 0; + /** Lands a commit on the remote's main, so the server's next fetch transfers something. */ + const advanceRemote = Effect.gen(function* () { + const git = (args: ReadonlyArray) => run("git", ["--git-dir", bare, ...args]); + const commit = (yield* git([ + "-c", + "user.email=bench@t3.codes", + "-c", + "user.name=bench", + "commit-tree", + "main^{tree}", + "-p", + "main", + "-m", + `upstream ${++pushes}`, + ])).stdout.trim(); + yield* git(["update-ref", "refs/heads/main", commit]); + yield* git(["update-server-info"]); + }); + + /** Requests the project setup made before the server started, which `verify` leaves out. */ + let setupRequests = 0; + let publishedMain: string | undefined; + let fetchedPush = false; + let completedPolls = 0; + const failures: Array = []; + /** + * What a web client with the pull requests sidebar and the branch's PR open asks for: the list, + * then the branch PR's summary and checks, every 30 s until interrupted. Failures are kept, not + * thrown, so one bad answer does not end the soak. + */ + const pollLikeWebClient = Effect.fn("serverMetrics.fakeGitHub.poll")(function* (rpc: { + readonly list: (input: PullRequestListInput) => Effect.Effect; + readonly summary: (input: PullRequestRef) => Effect.Effect; + readonly checks: (input: PullRequestRef) => Effect.Effect; + }) { + const record = (what: string) => (error: Failure) => + Effect.sync(() => { + failures.push(`${what}: ${error.message}`); + }); + while (true) { + const listed = yield* rpc + .list({ state: "open" }) + .pipe(Effect.tapError(record("pullRequests.list")), Effect.option); + const entry = + listed._tag === "Some" + ? listed.value.entries.find((row) => row.headBranch === "bench/feature") + : undefined; + if (listed._tag === "Some" && entry === undefined) { + failures.push(`pullRequests.list: no branch PR in ${listed.value.entries.length} rows`); + } + if (entry !== undefined) { + const ref = { + projectId: entry.projectId, + host: entry.host, + repository: entry.repository, + number: entry.number, + }; + const completed = yield* Effect.all([rpc.summary(ref), rpc.checks(ref)]).pipe( + Effect.as(true), + Effect.catch((error) => + record("pullRequests.summary/checks")(error).pipe(Effect.as(false)), + ), + ); + if (completed) completedPolls++; + } + yield* Effect.sleep(Duration.seconds(30)); + } + }); + + return { + host, + /** The server's view of the host: the fake token and CA, and none of the developer's logins. */ + env: { + GH_HOST: host, + GH_ENTERPRISE_TOKEN: TOKEN, + GITHUB_ENTERPRISE_TOKEN: "", + GH_TOKEN: "", + GITHUB_TOKEN: "", + // An empty gh config, so a gh the server runs has no login for any host. + GH_CONFIG_DIR: path.join(dir, "gh"), + NODE_EXTRA_CA_CERTS: certFile, + // Overrides a developer's own GIT_SSL_CAINFO, which would win over the repository's setting. + GIT_SSL_CAINFO: certFile, + NODE_USE_ENV_PROXY: "1", + HTTPS_PROXY: proxyUrl, + https_proxy: proxyUrl, + // The fake Anthropic API and the server's own loopback listeners stay direct. + NO_PROXY: "127.0.0.1,localhost,::1", + no_proxy: "127.0.0.1,localhost,::1", + }, + setupProject, + advanceRemote, + /** Records whether the project's origin/main moved past setup, i.e. the server fetched a push. */ + checkFetched: (project: string) => + run("git", ["rev-parse", "refs/remotes/origin/main"], { cwd: project }).pipe( + Effect.map(({ stdout }) => { + fetchedPush = stdout.trim() !== publishedMain; + }), + ), + requests: requests as ReadonlyArray, + pollLikeWebClient, + /** + * Prints what the server asked for, and fails unless it polled pull requests and checks and + * fetched from the remote. Poller failures are reported, not fatal: a long soak can see one. + */ + verify: Effect.gen(function* () { + const counts = new Map(); + for (const request of requests.slice(setupRequests)) { + const key = + request.operation ?? + (request.path.startsWith(`/${OWNER}/${REPO}.git/`) + ? request.status !== 200 + ? undefined + : request.path.startsWith(`/${OWNER}/${REPO}.git/info/refs`) + ? "git fetch" + : undefined + : `${request.method} ${request.path.replace(/\?.*/, "")} ${request.status}`); + if (key !== undefined) counts.set(key, (counts.get(key) ?? 0) + 1); + } + const listed = [...counts].map(([key, count]) => `${key} ×${count}`).join(", "); + yield* Console.error(`fake GitHub served ${requests.length} requests: ${listed}`); + if (failures.length > 0) { + yield* Console.error( + `fake GitHub: ${failures.length} client polls failed, first: ${failures[0]}`, + ); + } + const missing = [ + "PullRequestsByHead", + "PullRequestSearch", + "PullRequestCore", + "git fetch", + ].filter((key) => !counts.has(key)); + if (pushes > 0 && !fetchedPush) missing.push("a fetch that brought in a pushed commit"); + if (completedPolls === 0) missing.push("one full client poll (list, summary, checks)"); + if (missing.length > 0) { + return yield* new ScenarioError({ + message: `the soak never reached the fake GitHub for ${missing.join(", ")}`, + }); + } + }), + }; +}); + +export type FakeGitHub = Effect.Success>; diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index b06e08a590af0..bab911ab9124f 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -37,6 +37,8 @@ const Soak = Schema.Struct({ minutes: Schema.Number, heapMBPerHour: Schema.Number, rssMBPerHour: Schema.Number, + /** Processes below the server, so agent or git children that outlive their thread show. */ + childProcessesPerHour: Schema.optional(Schema.Number), }); const MachineState = Schema.Struct({ @@ -161,6 +163,14 @@ export const HeapGrowth = Schema.Struct({ MB: Schema.Number, }); +/** An object whose retained size grew at every soak snapshot, and how it is reached. */ +export const RetainerGrowth = Schema.Struct({ + path: Schema.String, + MB: Schema.Number, + retainedMB: Schema.Number, +}); +export type RetainerGrowth = typeof RetainerGrowth.Type; + export const ServerMetrics = Schema.Struct({ meta: Schema.Record( Schema.String, @@ -170,6 +180,7 @@ export const ServerMetrics = Schema.Struct({ /** Top CPU self time (ms) and allocated MB by function, from the last run. */ profiles: Schema.optional(Schema.Record(Schema.String, ProfileSummary)), soakHeapGrowth: Schema.optional(Schema.Array(HeapGrowth)), + soakRetainerGrowth: Schema.optional(Schema.Array(RetainerGrowth)), }); export type ServerMetrics = typeof ServerMetrics.Type; @@ -703,19 +714,24 @@ export function summarizeProfiles( return { cpuMs: top(cpuTotals, 0), allocatedMB: top(allocations, 1) }; } +const TypeNames = Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])); export const HeapSnapshot = Schema.Struct({ snapshot: Schema.Struct({ meta: Schema.Struct({ node_fields: Schema.Array(Schema.String), - node_types: Schema.Array(Schema.Union([Schema.Array(Schema.String), Schema.String])), + node_types: TypeNames, + edge_fields: Schema.Array(Schema.String), + edge_types: TypeNames, }), }), nodes: Schema.Array(Schema.Number), + edges: Schema.Array(Schema.Number), strings: Schema.Array(Schema.String), }); +type HeapSnapshot = typeof HeapSnapshot.Type; /** Self size by constructor from a V8 heap snapshot. */ -export function heapByConstructor(snapshot: typeof HeapSnapshot.Type) { +export function heapByConstructor(snapshot: HeapSnapshot) { const fields = snapshot.snapshot.meta.node_fields; const typeNames = snapshot.snapshot.meta.node_types[0]; const types = Array.isArray(typeNames) ? typeNames : []; @@ -757,6 +773,253 @@ export function heapGrowth( .map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) })); } +interface Retainer { + readonly retained: number; + /** The id of the node that dominates this one, none for the root. */ + readonly dominator: number | undefined; + /** Empty below `pathBytes`: such a node is only kept to compare sizes across snapshots. */ + readonly path: string; +} + +const TEXT_NODES = new Set(["string", "concatenated string", "sliced string", "regexp", "number"]); +const IDENTIFIER = /^[A-Za-z_$#][\w$]{0,48}$/; + +/** + * Retained size by node id for every node retaining at least `minBytes`, and for those retaining + * `pathBytes` the shortest strong path from the root to it. Node ids are stable within one process, so snapshots of one + * server line up. Paths name only code: string contents and non-identifier keys are left out. + */ +export function heapRetainers(snapshot: HeapSnapshot, minBytes = 16_000, pathBytes = 256_000) { + const { meta } = snapshot.snapshot; + const nodeFields = meta.node_fields.length; + const edgeFields = meta.edge_fields.length; + const list = (names: typeof meta.node_types) => { + const first = names[0]; + return Array.isArray(first) ? first : []; + }; + const nodeTypes = list(meta.node_types); + const edgeTypes = list(meta.edge_types); + const [typeAt, nameAt, idAt, sizeAt, edgeCountAt] = [ + "type", + "name", + "id", + "self_size", + "edge_count", + ].map((field) => meta.node_fields.indexOf(field)) as [number, number, number, number, number]; + const [edgeTypeAt, edgeNameAt, toAt] = ["type", "name_or_index", "to_node"].map((field) => + meta.edge_fields.indexOf(field), + ) as [number, number, number]; + const { nodes, edges, strings } = snapshot; + const count = nodes.length / nodeFields; + const firstEdge = new Uint32Array(count + 1); + for (let node = 0, offset = 0; node < count; node++) { + firstEdge[node] = offset; + offset += nodes[node * nodeFields + edgeCountAt]! * edgeFields; + firstEdge[node + 1] = offset; + } + const weak = edgeTypes.indexOf("weak"); + const shortcut = edgeTypes.indexOf("shortcut"); + const strong = (edge: number) => + edges[edge + edgeTypeAt] !== weak && edges[edge + edgeTypeAt] !== shortcut; + const target = (edge: number) => edges[edge + toAt]! / nodeFields; + + // Postorder from the root, then dominators by Cooper, Harvey and Kennedy's iteration. + const postorder = new Int32Array(count).fill(-1); + const order = new Int32Array(count); + const stack = new Int32Array(count); + const cursor = new Uint32Array(count); + const seen = new Uint8Array(count); + let depth = 0; + let visited = 0; + stack[depth++] = 0; + seen[0] = 1; + cursor[0] = firstEdge[0]!; + while (depth > 0) { + const node = stack[depth - 1]!; + if (cursor[node]! < firstEdge[node + 1]!) { + const edge = cursor[node]!; + cursor[node] = edge + edgeFields; + const next = target(edge); + if (strong(edge) && !seen[next]) { + seen[next] = 1; + cursor[next] = firstEdge[next]!; + stack[depth++] = next; + } + } else { + depth--; + postorder[node] = visited; + order[visited++] = node; + } + } + const predecessorStart = new Uint32Array(count + 1); + for (let node = 0; node < count; node++) { + if (!seen[node]) continue; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + if (strong(edge)) predecessorStart[target(edge) + 1]!++; + } + } + for (let node = 0; node < count; node++) predecessorStart[node + 1]! += predecessorStart[node]!; + const predecessors = new Int32Array(predecessorStart[count]!); + const fill = predecessorStart.slice(0, count); + for (let node = 0; node < count; node++) { + if (!seen[node]) continue; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + if (strong(edge)) predecessors[fill[target(edge)]!++] = node; + } + } + const dominator = new Int32Array(count).fill(-1); + dominator[0] = 0; + const intersect = (left: number, right: number) => { + while (left !== right) { + while (postorder[left]! < postorder[right]!) left = dominator[left]!; + while (postorder[right]! < postorder[left]!) right = dominator[right]!; + } + return left; + }; + for (let changed = true; changed;) { + changed = false; + for (let index = visited - 2; index >= 0; index--) { + const node = order[index]!; + let found = -1; + for (let at = predecessorStart[node]!; at < predecessorStart[node + 1]!; at++) { + const predecessor = predecessors[at]!; + if (dominator[predecessor] === -1) continue; + found = found === -1 ? predecessor : intersect(predecessor, found); + } + if (found !== -1 && dominator[node] !== found) { + dominator[node] = found; + changed = true; + } + } + } + const retained = new Float64Array(count); + for (let node = 0; node < count; node++) retained[node] = nodes[node * nodeFields + sizeAt]!; + for (let index = 0; index < visited - 1; index++) { + const node = order[index]!; + retained[dominator[node]!]! += retained[node]!; + } + + const parent = new Int32Array(count).fill(-1); + const parentEdge = new Int32Array(count).fill(-1); + const queue = new Int32Array(count); + let head = 0; + let tail = 0; + queue[tail++] = 0; + parent[0] = 0; + while (head < tail) { + const node = queue[head++]!; + for (let edge = firstEdge[node]!; edge < firstEdge[node + 1]!; edge += edgeFields) { + const next = target(edge); + if (!strong(edge) || parent[next] !== -1) continue; + parent[next] = node; + parentEdge[next] = edge; + queue[tail++] = next; + } + } + const nodeType = (node: number) => nodeTypes[nodes[node * nodeFields + typeAt]!] ?? "?"; + const label = (node: number) => { + const type = nodeType(node); + if (TEXT_NODES.has(type)) return `(${type})`; + const name = strings[nodes[node * nodeFields + nameAt]!] ?? ""; + const shown = name.length > 60 || /["'`\n\\]|:\/\/|(^|\s)\/[\w.]/.test(name) ? "?" : name; + if (type === "object") return shown; + if (type === "closure") return `${shown || "(anonymous)"}()`; + return `(${type}${shown ? ` ${shown}` : ""})`; + }; + const edgeName = (edge: number) => { + const type = edgeTypes[edges[edge + edgeTypeAt]!]; + const value = edges[edge + edgeNameAt]!; + if (type === "element" || type === "hidden") return `[${value}]`; + const name = strings[value] ?? ""; + return IDENTIFIER.test(name) ? name : ""; + }; + const pathTo = (node: number) => { + const steps: string[] = []; + for (let at = node; at !== 0 && steps.length < 40; at = parent[at]!) { + if (parent[at] === -1) return "(unreachable)"; + const from = parent[at]!; + steps.push( + from === 0 || nodeType(from) === "synthetic" + ? edgeName(parentEdge[at]!) + : `${label(from)}.${edgeName(parentEdge[at]!)}`, + ); + if (nodeType(from) === "synthetic") break; + } + const shown = steps.reverse(); + return [...(shown.length > 6 ? ["…", ...shown.slice(-6)] : shown), label(node)].join(" → "); + }; + const result = new Map(); + for (let node = 0; node < count; node++) { + if (!seen[node] || retained[node]! < minBytes) continue; + result.set(nodes[node * nodeFields + idAt]!, { + retained: retained[node]!, + dominator: node === 0 ? undefined : nodes[dominator[node]! * nodeFields + idAt]!, + path: + retained[node]! < pathBytes + ? "" + : nodeType(node) === "synthetic" + ? label(node) + : pathTo(node), + }); + } + return result; +} + +/** + * The objects whose retained size grew from each snapshot to the next, at least `minBytes` in all. + * An object is left out when a reported object it dominates holds at least 80% of its growth: of + * a chain that grew by about the same amount, only the deepest is kept, the container holding the + * growth. Nested objects whose growth differs are each reported. + */ +export function retainerGrowth( + snapshots: ReadonlyArray>, + minBytes = 1_000_000, +) { + const last = snapshots.at(-1); + if (last === undefined || snapshots.length < 2) return []; + const growth = new Map(); + for (const [id, { retained, path }] of last) { + if (path === "" || path.startsWith("(synthetic")) continue; + const sizes = [ + ...snapshots.slice(0, -1).map((snapshot) => snapshot.get(id)?.retained ?? 0), + retained, + ]; + const grewEachTime = sizes.every((size, index) => index === 0 || size > sizes[index - 1]!); + const grown = retained - sizes[0]!; + if (grewEachTime && grown >= minBytes) growth.set(id, grown); + } + const ancestors = (id: number) => { + const found: number[] = []; + for (let at = last.get(id)?.dominator; at !== undefined && found.length < 500;) { + found.push(at); + at = last.get(at)?.dominator; + } + return found; + }; + // Deepest first, so every descendant is decided before its ancestors: a row is left out + // only when a reported descendant holds at least 80% of its growth. + const heldBelow = new Map(); + const kept: Array<[number, number]> = []; + const depth = new Map([...growth.keys()].map((id) => [id, ancestors(id).length])); + const order = [...growth].toSorted((a, b) => depth.get(b[0])! - depth.get(a[0])!); + for (const [id, grown] of order) { + if ((heldBelow.get(id) ?? 0) >= grown * 0.8) continue; + kept.push([id, grown]); + for (const ancestor of ancestors(id)) { + heldBelow.set(ancestor, Math.max(heldBelow.get(ancestor) ?? 0, grown)); + } + } + const rows: RetainerGrowth[] = kept + .toSorted((a, b) => b[1] - a[1]) + .slice(0, 10) + .map(([id, grown]) => ({ + path: last.get(id)!.path, + MB: round(grown / 1e6, 2), + retainedMB: round(last.get(id)!.retained / 1e6, 2), + })); + return rows; +} + const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.String)); const spellings: ReadonlyArray<(path: string) => string> = [ (path) => path, diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 6597e9297514b..9baf6a86369a2 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -9,6 +9,7 @@ import { activityRenewalMissed, describeFailure, heapGrowth, + heapRetainers, loadWarnings, nextActivityReport, noiseReport, @@ -16,6 +17,7 @@ import { parsePsCpuTime, profileMismatch, parseRunSelection, + retainerGrowth, pathRewrites, pathSpellings, ServerMetrics, @@ -467,6 +469,87 @@ describe("heapGrowth", () => { }); }); +describe("heapRetainers", () => { + it("sums what each object alone keeps alive and names only code on the way to it", () => { + // root → Holder.cache → Map → [0] array → [0] string; Holder also points at the string weakly. + const node = (type: number, name: number, id: number, size: number, edges: number) => [ + type, + name, + id, + size, + edges, + ]; + const retainers = heapRetainers( + { + snapshot: { + meta: { + node_fields: ["type", "name", "id", "self_size", "edge_count"], + node_types: [["synthetic", "object", "array", "string"]], + edge_fields: ["type", "name_or_index", "to_node"], + edge_types: [["property", "element", "weak", "hidden"]], + }, + }, + nodes: [ + ...node(0, 4, 1, 0, 1), + ...node(1, 1, 3, 100, 2), + ...node(1, 2, 5, 50, 1), + ...node(2, 0, 7, 1_000, 1), + ...node(3, 5, 9, 500, 0), + ], + edges: [0, 6, 5, 0, 3, 10, 2, 0, 20, 3, 0, 15, 1, 0, 20], + strings: ["", "Holder", "Map", "cache", "(GC roots)", "a secret", "holder"], + }, + 0, + 0, + ); + expect(retainers.get(5)).toEqual({ + retained: 1_550, + dominator: 3, + path: "holder → Holder.cache → Map", + }); + expect(retainers.get(3)?.retained).toBe(1_650); + expect(retainers.get(9)?.path).toBe("holder → Holder.cache → Map.[0] → (array).[0] → (string)"); + }); +}); + +describe("retainerGrowth", () => { + const at = (sizes: Record) => + new Map( + Object.entries(sizes).map(([id, retained]) => [ + Number(id), + { retained, dominator: Number(id) === 3 ? undefined : 3, path: `node ${id}` }, + ]), + ); + it("reports the deepest object holding the growth, and only growth at every snapshot", () => { + const growth = retainerGrowth([ + at({ 3: 1_000_000, 5: 900_000, 7: 2_000_000 }), + at({ 3: 3_000_000, 5: 2_900_000, 7: 4_000_000 }), + at({ 3: 5_000_000, 5: 4_900_000, 7: 3_500_000 }), + ]); + expect(growth).toEqual([{ path: "node 5", MB: 4, retainedMB: 4.9 }]); + }); + it("keeps an ancestor its reported descendant does not account for", () => { + // A chain 1 → 2 → 3 growing by 7, 6 and 5 MB, and 4 under 1 growing by 2 MB. + const chain = (scale: number) => + new Map( + [ + [1, 7, undefined], + [2, 6, 1], + [3, 5, 2], + [4, 2, 1], + ].map(([id, mb, dominator]) => [ + id!, + { retained: (10 + mb! * scale) * 1e6, dominator, path: `node ${id}` }, + ]), + ); + expect(retainerGrowth([chain(0), chain(0.5), chain(1)]).map(({ path }) => path)).toEqual([ + "node 1", + "node 3", + "node 4", + ]); + }); +}); + describe("slope", () => { it("fits the cost per thread", () => { const points: Array = [ diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 9fa06fcfdea5c..6f553bcea38c1 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -57,6 +57,7 @@ import * as Scope from "effect/Scope"; import * as Socket from "effect/socket/Socket"; import { run } from "./scenarios/shell.ts"; +import { serveFakeGitHub, type FakeGitHub } from "./server-metrics-forge.ts"; import { compareMetrics, CpuProfile, @@ -65,6 +66,9 @@ import { HeapSnapshot, heapByConstructor, heapGrowth, + heapRetainers, + retainerGrowth, + type RetainerGrowth, competingBetween, loadWarnings, noiseReport, @@ -135,6 +139,9 @@ const RECONNECT_CLIENTS = 3; const RECONNECT_THREADS = 10; /** Clients that drop and reconnect at once in the opt-in storm, each holding one thread. */ const STORM_CLIENTS = 20; +/** Threads the soak keeps open; every few turns the oldest is replaced. */ +const SOAK_THREADS = 10; +const SOAK_CHURN_TURNS = 4; /** Event-loop delay sampling interval; each sample wakes the loop once. */ const LOOP_RESOLUTION_MS = 10; const LoopStats = Schema.Struct({ @@ -523,7 +530,8 @@ const inspect = Effect.fn("serverMetrics.inspect")(function* (url: string) { yield* send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); const json = chunks.join(""); chunks.length = 0; - return heapByConstructor(yield* decodeJson(HeapSnapshot)(json)); + const snapshot = yield* decodeJson(HeapSnapshot)(json); + return { byConstructor: heapByConstructor(snapshot), retainers: heapRetainers(snapshot) }; }), }; }); @@ -582,7 +590,8 @@ const descendantsOf = Effect.fn("serverMetrics.descendantsOf")(function* (pid: n } } else if (platform === "darwin") { const table = yield* output("ps", ["-A", "-o", "pid=,ppid="]); - for (const line of Option.getOrElse(table, () => "").split("\n")) { + if (Option.isNone(table)) return yield* new MetricsError({ message: "ps listed no processes" }); + for (const line of table.value.split("\n")) { const [child, parent] = line.trim().split(/\s+/).map(Number); if (child && parent) add(child, parent); } @@ -611,6 +620,8 @@ interface Environment { interface ServerOptions { /** A base dir `migrate-dev-db` prepared; the server starts on a copy of its database. */ readonly seed?: string; + /** A fake GitHub host the project's origin points at. */ + readonly forge?: FakeGitHub; } /** Transcript text: paths there are words in a conversation, which the server never acts on. */ @@ -834,12 +845,14 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( yield* fs.makeDirectory(project); yield* fs.writeFileString(path.join(project, "README.md"), "# bench\n"); for (const args of [ - ["init", "-q", "-b", "main"], + // Loose refs on purpose: the soak writes them as files, which a reftable store would ignore. + ["-c", "init.defaultRefFormat=files", "init", "-q", "-b", "main"], ["add", "."], ["-c", "user.email=bench@t3.codes", "-c", "user.name=bench", "commit", "-qm", "init"], ]) { yield* run("git", args, { cwd: project }); } + if (options.forge !== undefined) yield* options.forge.setupProject(project); const baseDir = path.join(directory, "base"); // Branch names come from Claude too, so a worktree launch's naming call reaches the fake API. yield* fs.makeDirectory(path.join(baseDir, "userdata"), { recursive: true }); @@ -872,6 +885,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", OTEL_SDK_DISABLED: "true", T3CODE_DEV_SEED: "0", + ...options.forge?.env, }; const port = yield* freePort; const started = yield* nowMs; @@ -1025,6 +1039,7 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( return { readyMs, + pid, startedAt: started, origin: `http://127.0.0.1:${port}`, /** The seeded projects' clones; none without a seed. */ @@ -1247,6 +1262,8 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( threadId: string, item: OrchestrationV2ThreadStreamItem, ) => Effect.Effect = () => Effect.void, + /** How long the server may go silent before the client drops the connection or a report fails. */ + pingTimeout?: Duration.Input, ) { const http = yield* HttpClient.HttpClient; // Headers alone do not finish a request; the deadline covers the body too. @@ -1265,7 +1282,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( ); const { ticket } = yield* decodeJson(Schema.Struct({ ticket: Schema.String }))(ticketBody); const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( + RpcClient.layerProtocolSocket(pingTimeout === undefined ? {} : { pingTimeout }).pipe( Layer.provide( Socket.layerWebSocket( `${server.origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, @@ -1279,6 +1296,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( // client costs, so the first such loss is kept for `healthy` to report. const lost = yield* Ref.make(undefined); const ready = Effect.fn("serverMetrics.subscription")(function* ( + name: string, stream: Stream.Stream, isReady: (item: A) => boolean, onItem: (item: A) => Effect.Effect = () => Effect.void, @@ -1294,8 +1312,10 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( Effect.andThen(isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void), ), ), - Effect.andThen(lose("a subscription ended")), - Effect.catchCause(() => lose("a subscription failed")), + Effect.andThen(lose(`the ${name} subscription ended`)), + Effect.catchCause((cause) => + lose(`the ${name} subscription failed: ${describeFailure(Cause.squash(cause))}`), + ), Effect.forkScoped, ); return Deferred.await(synchronized); @@ -1317,7 +1337,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }).pipe( // A server that keeps the socket open but never answers would otherwise hang the scenario. Effect.timeoutOrElse({ - duration: Duration.seconds(15), + duration: pingTimeout ?? Duration.seconds(15), orElse: () => new MetricsError({ message: "an activity report got no answer" }), }), ); @@ -1346,6 +1366,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( const synchronized = (item: { readonly kind: string }) => item.kind === "synchronized"; const waits = [ yield* ready( + "shell", client["orchestration.subscribeShell"]({ requestCompletionMarker: true, omitIdleSubagents: true, @@ -1353,9 +1374,10 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }), synchronized, ), - yield* ready(client.subscribeVcsStatus({ cwd: server.project }), () => true), + yield* ready("VCS status", client.subscribeVcsStatus({ cwd: server.project }), () => true), ...(yield* Effect.forEach(threadIds, (threadId) => ready( + `thread ${threadId}`, client["orchestration.subscribeThread"]({ threadId: ThreadId.make(threadId), requestCompletionMarker: true, @@ -1390,6 +1412,14 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( creationSource: "web", dispatchMode: { type: "start_immediately" }, }), + rpc: client, + /** Archives or deletes a thread the way the sidebar does. */ + retire: (type: "thread.archive" | "thread.delete", threadId: string, commandId: string) => + client["orchestration.dispatchCommand"]({ + type, + commandId: CommandId.make(commandId), + threadId: ThreadId.make(threadId), + }), /** Fails if any of this client's subscriptions or reports was lost since it attached. */ healthy: Effect.flatMap(Ref.get(lost), (message) => message === undefined ? Effect.void : Effect.fail(new MetricsError({ message })), @@ -1640,6 +1670,7 @@ interface RunOptions { /** One pass: startup, rest and firstWord share a server; quiet, streaming and soak get their own. */ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { const fs = yield* FileSystem.FileSystem; + const platform = yield* HostProcess.Platform; const path = yield* Path.Path; const machine = yield* watchMachine; const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); @@ -1658,6 +1689,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption const measured: { -readonly [K in keyof Measured]: Measured[K] } = {}; const profiles: Record = {}; let soakHeapGrowth: ReturnType | undefined; + let soakRetainerGrowth: ReadonlyArray | undefined; const withServer = ( name: string, body: (server: Server) => Effect.Effect, @@ -1916,50 +1948,165 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption ); } if (options.soakMinutes > 0) { - yield* withServer("soak", (server) => - Effect.gen(function* () { - const threads = yield* openThreads(server, 0, 10); - yield* Effect.sleep(Duration.seconds(60)); - // The snapshot inflates RSS once, so the slopes start after it. - const before = yield* server.snapshot; - const samples: Array<{ hours: number; window: Window }> = []; - const start = yield* nowMs; - const elapsed = Effect.map(nowMs, (now) => now - start); - const takeSample = Effect.gen(function* () { - samples.push({ hours: (yield* elapsed) / 3_600_000, window: yield* server.measure(5) }); - }); - let nextSample = 0; - for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { - if ((yield* elapsed) >= nextSample) { - yield* takeSample; - nextSample += 120_000; + const forge = yield* serveFakeGitHub(); + yield* withServer( + "soak", + (server) => + Effect.gen(function* () { + let threads = yield* openThreads(server, 0, SOAK_THREADS); + // A busy repository under a web client: thousands of loose remote-tracking refs, more + // arriving every turn as fetches and agent branches add them, so caches keyed by ref + // state churn the way they do on a real checkout. + const head = (yield* run("git", ["rev-parse", "HEAD"], { cwd: server.project })).stdout; + // Under a remote with no config, so no fetch (or a host's fetch.prune) can delete them. + const remotes = path.join(server.project, ".git", "refs", "remotes", "mirror"); + yield* fs.makeDirectory(remotes, { recursive: true }); + yield* Effect.forEach( + Array.from({ length: 3_000 }, (_, index) => index), + (index) => fs.writeFileString(path.join(remotes, `bench-${index}`), head), + { concurrency: 64, discard: true }, + ); + // A reftable store (GIT_DEFAULT_REF_FORMAT can still pick one) ignores refs written as files. + const listed = yield* run( + "git", + ["for-each-ref", "--count=3000", "refs/remotes/mirror/"], + { + cwd: server.project, + }, + ); + if (listed.stdout.trim().split("\n").length < 3_000) { + return yield* new MetricsError({ message: "git does not see the soak's loose refs" }); } - // Round robin, so two soaks send the same turns to the same threads. - const threadId = threads[turn % threads.length]; - if (threadId === undefined) - return yield* new MetricsError({ message: "no soak threads" }); - const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); - if (sent.exitCode !== 0) { - return yield* new MetricsError({ - message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, - }); + const token = yield* server.issueToken; + // The client gets a scope of its own so each churn cycle can drop it and reconnect. + const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => + Scope.close(scope, exit), + ); + // Each client also polls pull requests the way the sidebar and an open PR do. + const connect = Effect.fn("serverMetrics.soakClient")(function* ( + threadIds: ReadonlyArray, + ) { + // A heap snapshot pauses the server for longer than the default 5 s ping timeout. + const client = yield* attachClient( + server, + token, + threadIds, + undefined, + Duration.minutes(2), + ); + yield* forge + .pollLikeWebClient({ + list: client.rpc["pullRequests.list"], + summary: client.rpc["pullRequests.summary"], + checks: client.rpc["pullRequests.checks"], + }) + .pipe(Effect.forkScoped); + return client; + }); + let scope = yield* clientScope; + let client = yield* connect(threads).pipe(Scope.provide(scope)); + yield* Effect.sleep(Duration.seconds(60)); + // The first snapshot inflates RSS once, so the slopes start after it. + const snapshots = [yield* server.snapshot]; + const samples: Array<{ + hours: number; + window: Window; + rssMB: number; + processes: number | null; + }> = []; + const start = yield* nowMs; + const elapsed = Effect.map(nowMs, (now) => now - start); + let snapshotRssMB = 0; + const takeSample = Effect.gen(function* () { + const hours = (yield* elapsed) / 3_600_000; + const window = yield* server.measure(5); + // Windows lists no descendants, which is not the same as having none. + const processes = + platform === "win32" + ? null + : yield* descendantsOf(server.pid).pipe( + Effect.map((found) => found.length), + // Unknown, not zero: a failed probe leaves the process slope out. + Effect.orElseSucceed(() => null), + ); + samples.push({ hours, window, rssMB: window.rssMB - snapshotRssMB, processes }); + yield* Console.error( + `soak ${round(hours * 60)} min: heap ${window.heapAfterGcMB} MB, RSS ${window.rssMB} MB${processes === null ? "" : `, ${processes} child processes`}`, + ); + }); + let nextSample = 0; + for (let turn = 0; (yield* elapsed) < options.soakMinutes * 60_000; turn++) { + if (snapshots.length === 1 && (yield* elapsed) >= options.soakMinutes * 30_000) { + // RSS the snapshot itself added stays off the slope: later samples drop the step. + const before = (yield* sample(server.pid)).rss; + snapshots.push(yield* server.snapshot); + snapshotRssMB = Math.max(0, ((yield* sample(server.pid)).rss - before) / 1e6); + } + if ((yield* elapsed) >= nextSample) { + yield* takeSample; + nextSample += 120_000; + } + // Users come and go: a new thread replaces the oldest, which is archived and deleted, + // and the client reconnects, so state kept per thread or per connection must be freed. + if (turn > 0 && turn % SOAK_CHURN_TURNS === 0) { + yield* client.healthy; + const [fresh] = yield* openThreads(server, SOAK_THREADS + turn, 1); + const [oldest, ...rest] = threads; + if (fresh === undefined || oldest === undefined) + return yield* new MetricsError({ message: "no soak thread to churn" }); + threads = [...rest, fresh]; + const retiring = client; + yield* Scope.close(scope, Exit.void); + // A loss while the replacement thread started still counts against the run. + yield* retiring.healthy.pipe( + Effect.mapError( + (error) => new MetricsError({ message: `the retired client: ${error.message}` }), + ), + ); + scope = yield* clientScope; + client = yield* connect(threads).pipe(Scope.provide(scope)); + yield* forge.advanceRemote; + yield* client.retire("thread.archive", oldest, `bench-archive-${turn}`); + yield* client.retire("thread.delete", oldest, `bench-delete-${turn}`); + } + // Round robin, so two soaks send the same turns to the same threads. + const threadId = threads[turn % threads.length]; + if (threadId === undefined) + return yield* new MetricsError({ message: "no soak threads" }); + yield* fs.writeFileString(path.join(remotes, `soak-${turn}`), head); + const sent = yield* server.threadSend(threadId, `Short reply ${turn}.`); + if (sent.exitCode !== 0) { + return yield* new MetricsError({ + message: `soak turn ${turn} on ${threadId} failed: ${sent.stderr.trim() || sent.stdout.trim()}`, + }); + } + yield* Effect.sleep( + Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed))), + ); } - yield* Effect.sleep(Duration.millis(Math.max(0, (turn + 1) * 30_000 - (yield* elapsed)))); - } - yield* takeSample; - const perHour = (pick: (window: Window) => number) => - round(slope(samples.map(({ hours, window }) => [hours, pick(window)]))); - measured.soak = { - minutes: options.soakMinutes, - heapMBPerHour: perHour((window) => window.heapAfterGcMB), - rssMBPerHour: perHour((window) => window.rssMB), - }; - soakHeapGrowth = heapGrowth(before, yield* server.snapshot); - }), + yield* takeSample; + yield* client.healthy; + yield* forge.checkFetched(server.project); + const perHour = (pick: (sample: (typeof samples)[number]) => number) => + round(slope(samples.map((sample) => [sample.hours, pick(sample)]))); + measured.soak = { + minutes: options.soakMinutes, + heapMBPerHour: perHour(({ window }) => window.heapAfterGcMB), + rssMBPerHour: perHour(({ rssMB }) => rssMB), + ...(samples.some(({ processes }) => processes === null) + ? {} + : { childProcessesPerHour: perHour(({ processes }) => processes ?? 0) }), + }; + snapshots.push(yield* server.snapshot); + soakHeapGrowth = heapGrowth(snapshots[0]!.byConstructor, snapshots.at(-1)!.byConstructor); + soakRetainerGrowth = retainerGrowth(snapshots.map((snapshot) => snapshot.retainers)); + }), + { forge }, ); + yield* forge.verify; } measured.machine = yield* machine; - return { measured: measured as Measured, profiles, soakHeapGrowth }; + return { measured: measured as Measured, profiles, soakHeapGrowth, soakRetainerGrowth }; }, Effect.scoped); const machineLoad = Effect.gen(function* () { @@ -2277,7 +2424,7 @@ const runFlags = { soak: Flag.Int("soak").pipe( Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), Flag.withDescription( - "Minutes of soak: 10 threads, a short turn every 30 s; heap and RSS slopes per hour and the constructors that grew. Runs alone unless --only names more.", + "Minutes of soak: 10 threads under one web client, a short turn every 30 s in a project with 3,000 loose remote refs that gains one per turn. From minute 2, every 2 minutes a new thread replaces the oldest (archived, then deleted), the client reconnects and a fake GitHub remote gains a commit; the client polls that host's pull requests and checks. Reports heap, RSS and child-process slopes per hour, the constructors that grew, and the objects whose retained size grew at each of three snapshots with the path that holds them. Needs openssl on PATH and Node 24.5 or later. Runs alone unless --only names more.", ), Flag.withDefault(0), ), @@ -2381,6 +2528,7 @@ const runCommand = Command.make( runs, ...(last ? { profiles: last.profiles } : {}), ...(last?.soakHeapGrowth ? { soakHeapGrowth: last.soakHeapGrowth } : {}), + ...(last?.soakRetainerGrowth ? { soakRetainerGrowth: last.soakRetainerGrowth } : {}), }); }, Effect.scoped), ).pipe( From 8d9b39edc540fe61dba927681287e58b3db42afc Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:40:14 +0100 Subject: [PATCH 166/221] fix(mobile): long branch names in the Git menu no longer show a broken character (#41861) Co-authored-by: Julius Marminge --- .../threads/ThreadGitControls.logic.test.ts | 9 ++++++ .../threads/ThreadGitControls.logic.ts | 17 +++++++++++ .../features/threads/ThreadGitControls.tsx | 15 +--------- ...-menu-branch-keeps-whole-characters.e2e.ts | 28 +++++++++++++++++++ 4 files changed, 55 insertions(+), 14 deletions(-) create mode 100644 apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts create mode 100644 apps/mobile/src/features/threads/ThreadGitControls.logic.ts create mode 100644 scripts/scenarios/git-menu-branch-keeps-whole-characters.e2e.ts diff --git a/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts b/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts new file mode 100644 index 0000000000000..1538540949880 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts @@ -0,0 +1,9 @@ +import { expect, it } from "vite-plus/test"; + +import { compactMenuBranchLabel } from "./ThreadGitControls.logic"; + +it("keeps emoji whole at both cuts of a long branch name", () => { + expect(compactMenuBranchLabel("feature/abc😀-long-branch-name-😀-for-menus")).toBe( + "feature/abc…-for-menus", + ); +}); diff --git a/apps/mobile/src/features/threads/ThreadGitControls.logic.ts b/apps/mobile/src/features/threads/ThreadGitControls.logic.ts new file mode 100644 index 0000000000000..a3441835b5951 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.logic.ts @@ -0,0 +1,17 @@ +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; + +function truncateMiddle(value: string, maxLength: number): string { + if (value.length <= maxLength) { + return value; + } + + const headLength = Math.ceil((maxLength - 1) / 2); + const tailStart = value.length - Math.floor((maxLength - 1) / 2); + const headEnd = splitsSurrogatePair(value, headLength) ? headLength - 1 : headLength; + const tailFrom = splitsSurrogatePair(value, tailStart) ? tailStart + 1 : tailStart; + return `${value.slice(0, headEnd)}…${value.slice(tailFrom)}`; +} + +export function compactMenuBranchLabel(branch: string): string { + return truncateMiddle(branch, 24); +} diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 1a36d6b350e4a..9e7ab388ccee4 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -30,20 +30,7 @@ import { type TerminalMenuSession, } from "../terminal/terminalMenu"; import { projectScriptMenuLabel } from "@t3tools/shared/projectScriptsCopy"; - -function truncateMiddle(value: string, maxLength: number): string { - if (value.length <= maxLength) { - return value; - } - - const headLength = Math.ceil((maxLength - 1) / 2); - const tailLength = Math.floor((maxLength - 1) / 2); - return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`; -} - -function compactMenuBranchLabel(branch: string): string { - return truncateMiddle(branch, 24); -} +import { compactMenuBranchLabel } from "./ThreadGitControls.logic"; function compactMenuStatus(gitStatus: VcsStatusResult | null, resolve: MessageResolver): string { if (!gitStatus) { diff --git a/scripts/scenarios/git-menu-branch-keeps-whole-characters.e2e.ts b/scripts/scenarios/git-menu-branch-keeps-whole-characters.e2e.ts new file mode 100644 index 0000000000000..088b9b00838c2 --- /dev/null +++ b/scripts/scenarios/git-menu-branch-keeps-whole-characters.e2e.ts @@ -0,0 +1,28 @@ +import { expect } from "e2e"; + +import { run } from "./shell.ts"; +import { runPromise } from "./t3.ts"; +import { IOS, test } from "./t3-mobile.ts"; + +// The Git menu shows 12 units, "…" and the last 11; each emoji straddles one cut. +const BRANCH = "feature/abc😀-long-branch-name-😀-for-menus"; + +test( + "The Git menu's branch title keeps whole characters at both cuts", + IOS, + async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + await runPromise(run("git", ["checkout", "--quiet", "-b", BRANCH], { cwd: project })); + await t3.thread({ project, title: "Branch work", messages: ["first"] }); + // A local simulator keeps the last run's pairing. + await app.clearState().catch(() => {}); + await t3.open(); + + await screen.getByText("Branch work", { exact: false }).first().tap({ timeout: 120_000 }); + await screen.getByRole("button", "Git controls").tap({ timeout: 60_000 }); + const title = screen.getByText("feature/abc", { exact: false }).first(); + await title.waitFor({ timeout: 30_000 }); + await app.screenshot("git-menu"); + await expect(title).toHaveText("feature/abc…-for-menus, Clean"); + }, +); From 3d9a14d4da9b17f2fe10c985103518af66727d84 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 21:42:18 -0600 Subject: [PATCH 167/221] fix(web): IME keys no longer trigger or close the prompt stash menu (#41875) Co-authored-by: Julius Marminge --- .../chat/ComposerStashMenu.browser.test.tsx | 27 +++++++++++++++++++ .../src/components/chat/ComposerStashMenu.tsx | 1 + 2 files changed, 28 insertions(+) diff --git a/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx b/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx index 79e43bba74314..9b23e1360f201 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.browser.test.tsx @@ -108,3 +108,30 @@ it("leaves dialog, unrelated input and question button shortcuts alone while the expect(stash().element().textContent).toContain("second prompt"); await expect.element(editor()).toHaveValue("Unsent draft"); }); + +it("leaves IME composition keys in the composer alone while the stash is open", async () => { + for (const composing of [{ isComposing: true }, { keyCode: 229 }]) { + for (const key of ["ArrowDown", "Enter", "Escape"]) { + await using _screen = await render(); + const textarea = editor().element(); + await focus(textarea); + const event = new KeyboardEvent("keydown", { + key, + ...composing, + bubbles: true, + cancelable: true, + }); + await act(async () => { + textarea.dispatchEvent(event); + }); + expect(event.defaultPrevented, `${key} ${JSON.stringify(composing)}`).toBe(false); + await expect.element(stash()).toBeInTheDocument(); + await expect.element(editor()).toHaveValue("Unsent draft"); + } + } + + await using _control = await render(); + await focus(editor().element()); + await press("{Enter}"); + await expect.element(editor()).toHaveValue("first prompt"); +}); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index 46e3fec307bf1..8aa139f84efcf 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -89,6 +89,7 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { }); const handleKeyDown = useEffectEvent((event: KeyboardEvent) => { + if (event.isComposing || event.keyCode === 229) return; const drawer = drawerRef.current; if (!drawer) return; const target = event.target; From 8a9e8d12a86fd5640a609ea277afba948a9470dd Mon Sep 17 00:00:00 2001 From: Omar Espinosa <77650361+OmarAlex24@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:42:31 -0600 Subject: [PATCH 168/221] fix(acp-registry): models show their own reasoning levels before their first session (#41850) Co-authored-by: Julius Marminge --- .../src/server/driver.test.ts | 277 ++++++++++++++++++ .../src/server/driver.ts | 228 +++++++++----- .../src/server/learnedModelOptions.ts | 231 +++++++++++++++ .../provider-acp-registry/src/server/probe.ts | 125 +++++++- 4 files changed, 768 insertions(+), 93 deletions(-) create mode 100644 packages/provider-acp-registry/src/server/learnedModelOptions.ts diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 684eb21d7456b..564486b9d8269 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -2,6 +2,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { AcpRegistryOperationError, + DEFAULT_SERVER_SETTINGS, ProviderInstanceId, type ServerProvider, } from "@t3tools/contracts"; @@ -19,6 +20,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; @@ -949,6 +951,61 @@ createInterface({ input: process.stdin }).on("line", (line) => { }); `; +// Reports `effort` levels for its current model only and logs each model switch. +const perModelEffortAgentSource = ` +import { appendFileSync, readFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +const [logPath, modelsPath] = process.argv.slice(2); +const levels = JSON.parse(readFileSync(modelsPath, "utf8")); +const modelIds = Object.keys(levels); +let current = modelIds[0]; +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +const configOptions = () => [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: current, + options: modelIds.map((value) => ({ value, name: value })), + }, + ...(levels[current] === null + ? [] + : [ + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: levels[current][0], + options: levels[current].map((value) => ({ value, name: value })), + }, + ]), +]; +createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method, params } = JSON.parse(line); + if (id === undefined) return; + if (method === "initialize") { + send({ id, result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } }); + } else if (method === "session/new") { + send({ id, result: { sessionId: "probe-session", configOptions: configOptions() } }); + send({ + method: "session/update", + params: { + sessionId: "probe-session", + update: { sessionUpdate: "available_commands_update", availableCommands: [] }, + }, + }); + } else if (method === "session/set_config_option" && params.configId === "model") { + appendFileSync(logPath, params.value + "\\n"); + current = params.value; + send({ id, result: { configOptions: configOptions() } }); + } else { + send({ id, result: {} }); + } +}); +`; + const driverLayer = TestProviderHost.layer({ runBackgroundWork: false }).pipe( Layer.provideMerge(AcpRegistryRuntimeCoordinator.layer), Layer.provideMerge(IdAllocator.layer), @@ -1188,4 +1245,224 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = ); }), ); + + const makePerModelEffortAgent = Effect.fn("makePerModelEffortAgent")(function* ( + levels: Readonly | null>>, + ) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-" }); + const agentPath = path.join(directory, "agent.mjs"); + const logPath = path.join(directory, "switches.log"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, perModelEffortAgentSource); + yield* fileSystem.writeFileString(logPath, ""); + yield* fileSystem.writeFileString(modelsPath, JSON.stringify(levels)); + return { + spawn: { command: process.execPath, args: [agentPath, logPath, modelsPath] }, + modelSwitches: fileSystem + .readFileString(logPath) + .pipe(Effect.map((log) => log.split("\n").filter((line) => line.length > 0))), + }; + }); + const createRegistryInstance = ( + instanceId: ProviderInstanceId, + spawn: { readonly command: string; readonly args: ReadonlyArray }, + version: string, + ) => + AcpRegistryDriver.create({ + instanceId, + displayName: identity.displayName, + enabled: true, + environment: [], + config: decodeSettings({ agentId: "test-agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "test-agent", + version, + distribution: "npx", + }), + resolve: () => Effect.succeed({ distribution: "npx" as const, spawn }), + }), + ); + const effortLevels = (snapshot: ServerProvider) => + snapshot.models + .map((model) => { + const effort = model.capabilities?.optionDescriptors?.find( + (option) => option.id === "effort", + ); + const levels = effort?.type === "select" ? effort.options.map((option) => option.id) : []; + return `${model.slug}:${levels.join("+")}`; + }) + .join(); + const refreshUntilEffortLevels = ( + instance: Effect.Success>, + expected: string, + ) => + Effect.gen(function* () { + const reached = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => effortLevels(snapshot) === expected), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* instance.snapshot.refresh; + yield* Fiber.join(reached); + }); + + // A session's report: the model select plus the current model's own effort levels. + const liveSession = ( + models: ReadonlyArray, + model: string, + levels: ReadonlyArray, + ) => + normalizeAcpRegistryLiveConfiguration([ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: model, + options: models.map((value) => ({ value, name: value })), + }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: levels[0]!, + options: levels.map((value) => ({ value, name: value })), + }, + ]); + + it.effect("reads each visible model's own reasoning levels before its first session", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_discovery"); + yield* (yield* TestProviderHost.TestProviderHostSettings).set({ + ...DEFAULT_SERVER_SETTINGS, + favorites: [{ provider: instanceId, model: "fav" }], + providerModelPreferences: { [instanceId]: { hiddenModels: ["hidden"], modelOrder: [] } }, + }); + const agent = yield* makePerModelEffortAgent({ + default: ["medium", "high"], + plain: null, + other: ["low", "high"], + hidden: ["low"], + fav: ["none", "max"], + }); + const instance = yield* createRegistryInstance(instanceId, agent.spawn, "1.0.0"); + + yield* refreshUntilEffortLevels( + instance, + "default:medium+high,plain:,other:low+high,hidden:,fav:none+max", + ); + // Favorites first, hidden models skipped, then the agent's own model restored. + expect(yield* agent.modelSwitches).toEqual(["fav", "plain", "other", "default"]); + + // What a live session reports for a model outranks what discovery read for it. + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const models = ["default", "plain", "other", "hidden", "fav"]; + const live = yield* instance.snapshot.streamChanges.pipe( + Stream.filter( + (snapshot) => + effortLevels(snapshot) === "default:high,plain:,other:xhigh,hidden:,fav:none+max", + ), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "other", ["xhigh"]), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "default", ["high"]), + ); + expect(Option.isSome(yield* Fiber.join(live))).toBe(true); + }), + ); + + it.effect("reads every model of a catalog larger than one discovery batch in one refresh", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_large_catalog"); + const others = Array.from({ length: 30 }, (_, index) => `model-${index}`); + yield* (yield* TestProviderHost.TestProviderHostSettings).set({ + ...DEFAULT_SERVER_SETTINGS, + providerModelPreferences: { + [instanceId]: { hiddenModels: [], modelOrder: [...others, "opus"] }, + }, + }); + const agent = yield* makePerModelEffortAgent({ + sonnet: ["medium"], + ...Object.fromEntries(others.map((slug) => [slug, ["low"]])), + opus: ["high", "max"], + }); + const instance = yield* createRegistryInstance(instanceId, agent.spawn, "1.0.0"); + + yield* refreshUntilEffortLevels( + instance, + ["sonnet:medium", ...others.map((slug) => `${slug}:low`), "opus:high+max"].join(), + ); + expect(yield* agent.modelSwitches).toEqual([...others, "opus", "sonnet"]); + }), + ); + + it.effect("keeps discovered reasoning levels across restarts until the agent updates", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acpRegistry_persisted"); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const agent = yield* makePerModelEffortAgent({ + default: ["medium", "high"], + other: ["low", "high"], + }); + const runInstance = ( + version: string, + expected: string, + then: ( + instance: Effect.Success>, + ) => Effect.Effect = () => Effect.void, + ) => + Effect.scoped( + createRegistryInstance(instanceId, agent.spawn, version).pipe( + Effect.tap((instance) => refreshUntilEffortLevels(instance, expected)), + Effect.flatMap(then), + ), + ); + + yield* runInstance("1.0.0", "default:medium+high,other:low+high"); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + // Reused after a restart; a live session then replaces the stored levels. + yield* runInstance("1.0.0", "default:medium+high,other:low+high", (instance) => + Effect.gen(function* () { + const replaced = yield* instance.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => effortLevels(snapshot) === "default:high,other:xhigh"), + Stream.runHead, + Effect.forkScoped({ startImmediately: true }), + ); + const models = ["default", "other"]; + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "other", ["xhigh"]), + ); + yield* coordinator.publishLiveConfiguration( + instanceId, + liveSession(models, "default", ["high"]), + ); + yield* Fiber.join(replaced); + // The session ends with this instance; only the stored levels remain. + yield* coordinator.clearLiveConfiguration(instanceId); + }), + ); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + yield* runInstance("1.0.0", "default:medium+high,other:xhigh"); + expect(yield* agent.modelSwitches).toEqual(["other", "default"]); + + // An agent update makes every stored level stale. + yield* runInstance("2.0.0", "default:medium+high,other:low+high"); + expect(yield* agent.modelSwitches).toEqual(["other", "default", "other", "default"]); + }), + ); }); diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 46d8ed3219aa4..33c5ab9a46663 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -53,6 +53,7 @@ import { type AcpRegistryConfigurationProbe, type AcpRegistryConfigurationProbeResult, type AcpRegistryLiveConfiguration, + type AcpRegistryModelDiscovery, deleteAcpRegistrySession, disableAcpRegistryProvider, listAcpRegistrySessions, @@ -65,6 +66,12 @@ import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; import * as AcpRegistryAuth from "./auth.ts"; import * as AcpRegistryAuthenticationState from "./authenticationState.ts"; +import { + acpRegistryCurrentModelOptions, + acpRegistryModelsToDiscover, + makeAcpRegistryLearnedModelOptionsStore, + withAcpRegistryLearnedModelOptions, +} from "./learnedModelOptions.ts"; const DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); const decodeSettings = Schema.decodeSync(AcpRegistrySettings); @@ -518,6 +525,9 @@ export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.check readonly settings: AcpRegistrySettings; readonly cwd: string; readonly environment: NodeJS.ProcessEnv; + readonly modelDiscovery?: Omit & { + readonly onProbed: (provider: ServerProvider) => Effect.Effect>; + }; }, probeConfiguration: AcpRegistryConfigurationProbe, ): Effect.fn.Return { @@ -544,12 +554,25 @@ export const checkAcpRegistryProviderStatus = Effect.fn("AcpRegistryDriver.check inspection: inspected.success, }); } + const inspection = inspected.success; + const modelDiscovery = input.modelDiscovery; const probed = yield* Effect.result( probeConfiguration({ instanceId: input.instanceId, settings: input.settings, cwd: input.cwd, environment: providerProbeEnvironment(input.environment), + ...(modelDiscovery === undefined + ? {} + : { + modelDiscovery: { + onProbed: (probe) => + modelDiscovery.onProbed( + buildCheckedAcpRegistrySnapshot({ ...input, checkedAt, inspection, probe }), + ), + onDiscovered: modelDiscovery.onDiscovered, + }, + }), }), ); return Result.isFailure(probed) @@ -688,26 +711,31 @@ export const AcpRegistryDriver: ProviderDriver>([]); - const applyLiveConfiguration = ( + // reported by sessions and probe discovery are kept here and on disk. + const learnedModelOptions = yield* makeAcpRegistryLearnedModelOptionsStore({ + cacheDir: host.paths.providerStatusCacheDir, + instanceId, + settings: effectiveConfig, + }); + const applyLiveConfiguration = Effect.fn("AcpRegistryDriver.applyLiveConfiguration")(function* ( provider: ServerProvider, configuration: AcpRegistryLiveConfiguration, - ) => - Ref.modify(learnedModels, (learned) => { - const next = applyAcpRegistryLiveConfiguration( - provider, - configuration, - effectiveConfig.customModels, - learned.length > 0 ? learned : provider.models, - ); - return [next, next.models === provider.models ? learned : next.models]; - }); - const clearLearnedModels = Ref.set(learnedModels, []); + ) { + const reported = acpRegistryCurrentModelOptions(configuration); + if (reported !== undefined) { + yield* learnedModelOptions.learn(reported.modelId, reported.options, "live"); + } + return withAcpRegistryLearnedModelOptions( + applyAcpRegistryLiveConfiguration(provider, configuration, effectiveConfig.customModels), + yield* learnedModelOptions.get, + ); + }); + const clearLearnedModels = learnedModelOptions.clear; const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* ( input: ServerProvider, ) { if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false); + if (input.installed) yield* learnedModelOptions.setVersion(input.version); const provider = input.enabled && input.installed && @@ -715,26 +743,22 @@ export const AcpRegistryDriver: ProviderDriver { - const withCommands = applyAcpRegistryAvailableCommands(provider, commands); - return Option.match(configuration, { - onNone: () => Effect.succeed(withCommands), - onSome: (liveConfiguration) => - applyLiveConfiguration(withCommands, liveConfiguration), - }).pipe( - Effect.map((withConfiguration) => - applyAcpRegistryUrlAuthAction(withConfiguration, authAction), - ), - ); - }), - ); + if (Option.isNone(runtimeCoordinator)) { + return withAcpRegistryLearnedModelOptions(provider, yield* learnedModelOptions.get); + } + const coordinator = runtimeCoordinator.value; + const withCommands = applyAcpRegistryAvailableCommands( + provider, + yield* coordinator.getAvailableCommands(instanceId), + ); + const configuration = yield* coordinator.getLiveConfiguration(instanceId); + const withConfiguration = Option.isSome(configuration) + ? yield* applyLiveConfiguration(withCommands, configuration.value) + : withAcpRegistryLearnedModelOptions(withCommands, yield* learnedModelOptions.get); + return applyAcpRegistryUrlAuthAction( + withConfiguration, + yield* coordinator.getUrlAuthAction(instanceId), + ); }); // A local executable's version comes only from probing it, so readiness checks reuse the last report. const reportedLocalVersion = yield* Ref.make(null); @@ -751,19 +775,48 @@ export const AcpRegistryDriver: ProviderDriver