From 3b3255ccecf75db4c2da996eb153dca77373ff35 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 23:37:53 -0800 Subject: [PATCH 01/74] fix(server): queued messages stay visible when a restart cancels their started run (#41307) --- .../orchestration-v2/ProjectionStore.test.ts | 17 +++ .../src/orchestration-v2/ProjectionStore.ts | 23 +++- .../src/orchestration-v2/ThreadFind.test.ts | 3 +- .../src/orchestration-v2/ThreadSearch.test.ts | 20 +++- .../src/orchestration-v2/ThreadSearch.ts | 5 +- .../state/orchestrationV2Projection.test.ts | 8 +- .../src/orchestrationV2Timeline.test.ts | 110 ++++++++++-------- .../shared/src/orchestrationV2Timeline.ts | 17 +-- 8 files changed, 137 insertions(+), 66 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index f13f3f05409ba..636e69e7574b0 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -5679,6 +5679,23 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ); } + // Recovery cancels a run that had started; its delivered queued message stays. + const setCancelledStartedAt = (startedAt: string | null) => sql` + UPDATE orchestration_v2_projection_runs + SET payload_json = json_set(payload_json, '$.startedAt', ${startedAt}) + WHERE run_id = ${cancelledRunId} + `; + yield* setCancelledStartedAt(nowIso); + const startedCancelledSnapshot = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: sqlPageLimit, + }); + assert.isTrue( + startedCancelledSnapshot.projection.visibleTurnItems.some((row) => + String(row.sourceItemId).includes(":cancelled:"), + ), + ); + yield* setCancelledStartedAt(null); + // A steer moves the cancelled queued message outside the window. const steeredItemId = "turn-item:bounded-sql-history:steered-output"; const steeredRunId = RunId.make("run:bounded-sql-history:1000"); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2278284d7fde7..84458e644e509 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -3461,6 +3461,7 @@ export const layer: Layer.Layer = ) ) AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn' + AND (run.status = 'queued' OR json_extract(run.payload_json, '$.startedAt') IS NULL) ) AND ( ${window.requiredRunId ?? null} IS NULL @@ -7374,7 +7375,9 @@ export const layer: Layer.Layer = const [hidingRuns, superseded] = yield* Effect.all([ sql<{ id: RunId; status: OrchestrationV2Run["status"] }>` SELECT run_id AS id, status FROM orchestration_v2_projection_runs - WHERE thread_id = ${threadId} AND status IN ('rolled_back', 'queued', 'cancelled')`, + WHERE thread_id = ${threadId} + AND (status IN ('rolled_back', 'queued') + OR (status = 'cancelled' AND json_extract(payload_json, '$.startedAt') IS NULL))`, sql<{ runId: RunId; rootNodeId: NodeId; status: "superseded" }>` SELECT run_id AS runId, root_node_id AS rootNodeId, status FROM orchestration_v2_projection_run_attempts @@ -7396,8 +7399,8 @@ export const layer: Layer.Layer = })), }); // Only these runs can hide rows: every row of a rolled-back run, the queued turn of a - // queued or cancelled run, and the stop result of a replaced attempt. So the hidden rows - // are found without reading the thread. + // queued run or a cancelled one that never started, and the stop result of a replaced attempt. + // So the hidden rows are found without reading the thread. const stoppedRuns = new Set(stopRequests.map((row) => row.run_id)); const runsWithStatus = (...statuses: ReadonlyArray) => hidingRuns.flatMap((run) => (statuses.includes(run.status) ? [String(run.id)] : [])); @@ -8672,6 +8675,13 @@ export const layer: Layer.Layer = AND held.type = 'user_message' AND json_valid(held.payload_json) AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' + -- A started run delivered its queued input; only held rows load the run's payload. + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs AS started + WHERE started.run_id = held.run_id + AND started.status <> 'queued' + AND json_extract(started.payload_json, '$.startedAt') IS NOT NULL + ) ) ELSE 0 END AS item_count @@ -8692,6 +8702,13 @@ export const layer: Layer.Layer = AND held.type = 'user_message' AND json_valid(held.payload_json) AND json_extract(held.payload_json, '$.inputIntent') = 'queued_turn' + -- A started run delivered its queued input; only held rows load the run's payload. + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs AS started + WHERE started.run_id = held.run_id + AND started.status <> 'queued' + AND json_extract(started.payload_json, '$.startedAt') IS NOT NULL + ) ) END) FROM orchestration_v2_projection_runs r INDEXED BY orchestration_v2_projection_runs_hidden_items_idx diff --git a/apps/server/src/orchestration-v2/ThreadFind.test.ts b/apps/server/src/orchestration-v2/ThreadFind.test.ts index 6c6d0232bfce7..60c91be1065c9 100644 --- a/apps/server/src/orchestration-v2/ThreadFind.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFind.test.ts @@ -651,7 +651,8 @@ describe("V2 thread find", () => { Effect.gen(function* () { const projection = yield* setup; const queuedRunId = RunId.make("queued:cancelled"); - yield* commit([run(threadId, queuedRunId, 2, "cancelled")]); + const cancelled = run(threadId, queuedRunId, 2, "cancelled"); + yield* commit([{ ...cancelled, payload: { ...cancelled.payload, startedAt: null } }]); const queued = item("cancelled", 1, "needle", "user_message"); if (queued.type !== "user_message") return; const answer = item("async-answer:question", 2, "needle", "user_message"); diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 399224533089d..e545d40633643 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -746,7 +746,8 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { const queued = ThreadId.make("thread:queued"); const stopped = ThreadId.make("thread:stopped"); const recovered = ThreadId.make("thread:recovered"); - const run = (owner: ThreadId, status: "rolled_back" | "cancelled") => + const restarted = ThreadId.make("thread:restarted"); + const run = (owner: ThreadId, status: "rolled_back" | "cancelled", started = true) => ({ id: EventId.make(`run:${owner}`), type: "run.created", @@ -767,7 +768,7 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { activeAttemptId: null, status, requestedAt: at(1), - startedAt: at(1), + startedAt: started ? at(1) : null, completedAt: at(2), checkpointId: null, contextHandoffId: null, @@ -818,7 +819,7 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { runId: RunId.make(`run:${rewound}`), }), thread(queued, project), - run(queued, "cancelled"), + run(queued, "cancelled", false), message(queued, "queued-prompt", "user", "then mount the albatross drive", { runId: RunId.make(`run:${queued}`), }), @@ -840,6 +841,13 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { runId: RunId.make(`run:${recovered}`), }), shown(recovered, "recovered-reply", "reply"), + // A restart cancels a turn that already took its queued prompt. + thread(restarted, project), + run(restarted, "cancelled"), + message(restarted, "delivered-prompt", "user", "then label the albatross drive", { + runId: RunId.make(`run:${restarted}`), + }), + shown(restarted, "delivered-prompt", "queued_turn"), ], projections.apply, { discard: true }, @@ -848,7 +856,11 @@ it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => { (yield* search.search({ query: "albatross" })).matches .map((match) => match.messageId) .sort(), - [MessageId.make("recovered-reply"), MessageId.make("stopped-prompt")], + [ + MessageId.make("delivered-prompt"), + MessageId.make("recovered-reply"), + MessageId.make("stopped-prompt"), + ], ); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index 3ad48b26f172d..f3f8c6061dbe7 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -293,7 +293,10 @@ export const messageHitsQuery = ( SELECT 1 FROM orchestration_v2_projection_turn_items AS items WHERE items.run_id = runs.run_id AND json_extract(items.payload_json, '$.messageId') = messages.message_id - AND json_extract(items.payload_json, '$.inputIntent') IS NOT 'queued_turn' + AND ( + json_extract(items.payload_json, '$.inputIntent') IS NOT 'queued_turn' + OR json_extract(runs.payload_json, '$.startedAt') IS NOT NULL + ) ) ) ) diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts index 16301157a6a4e..6436de7c7d907 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts @@ -486,7 +486,13 @@ describe("applyOrchestrationV2ProjectionEvent", () => { it("hides a steer that fell back to the queue until its run starts", () => { const queuedRunId = RunId.make("run-requeued-steer"); - const queuedRun = { ...run, id: queuedRunId, ordinal: 2, status: "queued" } as const; + const queuedRun = { + ...run, + id: queuedRunId, + ordinal: 2, + status: "queued", + startedAt: null, + } as const; const reply = commandItem("item-reply", "reply", 102); const steer: OrchestrationV2TurnItem = { id: TurnItemId.make("item-steer"), diff --git a/packages/shared/src/orchestrationV2Timeline.test.ts b/packages/shared/src/orchestrationV2Timeline.test.ts index c2b7a0c920159..18a59c28a8fbe 100644 --- a/packages/shared/src/orchestrationV2Timeline.test.ts +++ b/packages/shared/src/orchestrationV2Timeline.test.ts @@ -1,4 +1,5 @@ import { NodeId, RunId } from "@t3tools/contracts"; +import { DateTime } from "effect"; import { describe, expect, it } from "vite-plus/test"; import { @@ -91,62 +92,73 @@ describe.each([ ).toBe(true); }); - it.each([ + it.each<{ + status: VisibilityInput["runs"][number]["status"]; + startedAt?: string; + hidden: string[]; + }>([ ...ordinaryStatuses.map((status) => ({ status, hidden: [] })), { status: "queued", hidden: ["queued"] }, { status: "cancelled", hidden: ["queued"] }, + { status: "cancelled", startedAt: "2026-11-23T06:11:54.535Z", hidden: [] }, { status: "rolled_back", hidden: ["queued", "start", "steer", "promoted", "legacy", "assistant", "request", "result"], }, - ] satisfies ReadonlyArray<{ - status: VisibilityInput["runs"][number]["status"]; - hidden: string[]; - }>)("keeps the correct transcript rows for $status runs", ({ status, hidden }) => { - const rows = [ - { id: "queued", type: "user_message", inputIntent: "queued_turn", runId, nodeId }, - { id: "start", type: "user_message", inputIntent: "turn_start", runId, nodeId }, - { id: "steer", type: "user_message", inputIntent: "steer", runId, nodeId }, - { - id: "promoted", - type: "user_message", - inputIntent: "promoted_queued_to_steer", - runId, - nodeId, - }, - { id: "legacy", type: "user_message", runId, nodeId }, - { id: "assistant", type: "assistant_message", inputIntent: "queued_turn", runId, nodeId }, - { id: "request", type: "run_interrupt_request", runId, nodeId }, - { id: "result", type: "run_interrupt_result", runId, nodeId }, - { id: "null", type: "user_message", inputIntent: "queued_turn", runId: null, nodeId }, - { - id: "missing", - type: "user_message", - inputIntent: "queued_turn", - runId: otherRunId, - nodeId, - }, - ] satisfies ReadonlyArray; - const input = { - runs: [{ id: runId, status }], - attempts: [], - items: rows, - } satisfies VisibilityInput; - expect(rows.filter((item) => isVisible({ ...input, item })).map((item) => item.id)).toEqual( - [ - "queued", - "start", - "steer", - "promoted", - "legacy", - "assistant", - "request", - "result", - "null", - "missing", - ].filter((id) => !hidden.some((hiddenId) => hiddenId === id)), - ); - }); + ])( + "keeps the correct transcript rows for $status runs (started $startedAt)", + ({ status, startedAt, hidden }) => { + const rows = [ + { id: "queued", type: "user_message", inputIntent: "queued_turn", runId, nodeId }, + { id: "start", type: "user_message", inputIntent: "turn_start", runId, nodeId }, + { id: "steer", type: "user_message", inputIntent: "steer", runId, nodeId }, + { + id: "promoted", + type: "user_message", + inputIntent: "promoted_queued_to_steer", + runId, + nodeId, + }, + { id: "legacy", type: "user_message", runId, nodeId }, + { id: "assistant", type: "assistant_message", inputIntent: "queued_turn", runId, nodeId }, + { id: "request", type: "run_interrupt_request", runId, nodeId }, + { id: "result", type: "run_interrupt_result", runId, nodeId }, + { id: "null", type: "user_message", inputIntent: "queued_turn", runId: null, nodeId }, + { + id: "missing", + type: "user_message", + inputIntent: "queued_turn", + runId: otherRunId, + nodeId, + }, + ] satisfies ReadonlyArray; + const input = { + runs: [ + { + id: runId, + status, + ...(startedAt === undefined ? {} : { startedAt: DateTime.makeUnsafe(startedAt) }), + }, + ], + attempts: [], + items: rows, + } satisfies VisibilityInput; + expect(rows.filter((item) => isVisible({ ...input, item })).map((item) => item.id)).toEqual( + [ + "queued", + "start", + "steer", + "promoted", + "legacy", + "assistant", + "request", + "result", + "null", + "missing", + ].filter((id) => !hidden.some((hiddenId) => hiddenId === id)), + ); + }, + ); it.each([ { name: "empty history", runs: [], attempts: [] }, diff --git a/packages/shared/src/orchestrationV2Timeline.ts b/packages/shared/src/orchestrationV2Timeline.ts index e651dbfb01653..292a0dfbbb8ab 100644 --- a/packages/shared/src/orchestrationV2Timeline.ts +++ b/packages/shared/src/orchestrationV2Timeline.ts @@ -5,7 +5,8 @@ import type { OrchestrationV2UserMessageInputIntent, } from "@t3tools/contracts"; -type TimelineRun = Pick; +type TimelineRun = Pick & + Partial>; type TimelineRunAttempt = Pick; type TimelineTurnItem = Pick & { readonly inputIntent?: OrchestrationV2UserMessageInputIntent; @@ -38,6 +39,11 @@ function isOrchestrationV2SupersededInterrupt(input: { return !hasMatchingRequest; } +// A run that started received its queued input, even if recovery cancelled it later. +function isHeldRun(run: TimelineRun): boolean { + return run.status === "queued" || (run.status === "cancelled" && run.startedAt == null); +} + export function isOrchestrationV2TurnItemVisible(input: { readonly item: TimelineTurnItem; readonly runs: ReadonlyArray; @@ -53,14 +59,12 @@ export function isOrchestrationV2TurnItemVisible(input: { } // A steer can return to the queue before delivery. Keep its retained item out - // of conversation history until its run starts; cancelled queued inputs stay hidden. + // of conversation history until its run starts; cancelled undelivered inputs stay hidden. if ( item.type === "user_message" && item.inputIntent === "queued_turn" && item.runId !== null && - input.runs.some( - (run) => run.id === item.runId && (run.status === "queued" || run.status === "cancelled"), - ) + input.runs.some((run) => run.id === item.runId && isHeldRun(run)) ) { return false; } @@ -79,8 +83,7 @@ export function createOrchestrationV2TurnItemVisibility(input: { }): (item: TimelineTurnItem) => boolean { const statuses = new Map(); for (const run of input.runs) { - if (run.status === "rolled_back" || run.status === "cancelled" || run.status === "queued") - statuses.set(run.id, run.status); + if (run.status === "rolled_back" || isHeldRun(run)) statuses.set(run.id, run.status); else statuses.delete(run.id); } const supersededRoots = new Map< From 9cf81e2a6e717510708713fa951d368095a1de71 Mon Sep 17 00:00:00 2001 From: fixfon <12512757+fixfon@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:39:47 +0300 Subject: [PATCH 02/74] fix(desktop): annotation Select picks elements inside open shadow roots (#23180) Co-authored-by: Julius Marminge --- apps/desktop/src/preview/PickPreload.ts | 18 +-- apps/desktop/src/preview/PickTarget.test.ts | 121 ++++++++++++++++++++ apps/desktop/src/preview/PickTarget.ts | 22 ++++ 3 files changed, 154 insertions(+), 7 deletions(-) create mode 100644 apps/desktop/src/preview/PickTarget.test.ts create mode 100644 apps/desktop/src/preview/PickTarget.ts diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index c7599d217b1a1..5113617a8f324 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -28,6 +28,7 @@ import { type StrokeGeometry, } from "./AnnotationStroke.ts"; import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts"; +import { pickElementAtPoint } from "./PickTarget.ts"; import { installRecordingCursor } from "./RecordingCursor.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS } from "./RecordingInput.ts"; import { @@ -320,13 +321,16 @@ function isAnnotationNode(element: Element): boolean { } function pickFromPoint(clientX: number, clientY: number): Element | null { - for (const candidate of document.elementsFromPoint(clientX, clientY)) { - if (!(candidate instanceof Element)) continue; - if (isAnnotationNode(candidate) || candidate.hasAttribute(INPUT_LAYER_ATTRIBUTE)) continue; - if (candidate === document.documentElement || candidate === document.body) continue; - return candidate; - } - return null; + return pickElementAtPoint( + document, + clientX, + clientY, + (element) => + isAnnotationNode(element) || + element.hasAttribute(INPUT_LAYER_ATTRIBUTE) || + element === document.documentElement || + element === document.body, + ); } function describeRawElement(element: Element): string { diff --git a/apps/desktop/src/preview/PickTarget.test.ts b/apps/desktop/src/preview/PickTarget.test.ts new file mode 100644 index 0000000000000..cb245e9565a1c --- /dev/null +++ b/apps/desktop/src/preview/PickTarget.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { pickElementAtPoint } from "./PickTarget.ts"; + +// Models the DOM contract the picker relies on: hit-testing covers the whole page, and each +// `elementsFromPoint` retargets the hits against the scope it is called on, like Blink does. +class FakeElement { + shadowRoot: FakeScope | null = null; + readonly label: string; + readonly scope: FakeScope; + + constructor(label: string, scope: FakeScope) { + this.label = label; + this.scope = scope; + scope.members.add(this); + } +} + +class FakeScope { + readonly members = new Set(); + readonly host: FakeElement | null; + private readonly page: FakePage; + + constructor(page: FakePage, host: FakeElement | null) { + this.page = page; + this.host = host; + } + + contains(element: FakeElement): boolean { + return this.members.has(element); + } + + elementsFromPoint(): FakeElement[] { + const elements: FakeElement[] = []; + for (const hit of this.page.hits) { + const element = this.retarget(hit); + if (elements.at(-1) !== element) elements.push(element); + } + if (elements.at(-1) !== this.page.html) elements.push(this.page.html); + return elements; + } + + private retarget(target: FakeElement): FakeElement { + let element = target; + while (element.scope.host && !element.scope.encloses(this)) element = element.scope.host; + return element; + } + + private encloses(scope: FakeScope): boolean { + for (let current: FakeScope | null = scope; current; current = current.host?.scope ?? null) { + if (current === this) return true; + } + return false; + } +} + +class FakePage { + hits: FakeElement[] = []; + readonly overlays = new Set(); + readonly document = new FakeScope(this, null); + readonly html = new FakeElement("html", this.document); + readonly body = new FakeElement("body", this.document); + + attachShadow(host: FakeElement, mode: "open" | "closed"): FakeScope { + const root = new FakeScope(this, host); + if (mode === "open") host.shadowRoot = root; + return root; + } + + pick(): FakeElement | null { + return pickElementAtPoint( + this.document, + 0, + 0, + (element) => this.overlays.has(element) || element === this.html || element === this.body, + ); + } +} + +describe("pickElementAtPoint", () => { + it("picks the element inside an open shadow root instead of its host", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + const button = new FakeElement("button", page.attachShadow(host, "open")); + page.hits = [button, host, page.body, page.html]; + + expect(page.pick()?.label).toBe("button"); + }); + + it("falls back to the host when the point misses its shadow content", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + page.attachShadow(host, "open"); + page.hits = [host, page.body, page.html]; + + expect(page.pick()?.label).toBe("shadow-demo"); + }); + + it("keeps a closed shadow root opaque", () => { + const page = new FakePage(); + const outerHost = new FakeElement("outer-host", page.document); + const outerRoot = page.attachShadow(outerHost, "open"); + const closedHost = new FakeElement("closed-host", outerRoot); + const secret = new FakeElement("secret", page.attachShadow(closedHost, "closed")); + page.hits = [secret, closedHost, outerHost, page.body, page.html]; + + expect(page.pick()?.label).toBe("closed-host"); + }); + + it("picks the page element beneath the picker overlay, never the overlay", () => { + const page = new FakePage(); + const host = new FakeElement("shadow-demo", page.document); + const button = new FakeElement("button", page.attachShadow(host, "open")); + const overlay = new FakeElement("overlay", page.document); + page.overlays.add(overlay); + const toolbar = new FakeElement("toolbar", page.attachShadow(overlay, "closed")); + page.hits = [toolbar, button, host, page.body, page.html]; + + expect(page.pick()?.label).toBe("button"); + }); +}); diff --git a/apps/desktop/src/preview/PickTarget.ts b/apps/desktop/src/preview/PickTarget.ts new file mode 100644 index 0000000000000..af689a07bedda --- /dev/null +++ b/apps/desktop/src/preview/PickTarget.ts @@ -0,0 +1,22 @@ +interface PickScope { + elementsFromPoint(x: number, y: number): ReadonlyArray; + contains(node: NoInfer): boolean; +} + +// Document hit-testing retargets shadow content to its host, so descend into open roots. +// ShadowRoot.elementsFromPoint still lists the host and the rest of the page (the overlay +// too), so only the root's own elements count. Closed roots expose no shadowRoot. +export function pickElementAtPoint | null }>( + scope: PickScope, + x: number, + y: number, + isExcluded: (element: E) => boolean, +): E | null { + for (const candidate of scope.elementsFromPoint(x, y)) { + if (!scope.contains(candidate) || isExcluded(candidate)) continue; + const inner = + candidate.shadowRoot && pickElementAtPoint(candidate.shadowRoot, x, y, isExcluded); + return inner ?? candidate; + } + return null; +} From 65cd6446233a8001c8c4f8e06cb4eee987cac0e9 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 01:44:31 -0600 Subject: [PATCH 03/74] fix(web): archive folders with leading or repeated slashes show their names (#41301) Co-authored-by: Julius Marminge --- .../AttachmentFilePreview.browser.test.tsx | 57 ++++++++++++------- .../web/src/components/files/BinaryViewer.tsx | 27 ++++++--- 2 files changed, 54 insertions(+), 30 deletions(-) diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 9316935ba2df0..77e339925c97e 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -238,37 +238,52 @@ describe("bounded binary previews", () => { } }); - it("can leave an archive folder with a repeated separator", async () => { + it("names archive folders whose paths have leading or repeated slashes", async () => { const bytes = new Uint8Array(2048); const write = (offset: number, value: string) => bytes.set(new TextEncoder().encode(value), offset); - write(0, "a//hello.txt"); - write(124, "00000000014\0"); - bytes.fill(32, 148, 156); - write(156, "0"); - write( - 148, - bytes - .subarray(0, 512) - .reduce((sum, byte) => sum + byte, 0) - .toString(8) - .padStart(6, "0") + "\0 ", - ); - write(512, "nested hello"); + const member = (offset: number, name: string, content: string) => { + write(offset, name); + write(offset + 124, content.length.toString(8).padStart(11, "0") + "\0"); + bytes.fill(32, offset + 148, offset + 156); + write(offset + 156, "0"); + write( + offset + 148, + bytes + .subarray(offset, offset + 512) + .reduce((sum, byte) => sum + byte, 0) + .toString(8) + .padStart(6, "0") + "\0 ", + ); + write(offset + 512, content); + }; + member(0, "/a//hello.txt", "nested hello"); + member(1024, "a/hello.txt", "plain hello"); const src = URL.createObjectURL(new Blob([bytes])); try { await using screen = await render(); - const child = () => screen.container.querySelector("tbody button"); - await vi.waitFor(() => expect(child()?.textContent).toBe("a"), 10_000); - await act(() => child()!.click()); - await act(() => child()!.click()); - await vi.waitFor(() => expect(child()?.textContent).toBe("hello.txt")); + const buttons = () => [ + ...screen.container.querySelectorAll("tbody button"), + ]; + const rows = () => buttons().map((button) => button.textContent); + const back = () => + screen.container.querySelector('[aria-label="Back to archive"]')!; + const preview = () => screen.container.querySelector("pre")?.textContent; + await vi.waitFor(() => expect(rows()).toEqual(["a"]), 10_000); + await act(() => buttons()[0]!.click()); + await vi.waitFor(() => expect(rows()).toEqual(["hello.txt", "hello.txt"])); + await act(() => buttons()[0]!.click()); + await vi.waitFor(() => expect(preview()).toContain("nested hello"), 10_000); + await act(() => back().click()); + await act(() => buttons()[1]!.click()); + await vi.waitFor(() => expect(preview()).toContain("plain hello"), 10_000); + await act(() => back().click()); + await vi.waitFor(() => expect(rows()).toEqual(["hello.txt", "hello.txt"])); const parent = () => screen.container.querySelector('[aria-label="Parent folder"]')!; await act(() => parent().click()); - await act(() => parent().click()); expect(parent().disabled).toBe(true); - expect(child()?.textContent).toBe("a"); + expect(rows()).toEqual(["a"]); } finally { URL.revokeObjectURL(src); } diff --git a/apps/web/src/components/files/BinaryViewer.tsx b/apps/web/src/components/files/BinaryViewer.tsx index 0151e9f08c0a7..63a2f119056c1 100644 --- a/apps/web/src/components/files/BinaryViewer.tsx +++ b/apps/web/src/components/files/BinaryViewer.tsx @@ -202,19 +202,28 @@ export default function BinaryViewer(props: { }; const children = new Map< string, - { path: string; directory: boolean; size: number; modified: string | null } + { path: string; entryPath: string; directory: boolean; size: number; modified: string | null } >(); for (const item of archive?.entries ?? []) { - if (!item.path.startsWith(folder)) continue; - const rest = item.path.slice(folder.length).replace(/\/$/, ""); + const name = item.path.replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/"); + if (!name.startsWith(folder)) continue; + const rest = name.slice(folder.length); if (!rest) continue; const slash = rest.indexOf("/"); - const path = slash < 0 ? item.path.replace(/\/$/, "") : `${folder}${rest.slice(0, slash)}`; + const path = slash < 0 ? name : `${folder}${rest.slice(0, slash)}`; const directory = slash >= 0 || item.directory; - const key = `${path}${directory ? "/" : ""}`; + // Files stay keyed by their raw name so `/a.txt` and `a.txt` remain two openable rows. + const key = directory ? `d:${path}` : `f:${item.path}`; const previous = children.get(key); - if (previous) previous.size += item.size; - else children.set(key, { path, directory, size: item.size, modified: item.modified }); + if (previous && directory) previous.size += item.size; + else + children.set(key, { + path, + entryPath: item.path, + directory, + size: item.size, + modified: item.modified, + }); } return (
@@ -347,7 +356,7 @@ export default function BinaryViewer(props: { ) .map((item) => ( @@ -359,7 +368,7 @@ export default function BinaryViewer(props: { else { setSelectedPath(item.path); setEntry(null); - send({ type: "entry", path: item.path }); + send({ type: "entry", path: item.entryPath }); } }} > From fcdaef886a91bd92e824db6b8670be1fbeb838fe Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 00:00:57 -0800 Subject: [PATCH 04/74] fix(server): provider updates keep running when the client disconnects (#27261) --- .../providerMaintenanceRunner.test.ts | 210 ++++++++++++------ .../src/provider/providerMaintenanceRunner.ts | 28 ++- apps/server/src/server.ts | 2 + apps/server/src/ws.ts | 9 +- 4 files changed, 166 insertions(+), 83 deletions(-) diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 985347a66e96b..6fec324302fea 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -8,12 +8,14 @@ import { } from "@t3tools/contracts"; import { ServerProviderUpdateError } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +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 Layer from "effect/Layer"; import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -250,27 +252,25 @@ const makeTestRunner = ( }, latestVersions: Layer.Layer = ProviderLatestVersions.layer, ) => - Effect.service(ProviderMaintenanceRunner.ProviderMaintenanceRunner).pipe( - Effect.provide( - ProviderMaintenanceRunner.layer.pipe( - Layer.provide( - Layer.mergeAll( - Layer.succeed(ProviderRegistry.ProviderRegistry, registry), - Layer.succeed(ModelManifest.ModelManifest, { - current: Effect.succeed(manifest), - refresh: Effect.succeed(manifest), - forceRefresh: Effect.succeed(manifest), - refreshOnDemand: Effect.succeed(manifest), - refreshInBackground: Effect.void, - }), - latestVersions, - // Layers memoize by reference, so a test that provides the gate shares it. - ProviderInstallationGate.layer, - ), + Layer.build( + ProviderMaintenanceRunner.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(ProviderRegistry.ProviderRegistry, registry), + Layer.succeed(ModelManifest.ModelManifest, { + current: Effect.succeed(manifest), + refresh: Effect.succeed(manifest), + forceRefresh: Effect.succeed(manifest), + refreshOnDemand: Effect.succeed(manifest), + refreshInBackground: Effect.void, + }), + latestVersions, + // Layers memoize by reference, so a test that provides the gate shares it. + ProviderInstallationGate.layer, ), ), ), - ); + ).pipe(Effect.map(Context.get(ProviderMaintenanceRunner.ProviderMaintenanceRunner))); function layerFailingLatestLookupAfterFirst() { let lookups = 0; @@ -905,14 +905,15 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("an interrupted update ends failed instead of running forever", () => { + it.effect("an update stopped by server shutdown ends failed instead of running forever", () => { const started = Deferred.makeUnsafe(); return Effect.gen(function* () { const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); - const updater = yield* makeTestRunner(registry); - const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + const serverScope = yield* Scope.make(); + const updater = yield* makeTestRunner(registry).pipe(Scope.provide(serverScope)); + yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); yield* Deferred.await(started); - yield* Fiber.interrupt(update); + yield* Scope.close(serverScope, Exit.void); const last = (yield* Ref.get(updateStatesRef)).at(-1); assert.deepStrictEqual( [last?.status, last?.message], @@ -931,11 +932,12 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("a request dropped while the final state is written still records it", () => { + it.effect("a shutdown while the final state is written still records it", () => { const writing = Deferred.makeUnsafe(); const release = Deferred.makeUnsafe(); return Effect.gen(function* () { const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); + const serverScope = yield* Scope.make(); const updater = yield* makeTestRunner({ ...registry, setProviderMaintenanceActionState: (input) => @@ -945,13 +947,13 @@ describe("providerMaintenanceRunner", () => { Effect.andThen(registry.setProviderMaintenanceActionState(input)), ) : registry.setProviderMaintenanceActionState(input), - }); + }).pipe(Scope.provide(serverScope)); - const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); yield* Deferred.await(writing); - update.interruptUnsafe(); + const shutdown = yield* Scope.close(serverScope, Exit.void).pipe(Effect.forkScoped); yield* Deferred.succeed(release, undefined); - yield* Fiber.await(update); + yield* Fiber.join(shutdown); assert.strictEqual((yield* Ref.get(updateStatesRef)).at(-1)?.status, "succeeded"); }).pipe( @@ -1150,58 +1152,124 @@ describe("providerMaintenanceRunner", () => { ); }); + it.effect("finishes a queued update whose caller is interrupted", () => + Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseProvider, { + installedVersionAfterUpdate: "1.0.0", + }); + const firstFinished = yield* Deferred.make(); + let blockQueuedState = true; + const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} }; + const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} }; + const queuedStateWritten = new Promise((resolve) => { + queuedStateWrittenLatch.resolve = resolve; + }); + const releaseQueuedState = new Promise((resolve) => { + releaseQueuedStateLatch.resolve = resolve; + }); + + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: Effect.fn( + "providerMaintenanceRunner.test.blockQueuedState", + )(function* (input) { + const providers = yield* registry.setProviderMaintenanceActionState(input); + if (input.state?.status === "queued" && blockQueuedState) { + queuedStateWrittenLatch.resolve(); + yield* Effect.promise(() => releaseQueuedState); + } + if (input.state?.status === "succeeded") { + yield* Deferred.succeed(firstFinished, undefined); + } + return providers; + }), + }); + + const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); + yield* Effect.promise(() => queuedStateWritten); + blockQueuedState = false; + + yield* Fiber.interrupt(first); + releaseQueuedStateLatch.resolve(); + yield* Deferred.await(firstFinished); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ stdout: "updated" })), + ), + ), + ), + ); + it.effect( - "releases the running-provider marker when interrupted after queuing but before the lock run starts", + "keeps the update command running and records its result when the caller is interrupted", () => Effect.gen(function* () { - const { registry } = yield* makeRegistry(baseProvider, { - installedVersionAfterUpdate: "1.0.0", - }); - let blockQueuedState = true; - const queuedStateWrittenLatch: { resolve: () => void } = { resolve: () => {} }; - const releaseQueuedStateLatch: { resolve: () => void } = { resolve: () => {} }; - const queuedStateWritten = new Promise((resolve) => { - queuedStateWrittenLatch.resolve = resolve; - }); - const releaseQueuedState = new Promise((resolve) => { - releaseQueuedStateLatch.resolve = resolve; - }); + const kills: Array = []; + const spawned = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const finished = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Deferred.succeed(spawned, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Deferred.await(exit), + isRunning: Effect.succeed(true), + kill: () => Effect.sync(() => kills.push("kill")), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(encoder.encode("added 1 package")), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ), + ); - const updater = yield* makeTestRunner({ - ...registry, - setProviderMaintenanceActionState: Effect.fn( - "providerMaintenanceRunner.test.blockQueuedState", - )(function* (input) { - const providers = yield* registry.setProviderMaintenanceActionState(input); - if (input.state?.status === "queued" && blockQueuedState) { - queuedStateWrittenLatch.resolve(); - yield* Effect.promise(() => releaseQueuedState); - } - return providers; - }), - }); + yield* Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseOpenCodeProvider); + const updater = yield* makeTestRunner({ + ...registry, + setProviderMaintenanceActionState: Effect.fn( + "providerMaintenanceRunner.test.recordFinishedState", + )(function* (input) { + const providers = yield* registry.setProviderMaintenanceActionState(input); + const status = input.state?.status; + if (input.state && status !== "queued" && status !== "running") { + yield* Deferred.succeed(finished, input.state); + } + return providers; + }), + }); - const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); - yield* Effect.promise(() => queuedStateWritten); - blockQueuedState = false; + const caller = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkChild); + yield* Deferred.await(spawned); + yield* Fiber.interrupt(caller); - yield* Fiber.interrupt(first); - releaseQueuedStateLatch.resolve(); + assert.deepStrictEqual( + kills, + [], + "interrupting the updateProvider caller killed the running npm install", + ); - const second = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.exit); - assert.strictEqual(Exit.isSuccess(second), true); - if (Exit.isSuccess(second)) { - assert.strictEqual(second.value.providers[0]?.updateState?.status, "succeeded"); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("1.0.0"), - layerMockSpawner(() => ({ stdout: "updated" })), + yield* Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)); + const finalState = yield* Deferred.await(finished); + assert.strictEqual(finalState.status, "succeeded"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("0.0.0"), + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), ), - ), - ), + ); + }), ); it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index 014aa67c26df0..a09bf1ee7dbba 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -13,6 +13,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -323,6 +324,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; + const serviceScope = yield* Effect.scope; const installationGate = yield* ProviderInstallationGate.ProviderInstallationGate; const runMaintenanceCommand = ( update: ProviderMaintenanceCommandAction, @@ -685,7 +687,8 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { }, ); - return yield* commandCoordinator + // Installers cannot be safely killed mid-install, so the update outlives a disconnecting caller. + const updateFiber = yield* commandCoordinator .withCommandLock({ targetKey, lockKey: update.lockKey, @@ -693,10 +696,10 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { run: runProviderUpdate(), }) .pipe( - // A dropped request interrupts the update; a "running" state would spin until restart. + // Server shutdown interrupts the update; a "running" state would spin until restart. Effect.onInterrupt(() => Effect.gen(function* () { - // A finished state stays, even if the request drops while it is being written. + // A finished state stays, even if shutdown lands while it is being written. if (yield* Ref.get(settled)) return; yield* setUpdateState( makeUpdateState({ @@ -708,15 +711,18 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ); }).pipe(Effect.ignore), ), - Effect.mapError((error) => - isServerProviderUpdateError(error) - ? new ServerProviderUpdateError({ - provider, - reason: error.reason, - }) - : error, - ), + Effect.forkIn(serviceScope), ); + return yield* Fiber.join(updateFiber).pipe( + Effect.mapError((error) => + isServerProviderUpdateError(error) + ? new ServerProviderUpdateError({ + provider, + reason: error.reason, + }) + : error, + ), + ); }); return ProviderMaintenanceRunner.of({ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 68f32f4ecf0a9..499c1e2acc0ca 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -78,6 +78,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime"; import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger"; import * as ProviderHostLive from "./provider/ProviderHostLive.ts"; +import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; import * as DocumentText from "./provider/DocumentText.ts"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; @@ -957,6 +958,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide(layerServerSettings), Layer.provide(PreviewAutomationBroker.layer), Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(layerDesktopAppUpdate))), + Layer.provide(ProviderMaintenanceRunner.layer), Layer.provide(layerCommandReadiness), Layer.provide(ServerHttp.layerBrowserApiCors), Layer.provide(ServerHttp.layerHttpCompression), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ff783eeb57324..b6922b9e90996 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3729,6 +3729,7 @@ export const layer = Layer.unwrap( Effect.gen(function* () { const serverBrowser = yield* ServerBrowser.ServerBrowser; const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate; + const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner; const npmRelease = yield* NpmRelease.NpmRelease; const pullRequests = yield* PullRequestService.PullRequestService; const issues = yield* IssueService.IssueService; @@ -3820,7 +3821,13 @@ export const layer = Layer.unwrap( Layer.provide(DefectReporter.layer), Layer.provide(AcpRegistrySessions.layer), Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)), - Layer.provide(ProviderMaintenanceRunner.layer), + // Installs outlive the connection that started them and lock across clients. + Layer.provide( + Layer.succeed( + ProviderMaintenanceRunner.ProviderMaintenanceRunner, + providerMaintenanceRunner, + ), + ), Layer.provide(Layer.succeed(NpmRelease.NpmRelease, npmRelease)), Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)), // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs. From e20e769b0997adb6b2b3ec26e9562a3c3d55f41a Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 02:01:09 -0600 Subject: [PATCH 05/74] fix(server): reject workflow signals with conflicting destinations (#41312) Co-authored-by: Julius Marminge --- .../mcp/toolkits/workflow/handlers.test.ts | 89 ++++++++++++++----- .../src/mcp/toolkits/workflow/handlers.ts | 7 ++ 2 files changed, 73 insertions(+), 23 deletions(-) diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts index c036cb8d7e649..77b7036681ad6 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -12,29 +12,28 @@ import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; import * as WorkflowHandlers from "./handlers.ts"; import { WorkflowToolkit } from "./tools.ts"; +const handlersWith = (workflows: Partial) => + McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( + Layer.provideMerge( + Layer.mergeAll( + NodeCrypto.layer, + McpToolAccessTestkit.liveThreadsLayer, + Layer.succeed(McpInvocationContext.McpInvocationContext, { + environmentId: EnvironmentId.make("environment:workflow"), + requestNamespace: "client:workflow", + thread: undefined, + client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + capabilities: new Set(["orchestration" as const]), + issuedAt: 0, + }), + Layer.mock(Workflows.Workflows)(workflows), + ), + ), + ); + it.effect("start passes an explicit null payload through and defaults an omitted one to {}", () => Effect.gen(function* () { const payloads: Array = []; - const layerDependencies = Layer.mergeAll( - NodeCrypto.layer, - McpToolAccessTestkit.liveThreadsLayer, - Layer.succeed(McpInvocationContext.McpInvocationContext, { - environmentId: EnvironmentId.make("environment:workflow"), - requestNamespace: "client:workflow", - thread: undefined, - client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, - capabilities: new Set(["orchestration" as const]), - issuedAt: 0, - }), - Layer.mock(Workflows.Workflows)({ - start: (_workflow, input) => - Effect.sync(() => { - payloads.push(input); - return { runId: "run-1" }; - }), - get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), - }), - ); yield* Effect.gen(function* () { const toolkit = yield* WorkflowToolkit; for (const input of [{ input: null }, {}]) { @@ -49,11 +48,55 @@ it.effect("start passes an explicit null payload through and defaults an omitted } }).pipe( Effect.provide( - McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( - Layer.provideMerge(layerDependencies), - ), + handlersWith({ + start: (_workflow, input) => + Effect.sync(() => { + payloads.push(input); + return { runId: "run-1" }; + }), + get: () => Effect.succeed({ run: undefined, steps: [], references: [] } as never), + }), ), ); expect(payloads).toEqual([null, {}]); }), ); + +it.effect("signal refuses a run destination mixed with a channel destination", () => + Effect.gen(function* () { + const delivered: Array = []; + const results = yield* Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + return yield* Effect.forEach( + [ + { runId: "run-1", wait: "review", channel: "other" }, + { workflow: "other", channel: "other", runId: "run-1" }, + { runId: "run-1", wait: "review" }, + ], + (address) => + toolkit + .handle("t3_workflow", { action: "signal", value: { choice: "yes" }, ...address }) + .pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((parts) => parts.at(-1)?.result), + ), + ); + }).pipe( + Effect.provide( + handlersWith({ + signal: (address) => + Effect.sync(() => { + delivered.push(address); + return "delivered" as const; + }), + }), + ), + ); + for (const result of results.slice(0, -1)) { + expect(result).toMatchObject({ code: "invalid_request" }); + } + expect(results.at(-1)).toEqual({ delivery: "delivered" }); + expect(delivered).toEqual([{ runId: "run-1", wait: "review" }]); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index b3ccb35f28151..7ebc6ac0cf7a4 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -58,6 +58,13 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { } if (input.action === "signal") { const value = yield* required(input.value, "value"); + const byRun = input.runId !== undefined || input.wait !== undefined; + const byChannel = input.workflow !== undefined || input.channel !== undefined; + if (byRun && byChannel) { + return yield* invalid( + "Address a signal with `runId` and `wait`, or with `workflow` and `channel`, not both.", + ); + } const address = input.runId !== undefined && input.wait !== undefined ? { runId: input.runId, wait: input.wait } From 37b316ac314ebb991c498492b5f1eb036a0eed6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Hu=E1=BB=B3nh=20L=E1=BB=A3i?= Date: Mon, 23 Nov 2026 16:03:59 +0800 Subject: [PATCH 06/74] fix(desktop): declare Apple Events access for Computer Use cleanup (#33869) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- scripts/build-desktop-artifact.test.ts | 7 ++++++- scripts/build-desktop-artifact.ts | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index c9180ec3d3ae6..43e89846bded0 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -592,7 +592,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { ), ); - it.effect("declares Calendar access for hosted commands in macOS builds", () => + it.effect("declares Calendar and Apple Events access for hosted commands in macOS builds", () => Effect.gen(function* () { for (const version of ["0.1.0", "0.1.1-nightly.20261019.1"]) { for (const signed of [false, true]) { @@ -610,6 +610,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { "NSCalendarsUsageDescription", "NSCalendarsFullAccessUsageDescription", "NSCalendarsWriteOnlyAccessUsageDescription", + "NSAppleEventsUsageDescription", ]) { assert.isString(mac.extendInfo[key], `${version}, signed=${signed}: ${key}`); assert.isNotEmpty(mac.extendInfo[key]); @@ -1591,6 +1592,10 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { assert.include(entitlements, "webcredentials:clerk.example.com"); assert.include(entitlements, "webcredentials:example.clerk.accounts.dev"); assert.include(entitlements, "com.apple.security.cs.allow-jit"); + assert.match( + entitlements, + /com\.apple\.security\.automation\.apple-events<\/key>\s*/u, + ); assert.match(entitlements, /com\.apple\.security\.device\.camera<\/key>\s*/u); assert.match(entitlements, /com\.apple\.security\.device\.audio-input<\/key>\s*/u); assert.notInclude(entitlements, "keychain-access-groups"); diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 746ac826005b3..90cc9e1118235 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -1395,6 +1395,8 @@ ${associatedDomains} com.apple.security.cs.disable-library-validation + com.apple.security.automation.apple-events + + + + +
+${action} +
+
+
+ +${status} + +> Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. + +
+
+
`; + describe("evaluatePullRequestWatch", () => { it.each(["pending", "success"] as const)( "reports a required rebase once with %s CI", @@ -913,6 +932,76 @@ describe("evaluatePullRequestWatch", () => { assert.deepEqual(evaluatePullRequestWatch(report.next, detail(), comments).changes, []); }); + it("skips CodeRabbit review acknowledgements and wakes once for their outcome edits", () => { + const current = ` +
+✅ Actions performed + +Review triggered. + +
`; + // GitHub's GraphQL API names bots without the "[bot]" suffix that its REST API adds. + for (const [login, acknowledgement] of [ + ["coderabbitai[bot]", codeRabbitReply("Review triggered.")], + ["coderabbitai[bot]", codeRabbitReply("Full review triggered.")], + ["coderabbitai[bot]", current], + ["coderabbitai", current], + ] as const) { + const queued = { + ...remark(login, "2026-10-02T12:06:00Z", acknowledgement), + kind: "issue-comment" as const, + path: null, + }; + const watching = watch({ headSha: "aaaaaaaaaa", wakes: 2 }); + const progress = evaluatePullRequestWatch(watching, detail(), [queued]); + assert.deepEqual(progress.changes, []); + assert.equal(progress.next.remarksThrough, queued.createdAt); + assert.deepEqual(progress.next.remarkIds, [queued.id]); + assert.equal(progress.next.wakes, 2); + assert.isFalse(progress.exhausted); + assert.deepEqual(evaluatePullRequestWatch(progress.next, detail(), [queued]).changes, []); + + const outcome = { + ...queued, + body: codeRabbitReply("Review finished."), + editedAt: "2026-10-02T12:07:00Z", + }; + const finished = evaluatePullRequestWatch(progress.next, detail(), [outcome]); + assert.deepEqual(finished.changes, [{ kind: "remarks", remarks: [outcome] }]); + assert.equal(finished.next.wakes, 3); + assert.deepEqual(evaluatePullRequestWatch(finished.next, detail(), [outcome]).changes, []); + + const late = remark("reviewer", queued.createdAt); + const mixed = evaluatePullRequestWatch(watching, detail(), [queued, late]); + assert.deepEqual(mixed.changes, [{ kind: "remarks", remarks: [late] }]); + assert.deepEqual(mixed.next.remarkIds, [queued.id, late.id]); + } + }); + + it("keeps other replies and outcomes actionable beside CodeRabbit review progress", () => { + const bodies = [ + codeRabbitReply("Full review triggered.", "Actions performed"), + codeRabbitReply("Unable to review.", "Action not completed"), + codeRabbitReply("Here is the answer to your question."), + "Review triggered.", + codeRabbitReply("Review triggered.").replace( + "", + "", + ), + ]; + const comments = [ + ...bodies.map((body, index) => ({ + ...remark("coderabbitai[bot]", "2026-10-02T12:06:00Z", body), + id: `coderabbit-${index}`, + })), + remark("other-bot[bot]", "2026-10-02T12:06:00Z", bodies[0]), + remark("reviewer", "2026-10-02T12:06:00Z", bodies[0]), + ]; + const report = evaluatePullRequestWatch(watch(), detail(), comments); + assert.deepEqual(report.changes, [{ kind: "remarks", remarks: comments.slice(1) }]); + assert.deepEqual(evaluatePullRequestWatch(report.next, detail(), comments).changes, []); + }); + it("cuts a long remark in the wake message without splitting an emoji", () => { const body = `${"x".repeat(196)}🚀 and more`; const report = evaluatePullRequestWatch(watch(), detail(), [ diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index 5999996ec5dda..e6e0be0f20310 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -42,6 +42,15 @@ const isFailedCheck = (check: PullRequestCheck) => const workflowRunOf = (url: string | null) => url?.match(/^.*\/actions\/runs\/\d+/)?.[0] ?? null; const approvalKey = (check: PullRequestCheck) => workflowRunOf(check.url) ?? check.name; +function isReviewAcknowledgement(remark: PullRequestComment): boolean { + return ( + remark.author?.login.toLowerCase().replace(/\[bot\]$/, "") === "coderabbitai" && + /[\s\S]*?[^\p{L}<]*Actions? performed<\/summary>\s*(?:
\s*
\s*
\s*)?(?:Full review|Review) triggered\./u.test( + remark.body.slice(0, 1_000), + ) + ); +} + export function evaluatePullRequestWatch( watch: ThreadPullRequestWatch, detail: Pick< @@ -219,7 +228,8 @@ export function evaluatePullRequestWatch( remark.author?.login.toLowerCase() !== own ); }); - if (fresh.length > 0) changes.push({ kind: "remarks", remarks: fresh }); + const actionable = fresh.filter((remark) => !isReviewAcknowledgement(remark)); + if (actionable.length > 0) changes.push({ kind: "remarks", remarks: actionable }); const latest = Math.max(through, ...fresh.map((remark) => Date.parse(activeAt(remark)))); const atLatest = fresh.filter((remark) => Date.parse(activeAt(remark)) === latest); const remarksThrough = latest === through ? watch.remarksThrough : activeAt(atLatest[0]!); From c768764bb6c599244b884ddbc53dd0da024eea2d Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 14:25:39 +0200 Subject: [PATCH 53/74] fix(cli): expand ~ in t3 environment link --from (#41430) Co-authored-by: Julius Marminge --- apps/server/src/cli/environment.test.ts | 3 ++- apps/server/src/cli/environment.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/environment.test.ts b/apps/server/src/cli/environment.test.ts index 9ad17441add6e..2fcdc88589e6e 100644 --- a/apps/server/src/cli/environment.test.ts +++ b/apps/server/src/cli/environment.test.ts @@ -5,6 +5,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { NodeHttpServer } from "@effect/platform-node"; import * as NodeServices from "@effect/platform-node/NodeServices"; import type { ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NetService from "@t3tools/shared/Net"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -101,7 +102,7 @@ it.effect("links a file of environments, reports each line, and fails when one d retry, `${one.url} ${firstCode}\n${two.url} ${yield* codeFor(two)}\n${three.url} never-valid\n`, ); - yield* link(retry); + yield* link("~/retry.txt").pipe(Effect.provideService(HostProcess.HomeDirectory, baseDir)); const retried = (yield* reports).at(-1) ?? ""; expect(retried).toContain( `${one.url}: already linked as VM 1 (environment-vm-1), left as it is`, diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts index ab55715e721cb..a4b47ebbe8c55 100644 --- a/apps/server/src/cli/environment.ts +++ b/apps/server/src/cli/environment.ts @@ -29,6 +29,7 @@ import * as PeerLinks from "../peer/PeerLinks.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { expandHomePath } from "../os-jank.ts"; import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -201,7 +202,7 @@ const readLinkBatch = Effect.fn("environment.readLinkBatch")(function* (from: st ); } const fs = yield* FileSystem.FileSystem; - return yield* fs.readFileString(from); + return yield* fs.readFileString(yield* expandHomePath(from)); }); const environmentLinkCommand = Command.make("link", { From 27ecc0fad96609ea1d42f9388541199336c02ae9 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 06:31:02 -0600 Subject: [PATCH 54/74] fix(cli): reject incomplete workflow signal addresses locally (#41431) Co-authored-by: Julius Marminge --- apps/server/src/cli/workflow.test.ts | 34 ++++++++++++++++------------ apps/server/src/cli/workflow.ts | 7 ++++++ 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/apps/server/src/cli/workflow.test.ts b/apps/server/src/cli/workflow.test.ts index 0c99ca8ee8d21..82b4705e45fa6 100644 --- a/apps/server/src/cli/workflow.test.ts +++ b/apps/server/src/cli/workflow.test.ts @@ -166,21 +166,25 @@ it.effect("reports what the server refused instead of calling it unreachable", ( }), ); -it.effect("signal refuses both addresses at once before reaching the server", () => +it.effect("signal sends only one complete address to the server", () => Effect.gen(function* () { - const { error, calls } = yield* runCli([ - "signal", - "{}", - "--run", - "run-1", - "--wait", - "approve", - "--workflow", - "review", - "--channel", - "pr-1", - ]); - assert.strictEqual(error?._tag, "ThreadUsageError"); - assert.lengthOf(calls, 0); + const byRun = ["--run", "run-1", "--wait", "approve"]; + const byChannel = ["--workflow", "review", "--channel", "pr-1"]; + for (const [address, sent] of [ + [byRun, true], + [byChannel, true], + [[...byRun, ...byChannel], false], + [[], false], + [["--run", "run-1"], false], + [["--wait", "approve"], false], + [["--workflow", "review"], false], + [["--channel", "pr-1"], false], + ] as const) { + const { error, calls } = yield* runCli(["signal", "{}", ...address], () => + Effect.succeed({ structuredContent: { delivery: "delivered" } }), + ); + assert.strictEqual(error?._tag, sent ? undefined : "ThreadUsageError"); + assert.lengthOf(calls, sent ? 1 : 0); + } }), ); diff --git a/apps/server/src/cli/workflow.ts b/apps/server/src/cli/workflow.ts index 95a499043c6c6..c02ee63551f88 100644 --- a/apps/server/src/cli/workflow.ts +++ b/apps/server/src/cli/workflow.ts @@ -244,6 +244,13 @@ const signalCommand = Command.make("signal", { "Address a signal with --run and --wait, or with --workflow and --channel, not both.", }); } + const completeRun = Option.isSome(flags.run) && Option.isSome(flags.wait); + const completeChannel = Option.isSome(flags.workflow) && Option.isSome(flags.channel); + if (!completeRun && !completeChannel) { + return yield* new ThreadUsageError({ + detail: "Address a signal with --run and --wait, or with --workflow and --channel.", + }); + } yield* withThreadTools( { ...flags, json: false }, Effect.fn("cli.workflow.signal")(function* (tools) { From 6ec46a61e60e1bbc60ef48b919d41b124632db7c Mon Sep 17 00:00:00 2001 From: Nirmal Thewarathanthri Date: Mon, 23 Nov 2026 20:43:59 +0800 Subject: [PATCH 55/74] =?UTF-8?q?fix(opencode):=20Usage=20=E2=86=92=20Limi?= =?UTF-8?q?ts=20no=20longer=20warns=20when=20no=20Console=20workspace=20is?= =?UTF-8?q?=20signed=20in=20(#41415)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Nirmal Thewarathanthri <8257850+nthewara@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/v2/OpenCode2Client.test.ts | 3 +-- packages/provider-opencode/src/server/v2/usageLimits.ts | 8 ++------ 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index 701ad57fe488a..c08627eccdc00 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -495,8 +495,7 @@ describe("OpenCode2Client usage limits", () => { const result = yield* api.usageLimits("/remote"); if (reason === undefined) assert.strictEqual(result, undefined); else assert.strictEqual(result?.unavailable?.reason, reason); - if ("data" in body && body.data === null) - assert.include(result?.unavailable?.message ?? "", "signed in"); + if (reason === "unsupported") assert.strictEqual(result?.unavailable?.message, undefined); if ("message" in body) assert.include(result?.unavailable?.message ?? "", "OpenCode Console budgets"); } diff --git a/packages/provider-opencode/src/server/v2/usageLimits.ts b/packages/provider-opencode/src/server/v2/usageLimits.ts index bdf678e424692..ea3f141b2100a 100644 --- a/packages/provider-opencode/src/server/v2/usageLimits.ts +++ b/packages/provider-opencode/src/server/v2/usageLimits.ts @@ -95,12 +95,8 @@ export const readServerUsageLimits = Effect.fn("OpenCode2Client.usageLimits")(fu ), }); const body = yield* HttpClientResponse.schemaBodyJson(ResponseBody)(response); - if (body.data === null) - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "No OpenCode Console workspace is signed in.", - }); + // OpenCode needs no Console workspace, so its absence is not worth a notice. + if (body.data === null) return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); const { go, budgets, workspace } = body.data; const usageURL = URL.parse(workspace.usageURL); const externalUsage = From 0db39e6b7c707334ddd5254d16a4486c48eb05d6 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 06:47:12 -0600 Subject: [PATCH 56/74] fix(cli): uninstall removes a script launcher whose target names the home through a symlink (#41435) Co-authored-by: Julius Marminge --- apps/server/src/cli/uninstall.test.ts | 16 ++++++++++++++++ apps/server/src/cli/uninstall.ts | 8 ++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index c22760da53453..7bb1046199c4e 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -200,9 +200,21 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { // recorded launchers: through a symlinked home, and dangling after a prune. const throughAlias = path.join(root, "bin/t3-alias"); const pruned = path.join(root, "bin/t3-pruned"); + const scriptThroughAlias = path.join(scriptDir, "t3-alias"); + const prunedScript = path.join(scriptDir, "t3-pruned"); yield* fs.symlink(root, path.join(root, "alias")); yield* fs.symlink(path.join(root, "alias/runtime/versions/1.0.0/t3"), throughAlias); yield* fs.symlink(path.join(versionsDir, "0.9.0/t3"), pruned); + yield* fs.writeFileString( + scriptThroughAlias, + posixLauncherScript(path.join(root, "alias/runtime/versions/1.0.0/t3")), + { mode: 0o755 }, + ); + yield* fs.writeFileString( + prunedScript, + posixLauncherScript(path.join(versionsDir, "0.9.0/t3")), + { mode: 0o755 }, + ); // Another program inside a version is not a launcher. const sibling = path.join(root, "bin/t3-sibling"); yield* fs.symlink(path.join(versionsDir, "1.0.0/node"), sibling); @@ -216,6 +228,8 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { pruned, sibling, script, + scriptThroughAlias, + prunedScript, editedScript, path.join(root, "missing"), ].join("\n") + "\n", @@ -226,6 +240,8 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { throughAlias, pruned, script, + scriptThroughAlias, + prunedScript, ]); } diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index a0d47c7384910..5624e6c2a894c 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -75,7 +75,8 @@ const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* ( const realVersionsDir = yield* fs .realPath(versionsDir) .pipe(Effect.orElseSucceed(() => versionsDir)); - // The link's own text keeps a pruned (dangling) target; the real path sees through a + const scriptTarget = platform === "win32" ? undefined : yield* readPosixLauncherTarget(launcher); + // The link or script text keeps a pruned (dangling) target; the real path sees through a // symlinked T3 home. const targets = platform === "win32" @@ -91,7 +92,10 @@ const ownsLauncher = Effect.fn("cli.uninstall.owns_launcher")(function* ( Effect.orElseSucceed(() => undefined), ), yield* fs.realPath(launcher).pipe(Effect.orElseSucceed(() => undefined)), - yield* readPosixLauncherTarget(launcher), + scriptTarget, + scriptTarget !== undefined + ? yield* fs.realPath(scriptTarget).pipe(Effect.orElseSucceed(() => undefined)) + : undefined, ]; return targets.some( (target) => From 3ab1ee20bd451eee58c1cbc9d1fd135fe5425045 Mon Sep 17 00:00:00 2001 From: Anthony Mittaz Date: Mon, 23 Nov 2026 23:47:27 +1100 Subject: [PATCH 57/74] fix(server): long setup scripts complete in macOS zsh (#37836) Co-authored-by: Julius Marminge --- .../project/ProjectSetupScriptRunner.test.ts | 21 ++++++++++++------- .../src/project/ProjectSetupScriptRunner.ts | 9 ++++++-- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index c495feb4cef66..3827fca09cf74 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -138,7 +138,9 @@ describe("ProjectSetupScriptRunner", () => { const { writes } = yield* setup({ shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", }); - expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE"); + const submitted = yield* Queue.take(writes); + expect(submitted).toContain("$global:LASTEXITCODE"); + expect(submitted).not.toContain("\x1b[200~"); }), ); @@ -209,9 +211,11 @@ describe("ProjectSetupScriptRunner", () => { it.effect("types into a quiet shell that has no line editor", () => Effect.gen(function* () { - const { writes } = yield* setup(); + const { writes } = yield* setup({ command: "printf '%s\\n' 'setup-ready'\n".repeat(120) }); yield* TestClock.adjust("3 seconds"); - expect(yield* Queue.take(writes)).toContain("vp i"); + const submitted = yield* Queue.take(writes); + expect(submitted).toContain("setup-ready"); + expect(submitted).not.toContain("\x1b[200~"); }), ); @@ -271,6 +275,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { const { writes, outputLines, emit, completion } = yield* setup({ command }); yield* emit({ ...event, type: "output", data: "\x1b[?2004h" }); const submitted = yield* Queue.take(writes); + const shellInput = submitted.replace("\x1b[200~", "").replace("\x1b[201~", ""); const cwd = yield* HostProcess.WorkingDirectory; const env = yield* HostProcess.Environment; @@ -281,7 +286,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { const handle = yield* spawner.spawn( ChildProcess.make( "/bin/bash", - ["--noprofile", "--norc", "-c", submitted.replaceAll("\r", "\n")], + ["--noprofile", "--norc", "-c", shellInput.replaceAll("\r", "\n")], { cwd, env: { PATH: env.PATH }, @@ -302,6 +307,7 @@ const runObservedSetup = Effect.fnUntraced(function* (command: string) { yield* emit({ ...event, type: "closed" }); return { submitted, + shellInput, lines: yield* Queue.clear(outputLines), exitCode: (yield* completion).exitCode, }; @@ -347,9 +353,10 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("POSIX setup co assert.deepEqual(result.lines, expected); assert.equal(result.exitCode, 0); assert.equal(result.submitted.at(-1), "\r"); - assert.notInclude(result.submitted, "\n"); - // The runner can write before the shell switches the terminal out of canonical mode. - for (const line of result.submitted.slice(0, -1).split("\r")) { + assert.isTrue(result.submitted.startsWith(" \x1b[200~")); + assert.isTrue(result.submitted.endsWith("\x1b[201~\r")); + assert.notInclude(result.submitted.slice(0, -1), "\r"); + for (const line of result.shellInput.slice(0, -1).split("\n")) { assert.isBelow(utf8.encode(line).byteLength, 1_024); } }), diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 1c94a3f118757..667aa33c6dcde 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -412,7 +412,7 @@ export const make = Effect.gen(function* () { const seen = activity; yield* Effect.sleep(SHELL_QUIET_FALLBACK); if (activity !== seen) continue; - if (!busy) return "ready" as const; + if (!busy) return "quiet" as const; yield* input.onStartupPrompt; } }); @@ -603,7 +603,12 @@ export const make = Effect.gen(function* () { : terminalManager.write({ threadId: input.threadId, terminalId, - data: projectScriptTerminalInput(commandLine), + // macOS zsh garbles long typed-ahead multiline input; a live line editor takes it as one paste. + data: projectScriptTerminalInput( + shell === "ready" && completionShell === "posix" && commandLine.includes("\r") + ? `\x1b[200~${commandLine.replaceAll("\r", "\n")}\x1b[201~` + : commandLine, + ), }), ), Effect.catchCause((cause) => From c6fe23dd2871126cd189cf197761849e7ef0f91d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 04:52:01 -0800 Subject: [PATCH 58/74] fix(server): preview type sends key events to the page (#41432) --- apps/server/src/preview/ServerBrowser.test.ts | 28 ++++++++ apps/server/src/preview/ServerBrowser.ts | 12 ++-- .../src/preview/ServerBrowserPage.test.ts | 56 ++++++++++++++- apps/server/src/preview/ServerBrowserPage.ts | 68 ++++++++++++++++--- 4 files changed, 149 insertions(+), 15 deletions(-) diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index d8e5f0622241c..f0841ca2556d3 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -1735,6 +1735,34 @@ it.effect( ).pipe(Effect.provide(layer)), ); +it.effect("stops typing long text at the request's deadline and says how far it got", () => + Effect.scoped( + Effect.gen(function* () { + const { broker, tabId } = yield* ready; + const page = contexts[0]!.page; + page.evaluate.mockImplementation(async () => true as never); + let now = 1_700_000_000_000; + const clock = vi.spyOn(Date, "now").mockImplementation(() => now); + yield* Effect.addFinalizer(() => Effect.sync(() => clock.mockRestore())); + // Each piece of keys takes 10 seconds here: over the request's 5, under the 15-second default. + const type = vi.fn(async (_text: string) => void (now += 10_000)); + Object.assign(page, { keyboard: { type } }); + const failure = yield* broker + .invoke({ + scope, + tabId, + operation: "type", + input: { text: "a".repeat(200) }, + timeoutMs: 5_000, + }) + .pipe(Effect.flip); + expect(failure._tag).toBe("PreviewAutomationTimeoutError"); + expect(failure.message).toMatch(/after 64 of 200 characters/); + expect(type.mock.calls).toEqual([["a".repeat(64)]]); + }), + ).pipe(Effect.provide(layer)), +); + it.effect("reports a pending dialog without evaluating the page and resolves it explicitly", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 9fd94232a5e23..8adba6ba3e478 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -2945,10 +2945,14 @@ const make = Effect.gen(function* () { return recordAction(tab, "upload", () => uploadFiles(tab, input as PreviewAutomationUploadInput), ); - case "type": - return recordAction(tab, "type", () => - ServerBrowserPage.type(tab.page, input as PreviewAutomationTypeInput), - ); + case "type": { + // As for click: typing stops at the broker's deadline instead of running on after the reply. + const typeInput = { + ...(input as PreviewAutomationTypeInput), + timeoutMs: Math.max(1, Math.floor(deadlineMs - performance.now())), + }; + return recordAction(tab, "type", () => ServerBrowserPage.type(tab.page, typeInput)); + } case "press": return recordAction(tab, "press", () => ServerBrowserPage.press(tab.page, input as PreviewAutomationPressInput), diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 9afe924dabc4c..544e4d81d01ab 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -410,6 +410,36 @@ describe("server browser element refs", () => { expect(await inner.inputValue()).toBe(""); }); + it("types into a field that builds its value from keydown, with and without clear", async () => { + await page.setContent( + ``, + ); + const keys = (selector: string) => + page.locator(selector).evaluate((field) => (field as unknown as { keys: string }).keys); + await ServerBrowserPage.type(page, { locator: "#a", text: "girona42" }); + expect(await keys("#a")).toBe("girona42"); + await ServerBrowserPage.type(page, { locator: "#b", text: "girona42", clear: true }); + expect(await keys("#b")).toBe("girona42"); + await ServerBrowserPage.type(page, { locator: "#b", text: "a".repeat(501), clear: true }); + expect(await keys("#b")).toBe(`girona42${"a".repeat(501)}`); + + await page.setContent( + `
`, + ); + await ServerBrowserPage.type(page, { locator: "text=Email", text: "a@b.c", clear: true }); + expect(await page.locator("#e").inputValue()).toBe("a@b.c"); + await ServerBrowserPage.type(page, { locator: "#d", text: "2026-01-31", clear: true }); + expect(await page.locator("#d").inputValue()).toBe("2026-01-31"); + await ServerBrowserPage.type(page, { locator: "text=Tint", text: "#ff0000", clear: true }); + expect(await page.locator("#c").inputValue()).toBe("#ff0000"); + await ServerBrowserPage.type(page, { locator: "#r", text: "70", clear: true }); + expect(await page.locator("#r").inputValue()).toBe("70"); + await ServerBrowserPage.type(page, { locator: "#e", text: "x\ny" }); + await ServerBrowserPage.type(page, { locator: "#t", text: "one\r\ntwo" }); + expect(await page.locator("#t").inputValue()).toBe("one\ntwo"); + expect(await page.locator("#sent").inputValue()).toBe(""); + }); + it("shows dotted fields as dots wherever their value appears, keeping text values and refs", async () => { await page.setContent(`
password:
@@ -973,7 +1003,7 @@ describe("server browser type", () => { ({ locator: () => ({ last: () => ({ count: () => new Promise(() => {}) }) }), evaluate: focusAnswer, - keyboard: { insertText: async (text: string) => void typed.push(text) }, + keyboard: { type: async (text: string) => void typed.push(text) }, }) as unknown as Page; it("types into the focused field when Playwright's utility world never answers", async () => { @@ -1010,6 +1040,30 @@ describe("server browser type", () => { detail: { timeoutMs: 300 }, }); expect(typed).toEqual([]); + + // A target whose element is found but whose page then stops answering. + const fill = vi.fn(async () => {}); + const hung = { + locator: () => ({ evaluate: () => new Promise(() => {}), fill }), + keyboard: { type: async (text: string) => void typed.push(text) }, + } as unknown as Page; + void ServerBrowserPage.type(hung, { + locator: "#field", + text: "hello", + clear: true, + timeoutMs: 300, + }).then( + () => (outcome = "typed"), + (error: unknown) => (outcome = error), + ); + outcome = "pending"; + await vi.advanceTimersByTimeAsync(300); + expect(outcome).toMatchObject({ + tag: "PreviewAutomationTimeoutError", + detail: { timeoutMs: 300 }, + }); + expect(fill).not.toHaveBeenCalled(); + expect(typed).toEqual([]); } finally { vi.useRealTimers(); } diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index f5eed496da5fe..a633f4328d163 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -941,8 +941,8 @@ const focusTextTarget = (target: FocusCandidate | null) => { return active != null && (active === element || element.contains(active)); }; -// A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. -const focusedTextField = async (page: Page, timeout: number) => { +// Playwright's own timeout covers finding the element, not a page that stops answering the evaluation. +const pageAnswer = async (answer: Promise, timeout: number) => { let timer: ReturnType | undefined; const expired = new Promise((_, reject) => { timer = setTimeout( @@ -950,29 +950,77 @@ const focusedTextField = async (page: Page, timeout: number) => { reject( new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: `The page did not report its focused element within ${timeout}ms, so no text was typed.`, + message: `The page did not answer within ${timeout}ms, so no text was typed.`, detail: { timeoutMs: timeout }, }), ), timeout, ); }); - return await Promise.race([page.evaluate(focusTextTarget, null), expired]).finally(() => - clearTimeout(timer), + return await Promise.race([answer, expired]).finally(() => clearTimeout(timer)); +}; + +// Serialized into the page's main world, so it must not reference module scope. +const valueOnlyInput = ( + target: FocusCandidate & { + closest(selector: string): { readonly control: FocusCandidate | null } | null; + }, +) => { + // As fill does, a target that is not a control stands for its label's control. + const element = target.tagName === "INPUT" ? target : target.closest("label")?.control; + return ( + element?.tagName === "INPUT" && + ["color", "date", "datetime-local", "month", "range", "time", "week"].includes( + element.type ?? "", + ) ); }; +// Keys reach pages that build their value from keydown. Line breaks stay text: Enter would submit the form. +const typeKeys = async (page: Page, text: string, timeoutMs: number, deadline: number) => { + let typed = 0; + for (const [index, part] of text.split(/([\r\n]+)/u).entries()) { + // Keys cost about a millisecond each, so long text is sent in pieces that stop at the deadline. + const pieces = index % 2 === 1 ? [part] : (part.match(/[^]{1,64}/gu) ?? []); + for (const piece of pieces) { + if (Date.now() >= deadline) { + const reason = `Typing stopped after ${typed} of ${text.length} characters, which the field now holds. Type the rest in another call or raise timeoutMs.`; + throw new ServerBrowserOperationError({ + tag: "PreviewAutomationTimeoutError", + message: reason, + detail: { timeoutMs, reason }, + }); + } + if (index % 2 === 1) await page.keyboard.insertText(piece); + else await page.keyboard.type(piece); + typed += piece.length; + } + } +}; + export const type = async (page: Page, input: PreviewAutomationTypeInput) => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + // One deadline across steps keeps the reply inside the broker's grace; Playwright reads 0 as none. + const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const deadline = Date.now() + timeoutMs; + const remaining = () => Math.max(1, deadline - Date.now()); const locator = targetLocator(page, input); if (locator !== null && input.clear) { - await locator.fill(input.text, { timeout }); + // Pickers and sliders take a value such as 2026-01-31 only from fill, and some reject an empty one. + const timeout = remaining(); + if (await pageAnswer(locator.evaluate(valueOnlyInput, undefined, { timeout }), timeout)) { + await locator.fill(input.text, { timeout: remaining() }); + return; + } + // fill follows a label to its control and leaves that control focused for the keys. + await locator.fill("", { timeout: remaining() }); + await typeKeys(page, input.text, timeoutMs, deadline); return; } const focused = locator === null - ? await focusedTextField(page, timeout) - : await locator.evaluate(focusTextTarget, undefined, { timeout }); + ? // A `*:focus` locator needs Playwright's utility world, which some desktop tabs never get. + await pageAnswer(page.evaluate(focusTextTarget, null), remaining()) + : await locator.evaluate(focusTextTarget, undefined, { timeout: remaining() }); if (focused !== true) { throw new ServerBrowserOperationError({ tag: "PreviewAutomationTargetNotEditableError", @@ -983,7 +1031,7 @@ export const type = async (page: Page, input: PreviewAutomationTypeInput) => { await page.keyboard.press("ControlOrMeta+A"); await page.keyboard.press("Delete"); } - await page.keyboard.insertText(input.text); + await typeKeys(page, input.text, timeoutMs, deadline); }; export const hover = async ( From e6e863c0452d1d9e103123fc1315729a71eb2998 Mon Sep 17 00:00:00 2001 From: Martin Zeman Date: Mon, 23 Nov 2026 14:03:30 +0100 Subject: [PATCH 59/74] fix(shared): Open in Cursor skips a broken cursor on PATH (#38212) Co-authored-by: abominable-intelligence Co-authored-by: Julius Marminge --- .../src/process/externalLauncher.test.ts | 69 ++++++++++++++++++- packages/shared/src/editor.ts | 25 ++++--- 2 files changed, 81 insertions(+), 13 deletions(-) diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 4246baf39179c..83e140161a499 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -900,6 +900,67 @@ for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12 ); } +// Stand-ins for a `--version` check. The Cursor Agent CLI installs a cursor script that fails +// when no IDE is behind it, and a slow first start stays silent for longer than the check waits. +const scripts = { works: "", fails: "exit 1", stalls: "exec sleep 30" }; +// Each row: title, editor, script first on PATH, extra install, result on darwin, result on linux. +for (const [title, id, first, extra, onDarwin, onLinux = onDarwin] of [ + ["keeps a working cursor on PATH ahead of the bundle", "cursor", "works", "bundle", "cursor"], + ["keeps a cursor that never answers --version", "cursor", "stalls", "none", "cursor"], + ["skips a failing cursor for a later cursor on PATH", "cursor", "fails", "later", "later"], + ["skips a failing cursor for the Cursor bundle", "cursor", "fails", "bundle", "bundle", "none"], + ["rejects a zed that never answers --version", "zed", "stalls", "none", "none"], +] as const) { + for (const platform of ["darwin", "linux"] as const) { + it.effect.skipIf(windowsHost)(`${title} on ${platform}`, () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor-check-" }); + const commands = { + cursor: "cursor", + none: undefined, + first: path.join(home, "bin", id), + later: path.join(home, "later-bin", id), + bundle: path.join(home, "Applications/Cursor.app/Contents/Resources/app/bin/cursor"), + }; + for (const key of ["first", extra] as const) { + if (key === "none") continue; + yield* fs.makeDirectory(path.dirname(commands[key]), { recursive: true }); + const script = key === "first" ? scripts[first] : scripts.works; + yield* fs.writeFileString(commands[key], `#!/bin/sh\n${script}\n`); + yield* fs.chmod(commands[key], 0o755); + } + const editor = EDITORS.find((editor) => editor.id === id)!; + const env = { HOME: home, PATH: `${home}/bin:${home}/later-bin` }; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const started = yield* Deferred.make(); + // Signal that the `--version` check has a running process. + const signal = Deferred.succeed(started, undefined); + const [resolved] = yield* Effect.all( + [ + resolveEditorCommand(editor, env).pipe( + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(Path.Path, withSystemBin(path, path.join(home, "system-bin"))), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((cmd) => spawner.spawn(cmd).pipe(Effect.tap(signal))), + ), + ), + // The check runs on the test clock, so its timeout passes only when the clock moves. + first === "stalls" + ? Deferred.await(started).pipe(Effect.andThen(TestClock.adjust("2 seconds"))) + : Effect.void, + ], + { concurrency: "unbounded" }, + ); + const expected = commands[platform === "darwin" ? onDarwin : onLinux]; + assert.equal(Option.getOrUndefined(resolved)?.command, expected); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + } +} + for (const { layout, pathNames, fallbackNames, expected } of [ { layout: "PATH", pathNames: ["zed", "zeditor"], fallbackNames: [], expected: "zeditor" }, { @@ -959,14 +1020,16 @@ for (const { layout, pathNames, fallbackNames, expected } of [ ); } -// Linux editor discovery also probes fixed system directories; tests point them at a temp -// directory so an editor installed on the host cannot satisfy the lookup. +// Editor discovery also probes fixed system directories (Linux bin folders, macOS /Applications); +// tests point them at a temp directory so an editor installed on the host cannot satisfy the lookup. const withSystemBin = (path: Path.Path, systemBin: string): Path.Path => ({ ...path, join: (...parts) => path.join( ...parts.map((part) => - ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part, + ["/Applications", "/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) + ? systemBin + : part, ), ), }); diff --git a/packages/shared/src/editor.ts b/packages/shared/src/editor.ts index 902e06bd7f986..544da3d67e98b 100644 --- a/packages/shared/src/editor.ts +++ b/packages/shared/src/editor.ts @@ -37,9 +37,10 @@ const isVersionedBundle = (entry: string, name: string) => { return /^\d[\d.]*$/.test(entry.slice(name.length + 1, -".app".length)); }; -// OpenZFS's event daemon is also named zed; it rejects `--version` instead of starting. -const isZedEditor = Effect.fn("editor.isZedEditor")( - function* (command: string) { +// OpenZFS's event daemon is also named zed, and the Cursor Agent CLI installs a cursor script +// that fails without an IDE behind it; both reject `--version` instead of starting. +const isEditorCommand = Effect.fn("editor.isEditorCommand")( + function* (command: string, isZed: boolean) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const handle = yield* spawner.spawn( ChildProcess.make(command, ["--version"], { @@ -52,10 +53,12 @@ const isZedEditor = Effect.fn("editor.isZedEditor")( [handle.stdout.pipe(Stream.decodeText(), Stream.runHead), handle.exitCode], { concurrency: "unbounded" }, ); - return exitCode === 0 && Option.getOrElse(stdout, () => "").startsWith("Zed"); + return exitCode === 0 && (!isZed || Option.getOrElse(stdout, () => "").startsWith("Zed")); }, Effect.scoped, - Effect.timeout("2 seconds"), + // A slow first start after an update must not hide a working Cursor. + (probe, _command, isZed) => + Effect.timeoutOrElse(probe, { duration: "2 seconds", orElse: () => Effect.succeed(!isZed) }), Effect.catchCause(() => Effect.succeed(false)), ); @@ -69,6 +72,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun // Prefer Zed's macOS bundle because OpenZFS also installs a zed executable. const preferBundle = platform === "darwin" && editor.id === "zed"; const preferZeditor = platform === "linux" && editor.id === "zed"; + const probeCursor = editor.id === "cursor" && platform !== "win32"; if (platform === "win32" && editor.id === "zed") { const isStable = (resolved: string) => !isPrereleaseZedPath(resolved); let firstCommand: string | undefined; @@ -83,7 +87,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun if (firstCommand === undefined && matches.length > 0) firstCommand = command; } if (firstCommand !== undefined) return Option.some({ command: firstCommand, baseArgs }); - } else if (!preferBundle && !preferZeditor) { + } else if (!preferBundle && !preferZeditor && !probeCursor) { for (const command of editor.commands) { if (yield* isCommandAvailable(command, { env })) return Option.some({ command, baseArgs }); } @@ -95,7 +99,7 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun const names = installNames[editor.id] ?? [editor.label]; const command = editor.commands[0]; const jetbrains = editor.launchStyle === "line-column"; - const candidates: string[] = []; + const candidates: string[] = probeCursor ? [...editor.commands] : []; let toolbox: { dir: string; suffix: string } | undefined; if (platform === "darwin") { @@ -216,14 +220,15 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun const probeZed = editor.id === "zed" && platform !== "win32"; const rejected = new Set(); for (const candidate of candidates) { - // OpenZFS zed can shadow the editor's zed in an earlier PATH entry. + // An earlier PATH entry can hold OpenZFS zed or the Cursor Agent CLI's cursor script. const matches = - probeZed && candidate === "zed" + (probeZed || probeCursor) && candidate === command ? yield* resolveCommandPaths(candidate, { env, until: () => false }) : [yield* resolveCommandPath(candidate, { env })]; for (const resolved of matches) { if (resolved === null || rejected.has(resolved)) continue; - if (probeZed && path.basename(candidate) === "zed" && !(yield* isZedEditor(resolved))) { + const probed = probeCursor || (probeZed && path.basename(candidate) === "zed"); + if (probed && !(yield* isEditorCommand(resolved, probeZed))) { rejected.add(resolved); continue; } From 5e128576b52e16a528650afea0e0c02460d12011 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Mon, 23 Nov 2026 15:03:42 +0200 Subject: [PATCH 60/74] fix(cli): expand ~ in t3 policy templates --policy (#41438) Co-authored-by: Julius Marminge --- apps/server/src/cli/policy.test.ts | 37 +++++++++++++++++++++++++++--- apps/server/src/cli/policy.ts | 6 +++-- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/server/src/cli/policy.test.ts b/apps/server/src/cli/policy.test.ts index 7066cceebcd0f..d06998ff42882 100644 --- a/apps/server/src/cli/policy.test.ts +++ b/apps/server/src/cli/policy.test.ts @@ -1,12 +1,16 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { Command } from "effect/cli"; +import { cli } from "../binCli.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { makePersistedServerRuntimeState, @@ -16,7 +20,7 @@ import { describeRunningServer } from "./policy.ts"; const encodeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState)); -it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => { it.effect("tells whether the running server loaded the installed policy", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -53,5 +57,32 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => assert.include(yield* running(null, null), "runs without a policy, as installed"); assert.include(yield* running(undefined), "does not report which policy it loaded"); }), - ), -); + ); + + it.effect("templates 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-templates-" }); + yield* fs.writeFileString( + path.join(home, "policy.json"), + JSON.stringify({ schemaVersion: 1, organization: "Tilde Corp" }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "policy", + "templates", + home, + "--policy=~/policy.json", + ]).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provide(NetService.layer), + ); + + assert.include( + yield* fs.readFileString(path.join(home, "macos", "t3code.mobileconfig")), + "Tilde Corp", + ); + }), + ); +}); diff --git a/apps/server/src/cli/policy.ts b/apps/server/src/cli/policy.ts index dafc5352166f0..c48e2bc535a6f 100644 --- a/apps/server/src/cli/policy.ts +++ b/apps/server/src/cli/policy.ts @@ -13,6 +13,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { listManageableSettings } from "../policy/managedSettings.ts"; import { macosProfile, windowsAdml, windowsAdmx } from "../policy/policyTemplates.ts"; +import { expandHomePath } from "../os-jank.ts"; import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -132,13 +133,14 @@ const templatesCommand = Command.make("templates", { const path = yield* Path.Path; let document = SAMPLE_POLICY; if (Option.isSome(policy)) { - if (!(yield* fs.exists(policy.value))) { + const file = yield* expandHomePath(policy.value); + if (!(yield* fs.exists(file))) { return yield* new CliError.UserError({ cause: policy.value, userMessage: `No policy file at ${policy.value}.`, }); } - const loaded = (yield* ManagedPolicy.load(policy.value)).document; + const loaded = (yield* ManagedPolicy.load(file)).document; if (loaded !== undefined) document = loaded; } const random = yield* SecureRandom.SecureRandom; From 43115666546509f4ea2a804773a6f47715dcc353 Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 14:15:34 +0100 Subject: [PATCH 61/74] fix(server): read relocated shared strings in XLSX attachments (#41441) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 18 +++++++++++------- .../src/provider/userInputAttachments.test.ts | 4 ++-- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index cc675a539591d..a381ede3cc138 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -631,7 +631,7 @@ async function* document(path: string, extension: string): AsyncGenerator rel.attrs.TargetMode !== "External") - .map((rel) => [rel.attrs.Id, rel.attrs.Target]), + .map((rel) => [rel.attrs.Id, rel.attrs]), ); if (extension === ".docx") { // The package relationship names the main part; Word for the web saves word/document2.xml. @@ -682,14 +682,18 @@ 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 populatedStrings = strings.map(hasCellText); for (const sheet of all(workbook, "sheet")) { yield `\n## Sheet: ${sheet.attrs.name}\n`; - const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id); + const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id)?.Target; if (!target) { skip(`sheet relationship ${sheet.attrs.name}`); continue; @@ -764,7 +768,7 @@ async function* document(path: string, extension: string): AsyncGenerator node.name === "sldId")) { yield `\n\n## Slide ${++index}\n`; - const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id); + const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id)?.Target; if (!target) { skip(`slide relationship ${index}`); continue; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 640a491af0bc0..e81c404c4aef1 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -933,8 +933,8 @@ describe("question answer paths", () => { "xl/workbook.xml": '', "xl/_rels/workbook.xml.rels": - '', - "xl/sharedStrings.xml": "Lantern", + '', + "catalog/items.xml": "Lantern", "xl/styles.xml": '', "xl/worksheets/second.xml": From 2bc7878fff064f9d874bf3d8584f1bd1b20b2879 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 05:17:03 -0800 Subject: [PATCH 62/74] fix(server): import Claude sessions whose first prompt carries a large image (#41446) --- apps/server/src/project/AgentSessionJson.ts | 14 ++- .../src/project/AgentSessionScanner.test.ts | 57 +++++++++++ .../server/src/project/AgentSessionScanner.ts | 97 ++++++++++++++----- 3 files changed, 140 insertions(+), 28 deletions(-) diff --git a/apps/server/src/project/AgentSessionJson.ts b/apps/server/src/project/AgentSessionJson.ts index c9dc6baa5f5e6..35b2ac9fad1b0 100644 --- a/apps/server/src/project/AgentSessionJson.ts +++ b/apps/server/src/project/AgentSessionJson.ts @@ -49,7 +49,11 @@ export class TranscriptJsonLimitError extends Schema.TaggedError void, selectPath: (path: JsonPath) => boolean, - options?: { readonly maxDepth?: number }, + options?: { + readonly maxDepth?: number; + // Reports each selected top-level string field as soon as it ends, before the record does. + readonly onTopLevelString?: (key: string, value: string) => void; + }, ) { // 3.6.0 omits the synchronous tokenizer from types; parser() adds an unnecessary async generator. const { jsonParser } = StreamJson as typeof StreamJson & { @@ -133,7 +137,13 @@ export function createTranscriptJsonReader( return; case "endString": case "endNumber": - if (selectedValue) assemble(token); + if (selectedValue) { + const parent = stack[0]; + if (token.name === "endString" && stack.length === 1 && typeof parent?.key === "string") { + options?.onTopLevelString?.(parent.key, value); + } + assemble(token); + } endValue(); return; case "nullValue": diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index fc76fc150a1d2..09a7a396a294f 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -2327,6 +2327,63 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("imports a Claude session whose first prompt carries an image over 1 MiB", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-large-image-claude-"); + const codexHomePath = yield* makeTempDir("t3code-large-image-codex-"); + const workspace = yield* makeTempDir("t3code-large-image-workspace-"); + const sessionId = "large-image-session"; + const contents = [ + { type: "queue-operation", operation: "enqueue", sessionId }, + { type: "queue-operation", operation: "dequeue", sessionId }, + { + type: "user", + cwd: workspace, + sessionId, + timestamp: "2026-08-24T10:00:00.000Z", + message: { + role: "user", + content: [ + { type: "text", text: "Look at this screenshot" }, + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "A".repeat(1_100 * 1024), + }, + }, + ], + }, + }, + { + type: "assistant", + sessionId, + timestamp: "2026-08-24T10:01:00.000Z", + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + }, + ] + .map((record) => encodeTranscriptRecord(record)) + .join("\n"); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-large-image", `${sessionId}.jsonl`), + contents, + mtimeMs: nowMs - 60 * 60 * 1000, + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect(threads.map((thread) => thread.providerSessionId)).toEqual([sessionId]); + }), + ); + it.effect("imports every transcript that fits the per-file record limit", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 9bd4b5cebd276..b9029b8746b46 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -169,6 +169,17 @@ const decodePiEntryLinks = Schema.decodeUnknownOption( }), ); const selectTranscriptPath = createTranscriptJsonSelector(TranscriptRecord); +// Only the fields extractCwd reads, so a cwd record carrying a large image stays small in memory. +const selectCwdPath = createTranscriptJsonSelector( + Schema.Struct({ + cwd: Schema.String, + type: Schema.String, + payload: Schema.Struct({ + cwd: Schema.String, + source: Schema.Struct({ subagent: Schema.Null, subAgent: Schema.Null }), + }), + }), +); const decodeCodexTurnMetadata = Schema.decodeUnknownOption(CodexTurnMetadata); export const decodeImportedTranscriptPayload = Schema.decodeUnknownOption( Schema.Struct({ @@ -832,13 +843,7 @@ function isT3ManagedWorktree( } // false stops metadata scanning for an excluded rollout, even if later records contain a cwd. -function extractCwd(line: string, source: AgentSessionSource): string | null | false { - let parsed: unknown; - try { - parsed = JSON.parse(line); - } catch { - return null; - } +function extractCwd(parsed: unknown, source: AgentSessionSource): string | null | false { if (typeof parsed !== "object" || parsed === null) return null; const record = parsed as Record; @@ -1220,11 +1225,28 @@ export const make = Effect.gen(function* () { const size = isCompressedTranscript(transcript.filePath) ? Number.POSITIVE_INFINITY : transcript.identity.size; - const decoder = new TextDecoder(); - let remaining = ""; let bytesRead = 0; let recordsRead = 0; - const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); + let selectedBytes = 0; + const reserveSelected = (bytes: number) => { + selectedBytes += bytes; + if (selectedBytes > MAX_TRANSCRIPT_SCAN_BYTES) { + throw new TranscriptJsonLimitError({ + message: "Transcript cwd fields exceed the scan limit", + }); + } + }; + // Claude writes cwd before message, so a record with a large image need not be read to its end. + let topLevelCwd: string | null = null; + const createReader = () => + createTranscriptJsonReader(reserveSelected, selectCwdPath, { + onTopLevelString: (key, value) => { + if (key === "cwd" && value.trim().length > 0) topLevelCwd ??= value; + }, + }); + let reader = createReader(); + let decoder = new TextDecoder(); + let recordStarted = false; const reserveRecord = () => { if ( recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT || @@ -1237,13 +1259,43 @@ export const make = Effect.gen(function* () { budget.recordsRemaining -= 1; return true; }; - const readLastRecord = () => { - const record = remaining + decoder.decode(); - return record.length === 0 || !reserveRecord() - ? null - : extractCwd(record.trim(), source); + const finishRecord = () => { + reader.write(decoder.decode()); + const value = reader.finish(); + reader = createReader(); + decoder = new TextDecoder(); + recordStarted = false; + selectedBytes = 0; + return extractCwd(value, source); }; + const scanChunk = (chunk: Uint8Array): string | false | null | undefined => { + let start = 0; + while (start < chunk.byteLength) { + const newline = chunk.indexOf(10, start); + const end = newline === -1 ? chunk.byteLength : newline; + if (end > start) { + recordStarted = true; + reader.write(decoder.decode(chunk.subarray(start, end), { stream: true })); + if (topLevelCwd !== null) return reserveRecord() ? topLevelCwd : null; + } + if (newline === -1) return undefined; + if (!reserveRecord()) return null; + const cwd = finishRecord(); + if (cwd !== null) return cwd; + start = newline + 1; + } + return undefined; + }; + const parse = (f: () => A) => + Effect.try({ + try: f, + catch: (cause) => + new TranscriptParseError({ filePath: transcript.filePath, cause }), + }); + const readLastRecord = () => + !recordStarted || !reserveRecord() ? null : finishRecord(); + const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); while (bytesRead < maxBytes) { if (budget.bytesRemaining === 0 || budget.operationsRemaining === 0) { budget.truncated = true; @@ -1258,26 +1310,19 @@ export const make = Effect.gen(function* () { budget.bytesRemaining -= readSize; const next = yield* readChunk(readSize); if (Option.isNone(next)) { - return readLastRecord(); + return yield* parse(readLastRecord); } bytesRead += next.value.byteLength; - remaining += decoder.decode(next.value, { stream: true }); - const lines = remaining.split("\n"); - remaining = lines.pop() ?? ""; - - for (const line of lines) { - if (!reserveRecord()) return null; - const cwd = extractCwd(line.trim(), source); - if (cwd !== null) return cwd; - } + const result = yield* parse(() => scanChunk(next.value)); + if (result !== undefined) return result; } if (bytesRead < size) { budget.truncated = true; return null; } - return readLastRecord(); + return yield* parse(readLastRecord); }), ), ), From d1a6c35f7382beead7fb3125e530baf50a60786d Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 14:42:29 +0100 Subject: [PATCH 63/74] fix(server): keep PowerPoint slides with alternate relationship prefixes (#41454) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 17 ++++++++++++++++- .../src/provider/userInputAttachments.test.ts | 4 +++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index a381ede3cc138..47e9b2a57f107 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -149,6 +149,20 @@ function xml(source: string, extension: string): XmlNode { const children = (node: XmlNode | undefined) => node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? []; +function slideRelationshipId(slide: XmlNode, inheritedAttributes: XmlNode["attrs"]) { + for (const [name, value] of Object.entries(slide.attrs)) { + if (!name.endsWith(":id")) continue; + const binding = `xmlns:${name.slice(0, -3)}`; + const namespace = slide.attrs[binding] ?? inheritedAttributes[binding]; + if ( + namespace === "http://schemas.openxmlformats.org/officeDocument/2006/relationships" || + namespace === "http://purl.oclc.org/ooxml/officeDocument/relationships" + ) + return value; + } + return slide.attrs["r:id"] ?? slide.attrs.id; +} + function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean { // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes. // Keep one when no Choice carries text, such as a chart with a VML caption. @@ -765,10 +779,11 @@ async function* document(path: string, extension: string): AsyncGenerator node.name === "sldIdLst"); + const inheritedAttributes = { ...presentation?.attrs, ...slideList?.attrs }; let index = 0; for (const slide of children(slideList).filter((node) => node.name === "sldId")) { yield `\n\n## Slide ${++index}\n`; - const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id)?.Target; + const target = rels.get(slideRelationshipId(slide, inheritedAttributes))?.Target; if (!target) { skip(`slide relationship ${index}`); continue; diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index e81c404c4aef1..67c4b1f785b1f 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -1021,7 +1021,9 @@ describe("question answer paths", () => { "ppt/presentation.xml": ` - + + + From 06f513d50fe926a04b77a0b4d76f613adb32b717 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:01:45 -0800 Subject: [PATCH 64/74] fix(server): another agent's queued message no longer holds back an auto send (#41461) --- .../src/orchestration-v2/Orchestrator.ts | 9 +++- .../SteeringCompletion.integration.test.ts | 50 +++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b95f618d8c1df..6c499c3ea32a7 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -7571,7 +7571,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } - // An agent's automatic send must not overtake an earlier agent message still queued + // An agent's automatic send must not overtake its own earlier message still queued // (e.g. behind /compact), or the agent receives them out of send order. if ( command.deliveryIntent === "auto" && @@ -7588,7 +7588,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuedRuns.map((run) => run.userMessageId), ) .pipe(mapDispatchError(command)); - if ([...queuedMessages.values()].some((message) => message.createdBy === "agent")) { + if ( + [...queuedMessages.values()].some( + (message) => + message.createdBy === "agent" && message.senderThreadId === command.senderThreadId, + ) + ) { dispatchMode = { type: "queue_after_active" }; } } diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index d199eea71440b..229fb66ff8791 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1920,6 +1920,56 @@ it.effect("delivers agent messages queued behind /compact before a later one ste }), ); +// regression: #41455 one sender's queued message holds back another sender's automatic steer +it.effect("an agent's automatic send steers past another sender's queued message", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "agent-steer-past-other-sender", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const active = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "running", + )!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("send-first"), + threadId, + messageId: MessageId.make("message:queued-first"), + text: "queued first", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:sender-a"), + }); + yield* worker.drain(); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("send-urgent"), + threadId, + messageId: MessageId.make("message:urgent"), + text: "urgent", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: active.id }, + deliveryIntent: "auto", + createdBy: "agent", + creationSource: "mcp", + senderThreadId: ThreadId.make("thread:sender-c"), + }); + yield* worker.drain(); + + assert.lengthOf(started, 1); + assert.deepEqual( + steered.map((text) => text.split("\n").at(-1)), + ["urgent"], + ); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #33454 a steer that restarts a completion wake run left its cohort claimed forever const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( harness: Pick< From c977a70fd63be83281fb637ff2a502721f9d6ffd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:19:57 -0800 Subject: [PATCH 65/74] feat(scripts): server metrics record machine load and derive noise floors from A/A runs (#41370) Co-authored-by: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 292 ++++++++++++++++++++++++++----- scripts/server-metrics.test.ts | 156 ++++++++++++++++- scripts/server-metrics.ts | 170 +++++++++++++++++- 3 files changed, 565 insertions(+), 53 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index c11cfca1589a7..0cd34b23935e9 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -39,8 +39,19 @@ const Soak = Schema.Struct({ rssMBPerHour: Schema.Number, }); +const MachineState = Schema.Struct({ + /** The highest 1-minute load average read through the run; none on Windows. */ + load1: Schema.NullOr(Schema.Number), + /** Cores other node, T3 and agent processes kept busy over the run; Linux only. */ + otherCpuCores: Schema.NullOr(Schema.Number), + minutes: Schema.Number, +}); +export type MachineState = typeof MachineState.Type; + /** One pass over the scenarios. */ export const Measured = Schema.Struct({ + /** What else the machine was doing during the pass; never compared, only warned about. */ + machine: Schema.optional(MachineState), startup: Schema.optional(Schema.Struct({ readyMs: Schema.Number })), rest: Schema.optional(Window), firstWord: Schema.optional(Schema.Struct({ inPlace: FirstWord, worktree: FirstWord })), @@ -202,20 +213,103 @@ export function flatten(measured: Measured): Map { return values; } -function noiseFloor(metric: string) { - if (metric.startsWith("scaling.")) return metric.endsWith("cpuPctPerThread") ? 0.2 : 2; - if (metric.startsWith("soak.")) return 20; - if (metric.endsWith("cpuPct")) return 1; - if (metric.endsWith("wakeupsPerSec")) return 20; - if (metric.endsWith("MB")) return 15; - if (metric.endsWith("KB")) return 20; - if (metric.includes(".shellMs.") || metric.includes(".openMs.")) return 50; - if (metric.endsWith("loopDelayP50Ms")) return 2; - if (metric.endsWith("loopDelayP99Ms")) return 5; - if (metric.endsWith("loopDelayMaxMs")) return 20; - if (metric.endsWith("gcPauseMs")) return 10; - if (metric.endsWith("gcCount")) return 20; - return 300; +/** + * How far a metric moves between runs of the same commit, and whether it moves little enough to + * gate on. First match wins. Re-derive from A/A files with `server-metrics noise`; see + * docs/internals/performance-regressions.md for the runs these came from. + */ +export interface NoiseRule { + readonly pattern: RegExp; + /** Absolute change a metric must clear on top of the relative threshold. */ + readonly floor: number; + /** False for metrics an A/A run moves too far to gate on: shown, never counted. */ + readonly gate: boolean; +} + +/** Shown, never counted: these A/A intervals were wider than half the metric (see `noise`). */ +const informational = (pattern: RegExp): NoiseRule => ({ pattern, floor: 0, gate: false }); + +// Estimated from A/A runs on cups (16 cores, load 1 to 20) on 2026-11-23, with and without the +// agent scope, rounded up and taking the larger of the two. +// busy and soak had no A/A run and keep the earlier floors. +export const NOISE_RULES: ReadonlyArray = [ + informational(/loopDelayP50Ms$/), + informational(/^(rest|quiet|streaming|clients\.attached\.\d+)\.loopDelay(P99|Max)Ms$/), + informational(/^(rest|quiet|clients\.attached\.\d+)\.gc(Count|PauseMs)$/), + informational(/^(streaming|pipeline)\.gcPauseMs$/), + informational(/^(pipeline\.loopDelayMaxMs|clients\.storm\.loopDelayP99Ms|quiet\.cpuPct)$/), + informational(/^scaling\.(cpuPct|wakeups)PerThread$/), + informational(/^clients\.attached\.\d+\.(cpuPct|wakeupsPerSec)$/), + informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/), + { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true }, + { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true }, + { pattern: /^soak\./, floor: 20, gate: true }, + { pattern: /^startup\.readyMs$/, floor: 600, gate: true }, + { pattern: /^firstWord\./, floor: 600, gate: true }, + { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, + { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true }, + { pattern: /^clients\.storm\.resubscribedMs$/, floor: 200, gate: true }, + { pattern: /^rest\.cpuPct$/, floor: 1, gate: true }, + { pattern: /cpuPct$/, floor: 3.5, gate: true }, + { pattern: /^(rest|quiet)\.wakeupsPerSec$/, floor: 12, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 110, gate: true }, + { pattern: /rssPeakMB$/, floor: 16, gate: true }, + { pattern: /rssMB$/, floor: 4, gate: true }, + { pattern: /heapAfterGcMB$/, floor: 1, gate: true }, + { pattern: /MB$/, floor: 15, gate: true }, + { pattern: /KB$/, floor: 20, gate: true }, + { pattern: /\.(shellMs|openMs)\./, floor: 50, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 3, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 22, gate: true }, + { pattern: /gcPauseMs$/, floor: 55, gate: true }, + { pattern: /gcCount$/, floor: 6, gate: true }, + { pattern: /./, floor: 300, gate: true }, +]; + +export function noiseRule(metric: string, rules: ReadonlyArray = NOISE_RULES) { + return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true }; +} + +/** Fields that describe a run rather than measure it. */ +const isMetric = (metric: string) => + !( + metric === "soak.minutes" || + metric.startsWith("machine.") || + metric.endsWith("loopSamples") || + metric === "busy.projects" || + metric === "busy.ballastMB" || + metric.endsWith(".clients") || + metric.endsWith(".threads") || + metric === "busy.largeThread.messages" || + metric.startsWith("scaling.points") + ); + +/** + * A run is loaded when other node, T3 and agent processes kept this share of the cores busy, or, + * where that is unknown, when the 1-minute load passed this much per CPU. The load counts the + * run's own agents too, so it is only the fallback. + */ +export const HEAVY_LOAD_PER_CPU = 0.75; +export const HEAVY_OTHER_CPU_SHARE = 0.25; + +/** One line per side whose runs shared the machine with heavy load, so its numbers are suspect. */ +export function loadWarnings(side: string, metrics: ServerMetrics) { + const cpus = typeof metrics.meta.cpus === "number" ? metrics.meta.cpus : null; + if (cpus === null) return []; + const loaded = metrics.runs.flatMap(({ machine }) => + machine && + (machine.otherCpuCores === null + ? (machine.load1 ?? 0) >= cpus * HEAVY_LOAD_PER_CPU + : machine.otherCpuCores >= cpus * HEAVY_OTHER_CPU_SHARE) + ? [machine] + : [], + ); + if (loaded.length === 0) return []; + const worstLoad = Math.max(...loaded.map(({ load1 }) => load1 ?? 0)); + const worstOther = Math.max(...loaded.map(({ otherCpuCores }) => otherCpuCores ?? 0)); + return [ + `${side} ran under heavy load in ${loaded.length} of ${metrics.runs.length} runs (load up to ${worstLoad} on ${cpus} CPUs, other node/T3/agent processes up to ${worstOther} cores); rerun on a quieter machine before trusting a change`, + ]; } const median = (values: ReadonlyArray) => { @@ -241,16 +335,133 @@ export function bootstrapMedianDifference(a: ReadonlyArray, b: ReadonlyA return [differences[49]!, differences[1_949]!] as const; } -export function compareMetrics(before: ServerMetrics, after: ServerMetrics, threshold = 10) { - const collect = (metrics: ServerMetrics) => { - const values = new Map(); - for (const run of metrics.runs) { - for (const [metric, value] of flatten(run)) { - values.set(metric, [...(values.get(metric) ?? []), value]); - } +/** + * False for a wakeup count where only one side had the delay sampler: wakeups include the + * sampler's only when `loopSamples` sits beside them, so the two measured different things. The + * per-thread fit comes from the quiet windows, so it follows their method. + */ +function sameWakeupMethod( + metric: string, + a: ReadonlyMap, + b: ReadonlyMap, +) { + const window = + metric === "scaling.wakeupsPerThread" + ? "quiet." + : metric.endsWith("wakeupsPerSec") + ? metric.slice(0, -"wakeupsPerSec".length) + : ""; + return !window || a.has(`${window}loopSamples`) === b.has(`${window}loopSamples`); +} + +/** CPU seconds spent between two reads keyed by pid and start time; a process that exited is lost. */ +export function competingBetween( + before: ReadonlyMap, + after: ReadonlyMap, +) { + return [...after].reduce((total, [key, seconds]) => total + seconds - (before.get(key) ?? 0), 0); +} + +/** Why a directory is not an A/A pair: its files must record one and the same commit. */ +export function noisePairProblem(dir: string, a: ServerMetrics, b: ServerMetrics) { + const commits = [a.meta.commit, b.meta.commit]; + if (commits.some((commit) => typeof commit !== "string" || commit === "")) { + return `${dir}: a.json or b.json records no commit, so it cannot be shown to be an A/A run`; + } + return commits[0] === commits[1] + ? undefined + : `${dir}: a.json is ${commits[0]} and b.json ${commits[1]}; noise floors need one commit against itself`; +} + +/** Every metric's values across a file's runs. */ +const collect = (metrics: ServerMetrics) => { + const values = new Map(); + for (const run of metrics.runs) { + for (const [metric, value] of flatten(run)) { + values.set(metric, [...(values.get(metric) ?? []), value]); } - return values; - }; + } + return values; +}; + +/** Two significant digits, rounded up, so a derived floor never sits under what was seen. */ +const ceilSignificant = (value: number) => { + if (value <= 0) return 0; + const step = 10 ** (Math.floor(Math.log10(value)) - 1); + return round(Math.ceil(value / step) * step, 6); +}; + +/** An A/A interval wider than this share of a metric's median makes it informational. */ +export const NOISY_SHARE = 0.5; + +export interface NoiseRow { + readonly metric: string; + readonly median: number; + /** The widest half-width of an A/A pair's 95% interval of the median difference. */ + readonly halfWidth: number; + /** The largest |median(A) - median(B)| over the A/A pairs. */ + readonly aaDifference: number; + readonly floor: number; + readonly suggestedFloor: number; + readonly gate: boolean; + readonly suggestedGate: boolean; +} + +/** + * Each metric's A/A spread as `compare` sees it: the 95% interval of the median difference. The + * estimated floor (half the widest half-width, or the A/A median difference if larger) is how far + * an A/A interval must miss zero to flag. It is an estimate, not a bound. + */ +export function noiseReport( + pairs: ReadonlyArray, + rules: ReadonlyArray = NOISE_RULES, +) { + const found = new Map(); + for (const [before, after] of pairs) { + const a = collect(before); + const b = collect(after); + for (const [metric, x] of a) { + const y = b.get(metric); + if (!y || !isMetric(metric) || !sameWakeupMethod(metric, a, b)) continue; + const [low, high] = bootstrapMedianDifference(x, y); + const entry = found.get(metric) ?? { medians: [], halfWidth: 0, aaDifference: 0 }; + entry.medians.push(median([...x, ...y])); + entry.halfWidth = Math.max(entry.halfWidth, (high - low) / 2); + entry.aaDifference = Math.max(entry.aaDifference, Math.abs(median(y) - median(x))); + found.set(metric, entry); + } + } + const rows: NoiseRow[] = [...found].map(([metric, entry]) => { + const middle = median(entry.medians); + const rule = noiseRule(metric, rules); + return { + metric, + median: round(middle, 2), + halfWidth: round(entry.halfWidth, 2), + aaDifference: round(entry.aaDifference, 2), + floor: rule.floor, + suggestedFloor: ceilSignificant(Math.max(entry.halfWidth / 2, entry.aaDifference)), + gate: rule.gate, + suggestedGate: entry.halfWidth <= Math.abs(middle) * NOISY_SHARE, + }; + }); + const lines = [ + "| metric | median | ± A/A interval | A/A diff | floor | estimated floor | gated | suggest gating |", + "| :-- | --: | --: | --: | --: | --: | :-: | :-: |", + ...rows.map( + (row) => + `| ${row.metric} | ${row.median} | ${row.halfWidth} | ${row.aaDifference} | ${row.floor} | ${row.suggestedFloor}${row.suggestedFloor > row.floor ? " ⚠" : ""} | ${row.gate ? "yes" : "no"} | ${row.suggestedGate ? "yes" : "no"} |`, + ), + ]; + return { rows, table: lines.join("\n") }; +} + +export function compareMetrics( + before: ServerMetrics, + after: ServerMetrics, + threshold = 10, + rules: ReadonlyArray = NOISE_RULES, +) { const a = collect(before); const b = collect(after); const lines = [ @@ -264,18 +475,9 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const regressed: string[] = []; const improved: string[] = []; let compared = 0; + const informational: string[] = []; for (const metric of new Set([...a.keys(), ...b.keys()])) { - if ( - metric === "soak.minutes" || - metric.endsWith("loopSamples") || - metric === "busy.projects" || - metric === "busy.ballastMB" || - metric === "clients.storm.clients" || - metric === "busy.largeThread.messages" || - metric.startsWith("scaling.points") - ) { - continue; - } + if (!isMetric(metric)) continue; const x = a.get(metric); const y = b.get(metric); if (!x || !y) { @@ -285,13 +487,7 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre // Wakeups include the delay sampler's only when `loopSamples` sits beside them, so a file // from before the sampler and one from after measured different things. The per-thread fit // comes from the quiet windows. - const window = - metric === "scaling.wakeupsPerThread" - ? "quiet." - : metric.endsWith("wakeupsPerSec") - ? metric.slice(0, -"wakeupsPerSec".length) - : ""; - if (window && a.has(`${window}loopSamples`) !== b.has(`${window}loopSamples`)) { + if (!sameWakeupMethod(metric, a, b)) { lines.push(`| ${metric} | ${median(x)} | ${median(y)} | not comparable | | |`); continue; } @@ -299,12 +495,15 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre const mx = median(x); const my = median(y); // A change counts only past both the relative threshold and the absolute noise floor. - const limit = Math.max(noiseFloor(metric), (Math.abs(mx) * threshold) / 100); + const rule = noiseRule(metric, rules); + const limit = Math.max(rule.floor, (Math.abs(mx) * threshold) / 100); const repeated = x.length > 1 && y.length > 1; const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; - const verdict = low > limit ? "worse" : high < -limit ? "better" : ""; - if (verdict === "worse") regressed.push(metric); - if (verdict === "better") improved.push(metric); + const moved = low > limit ? "worse" : high < -limit ? "better" : ""; + if (moved && !rule.gate) informational.push(metric); + else if (moved === "worse") regressed.push(metric); + else if (moved === "better") improved.push(metric); + const verdict = rule.gate ? moved : moved ? `${moved} (noisy, not gated)` : "noisy"; const percent = mx === 0 ? (my === 0 ? 0 : Infinity) : ((my - mx) / Math.abs(mx)) * 100; const shown = Number.isFinite(percent) ? `${percent > 0 ? "+" : ""}${Math.round(percent)}%` @@ -314,7 +513,8 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre `| ${metric} | ${round(mx, 2)} | ${round(my, 2)} | ${shown} | ${interval} | ${verdict} |`, ); } - return { table: lines.join("\n"), regressed, improved, compared }; + const warnings = [...loadWarnings("before", before), ...loadWarnings("after", after)]; + return { table: lines.join("\n"), regressed, improved, informational, compared, warnings }; } const CallFrame = Schema.Struct({ diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 760c850dbbbea..de3237d3c0d23 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -3,9 +3,13 @@ import { describe, expect, it } from "vite-plus/test"; import { compareMetrics, + competingBetween, activityRenewalMissed, heapGrowth, + loadWarnings, nextActivityReport, + noiseReport, + noisePairProblem, parsePsCpuTime, parseRunSelection, pathRewrites, @@ -43,6 +47,17 @@ const base: Quiet = { cpuPct: 0.3, wakeupsPerSec: 7, rssPeakMB: 500 }; const cpuRuns = (...values: number[]) => quietRuns(...values.map((cpuPct) => ({ ...base, cpuPct }))); +// Fixed floors, so these cases test how compare gates rather than the calibrated table. +const gatedRules = [ + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /wakeupsPerSec$/, floor: 20, gate: true }, + { pattern: /MB$/, floor: 15, gate: true }, + { pattern: /loopDelayP99Ms$/, floor: 5, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: true }, + { pattern: /gcPauseMs$/, floor: 10, gate: true }, + { pattern: /./, floor: 300, gate: true }, +]; + describe("compareMetrics", () => { it.each([ ["a CPU jump past both the percentage and the floor", { cpuPct: 18.6 }, ["quiet.cpuPct"], []], @@ -60,7 +75,12 @@ describe("compareMetrics", () => { ["quiet.rssPeakMB"], ], ])("one run each: %s", (_name, change, regressed, improved) => { - const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change })); + const result = compareMetrics( + quietRuns(base), + quietRuns({ ...base, ...change }), + 10, + gatedRules, + ); expect(result.regressed).toEqual(regressed); expect(result.improved).toEqual(improved); }); @@ -75,10 +95,10 @@ describe("compareMetrics", () => { it("flags repeated runs only when the whole interval clears the limit", () => { const steady = cpuRuns(26.1, 27.4, 25.8); const fixed = cpuRuns(2.2, 2.5, 2.1); - expect(compareMetrics(steady, fixed).improved).toContain("quiet.cpuPct"); - expect(compareMetrics(fixed, steady).regressed).toContain("quiet.cpuPct"); + expect(compareMetrics(steady, fixed, 10, gatedRules).improved).toContain("quiet.cpuPct"); + expect(compareMetrics(fixed, steady, 10, gatedRules).regressed).toContain("quiet.cpuPct"); // The medians differ by 2.8 points, past the floor, but a resampled median can match. - expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9)).regressed).toEqual([]); + expect(compareMetrics(fixed, cpuRuns(2.2, 5, 9), 10, gatedRules).regressed).toEqual([]); }); it("reads a file written before loop delay and GC were recorded", () => { @@ -129,6 +149,134 @@ describe("compareMetrics", () => { }); }); +describe("compareMetrics with noise rules", () => { + const rules = [ + { pattern: /cpuPct$/, floor: 1, gate: true }, + { pattern: /loopDelayMaxMs$/, floor: 20, gate: false }, + { pattern: /./, floor: 1_000, gate: true }, + ]; + it.each([ + ["a gated metric past its floor", { cpuPct: 5 }, ["quiet.cpuPct"], []], + ["an ungated metric far past its floor", { loopDelayMaxMs: 300 }, [], ["quiet.loopDelayMaxMs"]], + ["an ungated metric under its floor", { loopDelayMaxMs: 20 }, [], []], + ])("%s", (_name, change, regressed, informational) => { + const result = compareMetrics(quietRuns(base), quietRuns({ ...base, ...change }), 10, rules); + expect(result.regressed).toEqual(regressed); + expect(result.informational).toEqual(informational); + }); + + it("marks an ungated metric in the table either way", () => { + const result = compareMetrics(quietRuns(base), quietRuns(base), 10, rules); + expect(result.table).toContain("| quiet.loopDelayMaxMs | 8 | 8 | 0% | | noisy |"); + }); +}); + +describe("noisePairProblem", () => { + const at = (commit: string | null): ServerMetrics => ({ meta: { ...meta, commit }, runs: [] }); + it.each([ + ["one commit against itself", at("abc"), at("abc"), undefined], + [ + "an A/B directory", + at("abc"), + at("def"), + "ab-out: a.json is abc and b.json def; noise floors need one commit against itself", + ], + [ + "a file with no commit", + at(null), + at(null), + "ab-out: a.json or b.json records no commit, so it cannot be shown to be an A/A run", + ], + ])("%s", (_name, a, b, problem) => { + expect(noisePairProblem("ab-out", a, b)).toBe(problem); + }); +}); + +describe("competingBetween", () => { + it.each([ + ["a process that kept running", [["10:500", 900]], [["10:500", 960]], 60], + ["a new process, counted whole", [], [["11:700", 30]], 30], + ["a reused pid is a new process", [["10:500", 900]], [["10:800", 300]], 300], + ["a process that exited is lost", [["10:500", 900]], [], 0], + ] as const)("%s", (_name, before, after, seconds) => { + expect(competingBetween(new Map(before), new Map(after))).toBe(seconds); + }); +}); + +describe("loadWarnings", () => { + const loaded = (cpus: number | null, ...machines: Array<[number | null, number | null]>) => + ({ + meta: { ...meta, cpus }, + runs: machines.map(([load1, otherCpuCores]) => ({ + machine: { load1, otherCpuCores, minutes: 10 }, + })), + }) satisfies ServerMetrics; + it.each([ + ["a quiet machine", loaded(16, [4, 1], [5, 2]), 0], + ["load past 0.75 per CPU with other processes unknown", loaded(16, [4, null], [12.5, null]), 1], + ["high load from the run's own agents", loaded(16, [21, 1]), 0], + ["other processes on a quarter of the cores", loaded(16, [4, 4.1]), 1], + ["no CPU count", loaded(null, [40, 40]), 0], + ["no machine state, as in older files", { meta: { ...meta, cpus: 16 }, runs: [{}] }, 0], + ])("%s", (_name, metrics, count) => { + expect(loadWarnings("before", metrics)).toHaveLength(count); + }); + + it("names the worst run", () => { + expect(loadWarnings("after", loaded(16, [13, 4.5], [14.2, 5]))[0]).toContain( + "after ran under heavy load in 2 of 2 runs (load up to 14.2 on 16 CPUs, other node/T3/agent processes up to 5 cores)", + ); + }); + + it("is reported by compareMetrics", () => { + expect(compareMetrics(quietRuns(base), loaded(16, [20, null])).warnings).toHaveLength(1); + }); +}); + +describe("noiseReport", () => { + it.each([ + // Resampled medians differ by -0.3 to 1.1: half-width 0.7, so the floor is 0.35. + ["the A/A interval", cpuRuns(2, 2.2, 2.4), cpuRuns(2.1, 3.1, 2.3), 0.7, 0.1, 0.35], + // Constant sides: no interval, and medians 2 and 3.25 differ by 1.25. + ["the A/A median difference", cpuRuns(2, 2), cpuRuns(3.25, 3.25), 0, 1.25, 1.3], + ])("estimates a floor from %s, rounded up", (_name, a, b, halfWidth, aaDifference, floor) => { + const [row] = noiseReport([[a, b]]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); + expect(row).toMatchObject({ halfWidth, aaDifference, suggestedFloor: floor }); + }); + + it("leaves out wakeups counted with the delay sampler on one side only", () => { + const sampled: ServerMetrics = { + meta, + runs: quietRuns({ ...base, wakeupsPerSec: 160 }).runs.map((run) => ({ + quiet: { ...run.quiet, loopSamples: 2_900 }, + })), + }; + const metrics = noiseReport([[quietRuns(base), sampled]]).rows.map(({ metric }) => metric); + expect(metrics).not.toContain("quiet.wakeupsPerSec"); + expect(metrics).toContain("quiet.cpuPct"); + }); + + it("takes the widest pair, and calls a metric noisy when its interval passes half its median", () => { + const quiet = [cpuRuns(2, 2.1), cpuRuns(2, 2.1)] as const; + const wild = [cpuRuns(1, 4), cpuRuns(2, 2)] as const; + const [row] = noiseReport([quiet, wild]).rows.filter(({ metric }) => metric === "quiet.cpuPct"); + expect(row?.halfWidth).toBe(1.5); + expect(row?.suggestedGate).toBe(false); + }); + + it("leaves out fields that describe a run", () => { + const withMachine = (metrics: ServerMetrics): ServerMetrics => ({ + ...metrics, + runs: metrics.runs.map((run) => ({ + ...run, + machine: { load1: 3, otherCpuCores: 1, minutes: 9 }, + })), + }); + const rows = noiseReport([[withMachine(cpuRuns(1)), withMachine(cpuRuns(1))]]).rows; + expect(rows.some(({ metric }) => metric.startsWith("machine."))).toBe(false); + }); +}); + describe("compareMetrics on the busy shell snapshot", () => { const window = { cpuPct: 1, wakeupsPerSec: 10, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 }; const busyRun = (shellMs: number, shellKB: number) => diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 8ab475f38a5ad..7b814efcbdbf5 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -28,6 +28,7 @@ import * as Random from "effect/Random"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { Argument, Command, Flag } from "effect/cli"; @@ -58,6 +59,10 @@ import { HeapSnapshot, heapByConstructor, heapGrowth, + competingBetween, + loadWarnings, + noiseReport, + noisePairProblem, round, ServerMetrics, slope, @@ -70,6 +75,7 @@ import { parseRunSelection, summarizeProfiles, type FirstWord, + type MachineState, type Measured, type ProfileSummary, type Window, @@ -1333,6 +1339,7 @@ interface RunOptions { const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOptions) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const machine = yield* watchMachine; const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-" }); const api = yield* serveFakeAnthropic(); const environment: Environment = { @@ -1619,6 +1626,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + measured.machine = yield* machine; return { measured: measured as Measured, profiles, soakHeapGrowth }; }, Effect.scoped); @@ -1641,6 +1649,110 @@ const machineLoad = Effect.gen(function* () { ), ); +/** Comm names of the processes that compete with a measured server on a developer's machine. */ +const COMPETING = /^(node|node-MainThread|t3|claude|codex|vite|pnpm)/; + +/** + * CPU seconds of every node, T3, claude or codex process outside this script's own tree, keyed by + * pid and start time so a reused pid is a new process. Linux only; elsewhere none, and the run + * records only the load average. + */ +const competingCpuSeconds = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform !== "linux") return Option.none>(); + const fs = yield* FileSystem.FileSystem; + const self = Number(yield* fs.readLink("/proc/self")); + const parents = new Map(); + const cpu = new Map(); + for (const entry of yield* fs.readDirectory("/proc")) { + if (!/^\d+$/.test(entry)) continue; + const stat = yield* fs + .readFileString(`/proc/${entry}/stat`) + .pipe(Effect.orElseSucceed(() => "")); + const open = stat.indexOf(" ("); + const close = stat.lastIndexOf(") "); + if (open < 0 || close < 0) continue; + const fields = stat.slice(close + 2).split(" "); + const pid = Number(entry); + parents.set(pid, Number(fields[1])); + if (COMPETING.test(stat.slice(open + 2, close))) { + // Fields after the name start at the state, field 3: utime 14, stime 15, starttime 22. + cpu.set(pid, { + key: `${pid}:${fields[19]}`, + seconds: (Number(fields[11]) + Number(fields[12])) / 100, + }); + } + } + const ours = (pid: number) => { + for (let at: number | undefined = pid; at !== undefined && at > 1; at = parents.get(at)) { + if (at === self) return true; + } + return false; + }; + return Option.some( + new Map([...cpu].filter(([pid]) => !ours(pid)).map(([, { key, seconds }]) => [key, seconds])), + ); +}).pipe(Effect.orElseSucceed(() => Option.none>())); + +/** How often the machine watcher reads competing CPU; a process that exits loses at most this. */ +const MACHINE_SAMPLE_SECONDS = 10; + +const load1 = Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + if (platform === "win32") return Option.none(); + if (platform === "linux") { + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString("/proc/loadavg").pipe(Effect.option); + return Option.map(text, (value) => Number(value.split(" ")[0])); + } + const text = yield* output("sysctl", ["-n", "vm.loadavg"]); + return Option.map(text, (value) => Number(value.replace(/[{}]/g, "").trim().split(/\s+/)[0])); +}).pipe(Effect.map(Option.filter(Number.isFinite))); + +/** + * Starts watching the machine for one run; the returned effect reads what competed with it: the + * highest 1-minute load seen and the cores other T3, node and agent processes kept busy. + */ +const watchMachine = Effect.gen(function* () { + const startedAt = yield* nowMs; + const loads: number[] = []; + // Unknown (none) once any read fails, so a partial sum never passes for the whole run. + let competing: Option.Option = Option.some(0); + let previous = yield* competingCpuSeconds; + if (Option.isNone(previous)) competing = Option.none(); + // The periodic and final reads would otherwise interleave across the await below. + const reading = yield* Semaphore.make(1); + const read = Effect.gen(function* () { + loads.push(...Option.toArray(yield* load1)); + if (Option.isNone(previous) || Option.isNone(competing)) return; + const next = yield* competingCpuSeconds; + if (Option.isNone(next)) { + competing = Option.none(); + return; + } + competing = Option.some(competing.value + competingBetween(previous.value, next.value)); + previous = next; + }).pipe(reading.withPermits(1)); + yield* read; + // Reading through the run, not only at its ends, keeps a busy process that exits mid-run. + yield* read.pipe( + Effect.delay(Duration.seconds(MACHINE_SAMPLE_SECONDS)), + Effect.forever, + Effect.forkScoped, + ); + return Effect.gen(function* () { + yield* read; + const elapsed = ((yield* nowMs) - startedAt) / 1_000; + const machine: MachineState = { + load1: loads.length ? round(Math.max(...loads), 2) : null, + otherCpuCores: + Option.isSome(competing) && elapsed > 0 ? round(competing.value / elapsed, 2) : null, + minutes: round(elapsed / 60, 1), + }; + return machine; + }); +}); + const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOptions) { const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; @@ -1694,13 +1806,21 @@ const report = Effect.fn("serverMetrics.report")(function* ( after: ServerMetrics, threshold: number, ) { - const { table, regressed, improved, compared } = compareMetrics(before, after, threshold); + const { table, regressed, improved, informational, compared, warnings } = compareMetrics( + before, + after, + threshold, + ); yield* Console.log(table); + for (const warning of warnings) yield* Console.error(`Warning: ${warning}`); if (compared === 0) { return yield* new MetricsError({ message: "the two files share no metric, so nothing was compared", }); } + if (informational.length) { + yield* Console.error(`Moved, but too noisy to gate on: ${informational.join(", ")}`); + } if (improved.length) yield* Console.error(`Better: ${improved.join(", ")}`); if (regressed.length === 0) return; yield* Console.error(`Worse: ${regressed.join(", ")}`); @@ -1937,7 +2057,51 @@ const compareCommand = Command.make( }), ).pipe( Command.withDescription( - "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor (1 CPU point, 20 wakeups/s, 15 MB, 300 ms; per thread 2 MB or 0.2 CPU points). Exits 1 on a regression.", + "Markdown table of two result files, lower is better. With 2+ runs a side, a metric counts only when the 95% bootstrap interval of the median difference clears the threshold and its noise floor, measured from A/A runs (see `noise`). Metrics too noisy to gate on are shown but never counted. Warns when either side ran under heavy machine load. Exits 1 on a regression.", + ), +); + +const noiseCommand = Command.make( + "noise", + { + dirs: Argument.String("dir").pipe( + Argument.withDescription("An `ab` out dir (a.json and b.json) of one commit against itself."), + Argument.atLeast(1), + ), + }, + Effect.fn("serverMetrics.noise")(function* (input) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const read = (file: string) => + fs.readFileString(file).pipe(Effect.flatMap(decodeJson(ServerMetrics))); + const pairs = yield* Effect.forEach(input.dirs, (dir) => + Effect.gen(function* () { + const a = yield* read(path.join(dir, "a.json")); + const b = yield* read(path.join(dir, "b.json")); + const problem = noisePairProblem(dir, a, b); + if (problem !== undefined) return yield* new MetricsError({ message: problem }); + for (const [file, metrics] of [ + ["a.json", a], + ["b.json", b], + ] as const) { + for (const warning of loadWarnings(path.join(dir, file), metrics)) { + yield* Console.error(`Warning: ${warning}`); + } + } + return [a, b] as const; + }), + ); + const { rows, table } = noiseReport(pairs); + if (rows.length === 0) { + return yield* new MetricsError({ + message: "no metric was measured on both sides of any pair, so nothing was calibrated", + }); + } + yield* Console.log(table); + }), +).pipe( + Command.withDescription( + "Spread of every metric over A/A runs (`ab `), an estimated floor covering the half ranges and median differences these runs showed, and which metrics are too noisy to gate on. ⚠ marks a current floor under the estimate. Refuses directories whose two files record different commits.", ), ); @@ -1945,7 +2109,7 @@ const serverMetricsCommand = Command.make("server-metrics").pipe( Command.withDescription( "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", ), - Command.withSubcommands([runCommand, abCommand, compareCommand]), + Command.withSubcommands([runCommand, abCommand, compareCommand, noiseCommand]), ); if (import.meta.main) { From 20419366c39daca3238c65b1c9018772e2f914a0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:22:43 -0800 Subject: [PATCH 66/74] feat(scripts): server metrics measure many threads working at once with one client (#41371) Co-authored-by: Claude Opus 5.5 --- docs/internals/16_performance-regressions.md | 3 + scripts/server-metrics-report.ts | 54 +++- scripts/server-metrics.test.ts | 41 +++ scripts/server-metrics.ts | 259 ++++++++++++++++++- 4 files changed, 343 insertions(+), 14 deletions(-) diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index 0e42c0fa09f3c..135fb95ea6905 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -37,6 +37,9 @@ heap, and first-request latency against a fake Anthropic API and the real `claud isolated runs. - Use `scaling` to separate per-thread cost from fixed server overhead, and `--soak ` to spot rising heap slopes (leaks). +- 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. - Test macOS, Windows, and Linux with `--no-agent-scope`: Linux systemd agent scopes mask per-process polling paths that other platforms run. diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 0cd34b23935e9..70a6e52ec73c4 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -48,6 +48,19 @@ const MachineState = Schema.Struct({ }); export type MachineState = typeof MachineState.Type; +const WorkingPoint = Schema.Struct({ + ...Window.fields, + /** Turns finished inside the window, per minute; higher is better. */ + turnsPerMin: Schema.Number, + /** Send to the agent's first API request. */ + toRequestMs: Spread, + /** The turn's last reply byte to the client seeing the run end. */ + turnEndMs: Spread, + /** Send to the client seeing the run end. */ + turnMs: Spread, +}); +export type WorkingPoint = typeof WorkingPoint.Type; + /** One pass over the scenarios. */ export const Measured = Schema.Struct({ /** What else the machine was doing during the pass; never compared, only warned about. */ @@ -73,6 +86,21 @@ export const Measured = Schema.Struct({ }), }), ), + /** + * N threads in worktrees of their own run editing turns back to back, all at once, with one + * web-like client subscribed to all of them. The scenario to steer server performance by. + */ + working: Schema.optional( + Schema.Struct({ + /** Each window by the number of threads working in it. */ + active: Schema.Record(Schema.String, WorkingPoint), + /** Fits over the windows: what each additional working thread costs. */ + heapMBPerThread: Schema.Number, + rssMBPerThread: Schema.Number, + cpuPctPerThread: Schema.Number, + loopDelayP99MsPerThread: Schema.Number, + }), + ), /** 50 short turns back to back on one thread. */ pipeline: Schema.optional( Schema.Struct({ @@ -244,6 +272,24 @@ export const NOISE_RULES: ReadonlyArray = [ { pattern: /^scaling\.heapMBPerThread$/, floor: 0.06, gate: true }, { pattern: /^scaling\.rssMBPerThread$/, floor: 0.2, gate: true }, { pattern: /^soak\./, floor: 20, gate: true }, + informational(/^working\.(cpuPct|loopDelayP99Ms)PerThread$/), + informational(/^working\.active\.\d+\.(wakeupsPerSec|loopDelayMaxMs|gcPauseMs)$/), + { pattern: /^working\.heapMBPerThread$/, floor: 0.06, gate: true }, + { pattern: /^working\.rssMBPerThread$/, floor: 0.2, gate: true }, + { pattern: /^working\.active\.\d+\.turnsPerMin$/, floor: 4, gate: true }, + { pattern: /^working\.active\.\d+\.toRequestMs\.median$/, floor: 1_100, gate: true }, + { pattern: /^working\.active\.\d+\.turnEndMs\.median$/, floor: 1_700, gate: true }, + { + pattern: /^working\.active\.\d+\.(toRequestMs\.p90|turnMs\.median)$/, + floor: 1_900, + gate: true, + }, + { pattern: /^working\.active\.\d+\.turnEndMs\.p90$/, floor: 2_200, gate: true }, + { pattern: /^working\.active\.\d+\.turnMs\.p90$/, floor: 2_800, gate: true }, + // Peak RSS while 20 agents run swings by a checkpoint's git children; the settled RSS does not. + { pattern: /^working\.active\.\d+\.rssPeakMB$/, floor: 170, gate: true }, + { pattern: /^working\.active\.\d+\.(cpuPct|loopDelayP99Ms)$/, floor: 5, gate: true }, + { pattern: /^working\.active\.\d+\.gcCount$/, floor: 8, gate: true }, { pattern: /^startup\.readyMs$/, floor: 600, gate: true }, { pattern: /^firstWord\./, floor: 600, gate: true }, { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, @@ -270,6 +316,9 @@ export function noiseRule(metric: string, rules: ReadonlyArray = NOIS return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true }; } +/** Throughput, where a drop is the regression. */ +export const higherIsBetter = (metric: string) => metric.endsWith("PerMin"); + /** Fields that describe a run rather than measure it. */ const isMetric = (metric: string) => !( @@ -465,7 +514,7 @@ export function compareMetrics( const a = collect(before); const b = collect(after); const lines = [ - "### Server metrics (lower is better)", + "### Server metrics (lower is better, except throughput per minute)", "", `before \`${before.meta.commit}\` (${before.runs.length} runs), after \`${after.meta.commit}\` (${after.runs.length} runs), ${after.meta.platform}${after.meta.noAgentScope ? ", no agent scope" : ""}`, "", @@ -499,7 +548,8 @@ export function compareMetrics( const limit = Math.max(rule.floor, (Math.abs(mx) * threshold) / 100); const repeated = x.length > 1 && y.length > 1; const [low, high] = repeated ? bootstrapMedianDifference(x, y) : [my - mx, my - mx]; - const moved = low > limit ? "worse" : high < -limit ? "better" : ""; + const up = low > limit ? "worse" : high < -limit ? "better" : ""; + const moved = higherIsBetter(metric) ? { worse: "better", better: "worse", "": "" }[up] : up; if (moved && !rule.gate) informational.push(metric); else if (moved === "worse") regressed.push(metric); else if (moved === "better") improved.push(metric); diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index de3237d3c0d23..adc86fddce588 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -277,6 +277,47 @@ describe("noiseReport", () => { }); }); +describe("compareMetrics on working throughput", () => { + const working = (turnsPerMin: number) => + ({ + meta, + runs: [ + { + working: { + active: { + "20": { + ...loopAtRest, + cpuPct: 90, + wakeupsPerSec: 1_600, + rssPeakMB: 700, + rssMB: 560, + heapAfterGcMB: 218, + turnsPerMin, + toRequestMs: { median: 4_000, p90: 9_000 }, + turnEndMs: { median: 16_000, p90: 25_000 }, + turnMs: { median: 24_000, p90: 36_000 }, + }, + }, + heapMBPerThread: 0.2, + rssMBPerThread: 0.8, + cpuPctPerThread: 0, + loopDelayP99MsPerThread: 0, + }, + }, + ], + }) satisfies ServerMetrics; + const rules = [{ pattern: /turnsPerMin$/, floor: 2, gate: true }]; + it.each([ + ["fewer turns a minute", 20, ["working.active.20.turnsPerMin"], []], + ["more turns a minute", 45, [], ["working.active.20.turnsPerMin"]], + ["a move under the floor", 34, [], []], + ])("%s", (_name, turnsPerMin, regressed, improved) => { + const result = compareMetrics(working(33), working(turnsPerMin), 5, rules); + expect(result.regressed).toEqual(regressed); + expect(result.improved).toEqual(improved); + }); +}); + describe("compareMetrics on the busy shell snapshot", () => { const window = { cpuPct: 1, wakeupsPerSec: 10, rssPeakMB: 500, rssMB: 500, heapAfterGcMB: 200 }; const busyRun = (shellMs: number, shellKB: number) => diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 7b814efcbdbf5..54fc28693b3fd 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -19,6 +19,7 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -33,6 +34,9 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { Argument, Command, Flag } from "effect/cli"; import { + CommandId, + MessageId, + type OrchestrationV2ThreadStreamItem, ORCHESTRATION_PROTOCOL_HEADER, ORCHESTRATION_PROTOCOL_VERSION, ORCHESTRATION_PROTOCOL_VERSION_TEXT, @@ -77,6 +81,7 @@ import { type FirstWord, type MachineState, type Measured, + type WorkingPoint, type ProfileSummary, type Window, } from "./server-metrics-report.ts"; @@ -84,8 +89,12 @@ import { const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; +/** A prompt holding this streams a reply that ends in a Write tool call, then a short answer. */ +const EDIT_MARKER = "[[edit-files]]"; /** Sequential turns in the pipeline scenario. */ const PIPELINE_TURNS = 50; +/** Threads working at once in each window of the working scenario. */ +const WORKING_THREADS = [5, 10, 20]; /** Clients that drop and reconnect at once in the clients scenario. */ const STORM_CLIENTS = 20; /** Event-loop delay sampling interval; each sample wakes the loop once. */ @@ -128,6 +137,8 @@ interface ApiRequest { readonly agent: boolean; readonly stream: boolean; readonly marker: string | undefined; + /** The request carries a tool result, so it is a turn's follow-up rather than its start. */ + readonly toolResult: boolean; /** When the reply's last event was produced; streamed replies only. */ endedAt?: number; } @@ -136,8 +147,26 @@ const MessagesRequest = Schema.Struct({ stream: Schema.optional(Schema.Boolean), model: Schema.optional(Schema.String), tools: Schema.optional(Schema.Array(Schema.Unknown)), + messages: Schema.optional( + Schema.Array(Schema.Struct({ role: Schema.String, content: Schema.Unknown })), + ), }); +/** Whether the newest message hands back a tool's result. */ +const endsInToolResult = (messages: typeof MessagesRequest.Type.messages) => { + const content = messages?.at(-1)?.content; + return ( + Array.isArray(content) && + content.some( + (block: unknown) => + typeof block === "object" && + block !== null && + "type" in block && + block.type === "tool_result", + ) + ); +}; + /** Streams a canned reply to every Messages request; a prompt holding SLOW_MARKER streams slowly. */ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(function* () { const requests: ApiRequest[] = []; @@ -157,7 +186,9 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio Effect.orElseSucceed((): typeof MessagesRequest.Type => ({})), ); const streamed = body.stream === true; + const toolResult = endsInToolResult(body.messages); const entry: ApiRequest = { + toolResult, at: yield* nowMs, stream: streamed, // Title and branch-name jobs carry only their structured-output tool; the agent carries many. @@ -183,10 +214,13 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio const event = (name: string, data: object) => `event: ${name}\ndata: ${encodeJson({ type: name, ...data })}\n\n`; const slow = raw.includes(SLOW_MARKER); - const words = slow ? 2_000 : 40; + // An editing turn streams a longer first reply, then writes a file in the agent's directory. + const cwd = /Primary working directory: ([^\\"\n]+)/.exec(raw)?.[1]?.trim(); + const edit = entry.agent && raw.includes(EDIT_MARKER) && !toolResult && cwd !== undefined; + const words = slow ? 2_000 : edit ? 150 : 40; const deltas = Stream.range(0, words - 1).pipe( Stream.mapEffect((word) => - Effect.sleep(Duration.millis(slow ? 50 : 5)).pipe( + Effect.sleep(Duration.millis(slow ? 50 : edit ? 10 : 5)).pipe( Effect.as( event("content_block_delta", { index: 0, @@ -196,6 +230,43 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio ), ), ); + const toolCall = edit + ? Stream.make( + event("content_block_stop", { index: 0 }), + event("content_block_start", { + index: 1, + content_block: { + type: "tool_use", + id: `toolu_bench_${requests.length}`, + name: "Write", + input: {}, + }, + }), + event("content_block_delta", { + index: 1, + delta: { + type: "input_json_delta", + partial_json: encodeJson({ + file_path: `${cwd}/bench/${entry.marker ?? `turn-${requests.length}`}.md`, + content: Array.from({ length: 40 }, (_, line) => `line ${line} of ${id}`).join( + "\n", + ), + }), + }, + }), + event("content_block_stop", { index: 1 }), + event("message_delta", { + delta: { stop_reason: "tool_use", stop_sequence: null }, + usage: { output_tokens: words }, + }), + ) + : Stream.make( + event("content_block_stop", { index: 0 }), + event("message_delta", { + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { output_tokens: words }, + }), + ); const events = Stream.make( event("message_start", { message: { @@ -212,15 +283,7 @@ const serveFakeAnthropic = Effect.fn("serverMetrics.serveFakeAnthropic")(functio event("content_block_start", { index: 0, content_block: { type: "text", text: "" } }), ).pipe( Stream.concat(deltas), - Stream.concat( - Stream.make( - event("content_block_stop", { index: 0 }), - event("message_delta", { - delta: { stop_reason: "end_turn", stop_sequence: null }, - usage: { output_tokens: words }, - }), - ), - ), + Stream.concat(toolCall), // Stamped as the last event is produced, so it is set before any client can see the end. Stream.concat( Stream.fromEffect( @@ -1128,6 +1191,11 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( server: Server, token: string, threadIds: ReadonlyArray, + /** Sees every item a thread subscription delivers, the snapshot included. */ + onThreadItem: ( + threadId: string, + item: OrchestrationV2ThreadStreamItem, + ) => Effect.Effect = () => Effect.void, ) { const http = yield* HttpClient.HttpClient; // Headers alone do not finish a request; the deadline covers the body too. @@ -1162,6 +1230,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( const ready = Effect.fn("serverMetrics.subscription")(function* ( stream: Stream.Stream, isReady: (item: A) => boolean, + onItem: (item: A) => Effect.Effect = () => Effect.void, ) { const synchronized = yield* Deferred.make(); const lose = (message: string) => @@ -1170,7 +1239,9 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( ); yield* stream.pipe( Stream.runForEach((item) => - isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void, + onItem(item).pipe( + Effect.andThen(isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void), + ), ), Effect.andThen(lose("a subscription ended")), Effect.catchCause(() => lose("a subscription failed")), @@ -1244,6 +1315,7 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( acceptDedupedBodies: true, }), synchronized, + (item) => onThreadItem(threadId, item), ), )), ]; @@ -1254,6 +1326,19 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }), ); return { + /** Sends a message the way the composer does, starting a turn at once. */ + send: (threadId: string, messageId: string, text: string) => + client["orchestration.dispatchCommand"]({ + type: "message.dispatch", + commandId: CommandId.make(messageId), + threadId: ThreadId.make(threadId), + messageId: MessageId.make(messageId), + text, + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { type: "start_immediately" }, + }), /** 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 })), @@ -1308,6 +1393,126 @@ const pipelineTurns = Effect.fn("serverMetrics.pipelineTurns")(function* ( }; }); +const TERMINAL_RUN = new Set(["completed", "failed", "interrupted", "cancelled", "rolled_back"]); + +/** Threads that each answered once in a worktree of their own, by id. */ +const openWorktreeThreads = Effect.fn("serverMetrics.openWorktreeThreads")(function* ( + server: Server, + count: number, +) { + const answers = yield* Effect.forEach( + Array.from({ length: count }, (_, index) => index), + (index) => server.threadStart(`Say hello ${index}.`, ["--wait", "--worktree", "main"]), + { concurrency: 5 }, + ); + const ids = answers.map((answer) => /^Thread (\S+)$/m.exec(answer.stderr)?.[1]); + const failed = answers.find((answer, index) => answer.exitCode !== 0 || !ids[index]); + if (failed) { + return yield* new MetricsError({ + message: `a worktree thread failed to start: ${failed.stderr.trim() || failed.stdout.trim()}`, + }); + } + return ids.filter((id) => id !== undefined); +}); + +/** + * Every given thread runs editing turns back to back, all at once, sent and watched by one client + * subscribed to all of them, as the web client is. Each turn streams a reply, writes a file in the + * thread's worktree through the agent's Write tool, and ends in a checkpoint of that change. The + * window is measured while every thread is working; turns finished inside it are timed. + */ +const workingWindow = Effect.fn("serverMetrics.workingWindow")(function* ( + environment: Environment, + server: Server, + token: string, + threadIds: ReadonlyArray, + timing: { readonly warmupSeconds: number; readonly windowSeconds: number }, + /** The first turn's marker number; each window needs its own range, as ids never repeat. */ + firstMarker: number, +) { + // One pending turn per thread: its message id and when the run's end reached the client. + const pending = new Map }>(); + const client = yield* attachClient(server, token, threadIds, (threadId, item) => { + if (item.kind !== "event" || item.event.type !== "run.updated") return Effect.void; + const run = item.event.payload; + const turn = pending.get(threadId); + if (!turn || run.userMessageId !== turn.messageId || !TERMINAL_RUN.has(run.status)) { + return Effect.void; + } + return Deferred.succeed(turn.done, run.status).pipe(Effect.asVoid); + }); + const turns: Array<{ endedAt: number; toRequest: number; turnEnd: number; turnMs: number }> = []; + let stopping = false; + let sequence = 0; + const work = Effect.fn("serverMetrics.workingThread")(function* (threadId: string) { + while (!stopping) { + const marker = `bench-run-${firstMarker + sequence++}`; + const messageId = `bench-message-${marker}`; + const done = yield* Deferred.make(); + pending.set(threadId, { messageId, done }); + const sentAt = yield* nowMs; + yield* client.send(threadId, messageId, `Edit a file. ${EDIT_MARKER} ${marker}`); + const status = yield* Deferred.await(done).pipe( + Effect.timeoutOrElse({ + duration: Duration.seconds(120), + orElse: () => new MetricsError({ message: `turn ${marker} never ended` }), + }), + ); + const endedAt = yield* nowMs; + if (status !== "completed") { + return yield* new MetricsError({ message: `turn ${marker} ended ${status}` }); + } + const forTurn = environment.requests.filter( + (request) => request.agent && request.marker === marker && request.at >= sentAt, + ); + const first = forTurn.find((request) => !request.toolResult); + const last = forTurn.findLast((request) => request.toolResult); + if (first === undefined || last?.endedAt === undefined) { + return yield* new MetricsError({ + message: `turn ${marker} never called its Write tool; is the Claude CLI's tool set unchanged?`, + }); + } + turns.push({ + endedAt, + toRequest: first.at - sentAt, + turnEnd: endedAt - last.endedAt, + turnMs: endedAt - sentAt, + }); + } + }); + const workers = yield* Effect.forEach(threadIds, (threadId) => Effect.forkScoped(work(threadId))); + // A failed turn ends the window at once instead of thinning it. + const failed = Effect.forEach(workers, Fiber.join, { + concurrency: "unbounded", + discard: true, + }).pipe(Effect.andThen(Effect.never)); + return yield* Effect.raceFirst( + Effect.gen(function* () { + yield* Effect.sleep(Duration.seconds(timing.warmupSeconds)); + const from = yield* nowMs; + const window = yield* server.measure(timing.windowSeconds); + const to = yield* nowMs; + // Every thread finishes the turn it is on, so the next window starts from idle threads. + stopping = true; + yield* Effect.forEach(workers, Fiber.join, { discard: true }); + yield* client.healthy; + const inside = turns.filter((turn) => turn.endedAt >= from && turn.endedAt <= to); + if (inside.length === 0) { + return yield* new MetricsError({ message: "no turn finished inside the window" }); + } + const point: WorkingPoint = { + ...window, + turnsPerMin: round((inside.length / (to - from)) * 60_000), + toRequestMs: spread(inside.map((turn) => turn.toRequest)), + turnEndMs: spread(inside.map((turn) => turn.turnEnd)), + turnMs: spread(inside.map((turn) => turn.turnMs)), + }; + return point; + }), + failed, + ); +}, Effect.scoped); + const SCENARIOS = [ "startup", "rest", @@ -1316,6 +1521,7 @@ const SCENARIOS = [ "streaming", "clients", "pipeline", + "working", "busy", ] as const; /** Scenarios that read the developer's real database, so they run only when named. */ @@ -1494,6 +1700,35 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + if (wanted("working")) { + yield* withServer("working", (server) => + Effect.gen(function* () { + const token = yield* server.issueToken; + const counts = WORKING_THREADS; + const threads = yield* openWorktreeThreads(server, Math.max(...counts)); + const active: Record = {}; + for (const [index, count] of counts.entries()) { + active[`${count}`] = yield* workingWindow( + environment, + server, + token, + threads.slice(0, count), + { warmupSeconds: 10, windowSeconds: 30 }, + 30_000 + index * 10_000, + ); + } + const fit = (pick: (point: WorkingPoint) => number) => + round(slope(counts.map((count) => [count, pick(active[`${count}`]!)] as const)), 3); + measured.working = { + active, + heapMBPerThread: fit((point) => point.heapAfterGcMB), + rssMBPerThread: fit((point) => point.rssMB), + cpuPctPerThread: fit((point) => point.cpuPct), + loopDelayP99MsPerThread: fit((point) => point.loopDelayP99Ms ?? 0), + }; + }), + ); + } if (wanted("pipeline")) { yield* withServer("pipeline", (server) => Effect.gen(function* () { From 059d1bdeb9d7c0358e8a39dadd812d14a97e4580 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:24:05 -0800 Subject: [PATCH 67/74] docs: point provider setup at ACP Registry agents like GitHub Copilot (#41478) --- docs/user/install.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/user/install.md b/docs/user/install.md index 60d2d12f01c90..60ee758a0e656 100644 --- a/docs/user/install.md +++ b/docs/user/install.md @@ -195,18 +195,19 @@ and enable the provider you want. Installation, login, and configuration belong to that environment's machine, even when you connect from a phone or another computer. -| Provider | Install and authenticate | -| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Codex | [Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. | -| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. | -| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. | -| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. | -| Kiro | Install [Kiro CLI](https://kiro.dev/docs/cli/), then run `kiro-cli login`. | -| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. | -| Antigravity | Install and sign in with Google from T3 Code's provider settings. | -| Pi | Install [Pi](./providers-pi.md#set-up-pi) with Node.js 22.19 or newer, then run `pi` and `/login`. | -| Muse Code | Install [Muse Code](https://dev.meta.ai/docs/muse-code) on the server, run `muse login`, then enable it in Settings → Providers. | -| fx | Install [fx](https://fx.sh) with `curl -fsSL https://fx.sh/setup.sh \| bash`, then run `fx login`. | +| Provider | Install and authenticate | +| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Codex | [Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), or install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`. | +| Claude | Install [Claude Code](https://claude.com/product/claude-code), then run `claude auth login`. | +| Cursor | Install [Cursor CLI](https://cursor.com/cli), then run `agent login`. | +| Grok Build | Install [Grok Build CLI](https://x.ai/cli), then run `grok login`. | +| Kiro | Install [Kiro CLI](https://kiro.dev/docs/cli/), then run `kiro-cli login`. | +| OpenCode | Install [OpenCode](https://opencode.ai), then run `opencode auth login`. | +| Antigravity | Install and sign in with Google from T3 Code's provider settings. | +| Pi | Install [Pi](./providers-pi.md#set-up-pi) with Node.js 22.19 or newer, then run `pi` and `/login`. | +| Muse Code | Install [Muse Code](https://dev.meta.ai/docs/muse-code) on the server, run `muse login`, then enable it in Settings → Providers. | +| fx | Install [fx](https://fx.sh) with `curl -fsSL https://fx.sh/setup.sh \| bash`, then run `fx login`. | +| ACP Registry agents | Add GitHub Copilot and other [ACP agents](./providers-acp.md#add-an-agent) from **Settings → Providers → Add provider → Show more**. | Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set its **Binary path** in provider settings, especially when using a version manager. @@ -246,7 +247,8 @@ their original values. For provider-specific setup and accounts, see [Codex](./providers-codex.md), [Claude](./providers-claude.md), [OpenCode](./providers-opencode.md), [Antigravity](./providers-antigravity.md), [Kiro](./providers-kiro.md), -[Pi](./providers-pi.md), [Muse Code](./providers-muse.md), and [fx](./providers-fx.md). +[Pi](./providers-pi.md), [Muse Code](./providers-muse.md), [fx](./providers-fx.md), and +[ACP Registry agents](./providers-acp.md). ### Provider check timeouts From 8f724d6329ad37bfb1eb5ca1eccc1d26ca1fab77 Mon Sep 17 00:00:00 2001 From: Behzad Motaghi Date: Mon, 23 Nov 2026 15:24:18 +0100 Subject: [PATCH 68/74] fix: treat empty PATH entries as the working directory in launcher and CLI lookups (#41393) Co-authored-by: Julius Marminge --- apps/server/src/cli/invocation.test.ts | 35 ++++++++++ apps/server/src/cli/invocation.ts | 11 ++- apps/server/src/cli/triage.test.ts | 48 +++++++++++++ apps/server/src/cli/triage.ts | 12 +++- apps/server/src/cloud/pinnedRuntime.test.ts | 67 +++++++++++++++++++ apps/server/src/cloud/pinnedRuntime.ts | 19 +++--- .../src/cloud/serviceLauncherClient.test.ts | 67 +++++++++++++++++++ .../server/src/cloud/serviceLauncherClient.ts | 18 ++++- packages/shared/src/relayClient.test.ts | 39 +++++++++++ packages/shared/src/relayClient.ts | 14 +++- 10 files changed, 313 insertions(+), 17 deletions(-) diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts index 8310649aa77cb..928e97dc69246 100644 --- a/apps/server/src/cli/invocation.test.ts +++ b/apps/server/src/cli/invocation.test.ts @@ -8,6 +8,7 @@ import * as Path from "effect/Path"; import packageJson from "../../package.json" with { type: "json" }; import { posixLauncherScript } from "../cloud/pinnedRuntime.ts"; import { + hostShellWord, resolveHostCliCommand, resolveRootCliCommand, resolveServerInstallation, @@ -187,6 +188,40 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => { ); }), ); + + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "names the absolute path of a t3 found through a relative PATH entry", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bin = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(bin, "t3"), "#!/bin/sh\n", { mode: 0o755 }); + const hostCommand = (searchPath: string) => + resolveHostCliCommand("doctor").pipe( + Effect.provideService(HostProcess.ExecutablePath, "/usr/bin/node"), + Effect.provideService(HostProcess.Arguments, [ + "/usr/bin/node", + "/opt/t3/lib/node_modules/t3/dist/bin.mjs", + ]), + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + ); + + // A relative entry was searched from this process's directory, unlike the user's shell. + expect(yield* hostCommand(path.relative(process.cwd(), bin))).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + // An empty entry makes the shell search its own directory first, wherever that is. + expect(yield* hostCommand(`:${bin}`)).toEqual({ + command: `${hostShellWord("linux", path.join(bin, "t3"))} doctor`, + launcher: false, + }); + expect(yield* hostCommand(bin)).toEqual({ command: "t3 doctor", launcher: false }); + }), + ); }); it.layer(NodeServices.layer)("manual server installation ownership", (it) => { diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts index 4804d44f0e324..69a3a5815bbd6 100644 --- a/apps/server/src/cli/invocation.ts +++ b/apps/server/src/cli/invocation.ts @@ -205,7 +205,16 @@ export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand ) : null; if (own === null || own === (yield* real(onPath))) { - return { command: withArgs(command), launcher: false }; + const path = yield* Path.Path; + const searchPath = (yield* HostProcess.Environment).PATH ?? ""; + // With an empty or relative PATH entry, plain `t3` depends on the directory it runs from. + const cwdDependent = + platform !== "win32" && + searchPath.length > 0 && + searchPath.split(":").some((entry) => !path.isAbsolute(entry)); + if (!cwdDependent) return { command: withArgs(command), launcher: false }; + const quoted = hostShellWord(platform, path.resolve(onPath)); + return { command: withArgs(`${quoted} ${subcommand}`), launcher: false }; } } const launcher = yield* resolveInstallLauncher; diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts index 25f7baeb3211e..41f4241fade68 100644 --- a/apps/server/src/cli/triage.test.ts +++ b/apps/server/src/cli/triage.test.ts @@ -190,3 +190,51 @@ it.live("a failed agent launch points at the prompt it could not run", () => ), ), ); + +it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "starts an agent found through a relative PATH entry from the session directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" }); + // Relative to this process, as an entry like "." is to the server that checked it. + const relativeBinDir = NodePath.relative(process.cwd(), binDir); + // Nested deeper than the entry climbs, so from the session directory it leads nowhere. + const climbs = relativeBinDir.split(NodePath.sep).filter((part) => part === "..").length; + const baseDir = NodePath.join( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" }), + ...Array.from({ length: climbs }, () => "nested"), + ); + NodeFS.mkdirSync(baseDir, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 }); + yield* Effect.acquireRelease( + Effect.sync(() => { + vi.stubEnv("PATH", relativeBinDir); + vi.stubEnv("CODEX_HOME", NodePath.join(baseDir, "codex-home")); + }), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const previousExitCode = process.exitCode; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + process.exitCode = previousExitCode; + }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "triage", + "--agent", + "codex", + "--base-dir", + baseDir, + ]); + + // The fake agent ran and exited 1, rather than failing to start. + assert.equal(process.exitCode, 1); + assert.include((yield* TestConsole.logLines).join("\n"), "Codex exited with code 1."); + }).pipe( + Effect.provide( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer), + ), + ), +); diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index cb0f94b254589..df73347cd9fe4 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -4,7 +4,8 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeReadlinePromises from "node:readline/promises"; -import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isCommandAvailable, resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Config from "effect/Config"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; @@ -220,7 +221,14 @@ export const triageCommand = Command.make("triage", { const model = Option.getOrUndefined(flags.model); const launchPrompt = buildTriageLaunchPrompt(promptFilePath); - const spawnSpec = yield* resolveSpawnCommand(selected.command, [ + // The agent starts in the session directory, so a PATH match relative to this one would + // be searched from there. Windows keeps the bare name for its .cmd shim handling. + const onPath = + (yield* HostProcess.Platform) === "win32" + ? null + : yield* resolveCommandPath(selected.command); + const command = onPath === null ? selected.command : NodePath.resolve(onPath); + const spawnSpec = yield* resolveSpawnCommand(command, [ ...(model === undefined ? [] : ["--model", model]), ...(selected.promptArgs ?? []), launchPrompt, diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 28a7d720c525f..d5f15cd1b4591 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -18,6 +18,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; import { + findPosixLauncher, isVersionExecutable, ensurePinnedRuntimeInstalled, isUnpublishedRelease, @@ -25,7 +26,9 @@ import { pinnedRuntimePaths, PinnedRuntimeInstallError, type PinnedRuntimeProgress, + posixLauncherScript, prunePinnedRuntimes, + resolveLauncherPath, } from "./pinnedRuntime.ts"; import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts"; @@ -987,3 +990,67 @@ it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => { }), ); }); + +// NTFS reports no exec bits, and these lookups pass over files without them. +const posixHost = HostProcess.Platform.defaultValue() !== "win32"; + +it.layer(NodeServices.layer)("launcher lookup on PATH", (it) => { + it.effect.skipIf(!posixHost)( + "resolves an empty entry of a nonempty PATH against the working directory", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const launcher = path.join(root, "t3"); + yield* fs.writeFileString(launcher, "", { mode: 0o755 }); + const missing = path.join(root, "missing"); + const lookup = (platform: NodeJS.Platform, searchPath: string) => + resolveLauncherPath.pipe( + Effect.provideService(HostProcess.InvokedAs, "t3"), + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService(HostProcess.Environment, { PATH: searchPath }), + Effect.provideService(HostProcess.WorkingDirectory, root), + ); + + assert.equal(yield* lookup("linux", `:${missing}`), launcher); + assert.equal(yield* lookup("linux", `${missing}:`), launcher); + assert.equal(yield* lookup("linux", `${missing}::${missing}`), launcher); + // An empty PATH searches nothing, and Windows has no such rule. + assert.isUndefined(yield* lookup("linux", "")); + assert.isUndefined(yield* lookup("win32", `;${missing}`)); + }), + ); + + it.effect.skipIf(!posixHost)("finds a launcher script through an empty PATH entry", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-path-" }); + const versionsDir = path.join(root, ".t3", "runtime", "versions"); + const executable = path.join(versionsDir, "1.0.0", "t3"); + yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); + yield* fs.writeFileString(executable, "", { mode: 0o755 }); + const bin = path.join(root, "bin"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString(path.join(bin, "t3"), posixLauncherScript(executable), { + mode: 0o755, + }); + const script = yield* fs.realPath(path.join(bin, "t3")); + const missing = path.join(root, "missing"); + const lookup = (searchPath: string) => + findPosixLauncher({ launchedAs: executable, versionsDir }).pipe( + Effect.provideService(HostProcess.Environment, { + PATH: searchPath, + T3CODE_INSTALL_BIN_DIR: missing, + }), + Effect.provideService(HostProcess.WorkingDirectory, bin), + ); + + assert.equal(yield* lookup(`:${missing}`), script); + assert.equal(yield* lookup(`${missing}:`), script); + // An empty PATH searches nothing, not even the working directory. + assert.isUndefined(yield* lookup("")); + }), + ); +}); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 13c8f251c93b6..e544852ef3dcc 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -537,9 +537,11 @@ export const resolveLauncherPath = Effect.gen(function* () { return path.resolve(cwd, invokedAs); } const delimiter = platform === "win32" ? ";" : ":"; - for (const directory of (environment["PATH"] ?? "").split(delimiter)) { - if (directory.length === 0) continue; - const candidate = path.resolve(cwd, directory, invokedAs); + const searchPath = environment["PATH"] ?? ""; + for (const directory of searchPath.split(delimiter)) { + // POSIX shells search the working directory for an empty entry of a nonempty PATH. + if (directory.length === 0 && (platform === "win32" || searchPath.length === 0)) continue; + const candidate = path.resolve(cwd, directory || ".", invokedAs); const info = yield* fs.stat(candidate).pipe(Effect.option); // Like the shell, pass over directories and non-executable files named the same. if ( @@ -645,12 +647,13 @@ export const findPosixLauncher = Effect.fn("cloud.pinned_runtime.find_posix_laun .readFileString(path.join(path.dirname(input.versionsDir), "launchers")) .pipe(Effect.orElseSucceed(() => "")); const cwd = yield* HostProcess.WorkingDirectory; + const searchPath = environment["PATH"] ?? ""; const candidates = [ - // PATH first, resolved like the shell does: it decides which t3 the user runs. - ...(environment["PATH"] ?? "") - .split(":") - .filter((directory) => directory.length > 0) - .map((directory) => path.resolve(cwd, directory, "t3")), + // PATH first, resolved like the shell does: it decides which t3 the user runs. An empty + // entry of a nonempty PATH is the working directory; an empty PATH searches nothing. + ...(searchPath.length === 0 ? [] : searchPath.split(":")).map((directory) => + path.resolve(cwd, directory || ".", "t3"), + ), path.join( environment["T3CODE_INSTALL_BIN_DIR"] || path.join(yield* HostProcess.HomeDirectory, ".local", "bin"), diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 338ff32a3c16e..85661360020f6 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -325,4 +325,71 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { assert.equal(yield* fs.readLink(onPath), foreign); }).pipe(Effect.provideService(HostProcess.Platform, "linux")), ); + + it.effect.each([ + { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true }, + { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true }, + { name: "whole", searchPath: () => "", moved: false }, + ])("treats a $name empty PATH entry like the shell does", ({ searchPath, moved }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const inCwd = path.join(cwd, "t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + yield* fs.makeDirectory(cwd); + yield* fs.symlink(exe("1.0.0"), inCwd); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: searchPath(path.join(root, "missing")), + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + // A nonempty PATH searches the working directory there; an empty PATH searches nothing. + if (moved) { + assert.equal(yield* fs.readFileString(inCwd), posixLauncherScript(exe("2.0.0"))); + } else { + assert.equal(yield* fs.readLink(inCwd), exe("1.0.0")); + } + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); + + it.effect("passes over a working-directory t3 the shell cannot run", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const cwd = path.join(root, "work"); + const onPath = path.join(root, "bin/t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "", { mode: 0o755 }); + } + // A directory named t3 in the working directory, which the shell skips. + yield* fs.makeDirectory(path.join(cwd, "t3"), { recursive: true }); + yield* fs.makeDirectory(path.dirname(onPath), { recursive: true }); + yield* fs.symlink(exe("1.0.0"), onPath); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: `:${path.dirname(onPath)}`, + }), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + + assert.equal(yield* fs.readFileString(onPath), posixLauncherScript(exe("2.0.0"))); + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); }); diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index e8f8941f3f9e8..3e7f4abfc2d57 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -163,9 +163,21 @@ export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined); const candidates = new Set(); if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3")); - for (const directory of (environment["PATH"] ?? "").split(":")) { - if (directory.length === 0) continue; - const candidate = path.join(directory, "t3"); + const searchPath = environment["PATH"] ?? ""; + const cwd = yield* HostProcess.WorkingDirectory; + for (const directory of searchPath.split(":")) { + // Like the shell, an empty entry of a nonempty PATH is the working directory. + if (directory.length === 0 && searchPath.length === 0) continue; + const candidate = path.join(directory || cwd, "t3"); + if (directory.length === 0) { + // The shell passes over a working-directory entry it cannot run and keeps searching. + const info = yield* fs.stat(candidate).pipe(Effect.option); + if (Option.isNone(info) || info.value.type !== "File" || (info.value.mode & 0o111) === 0) { + continue; + } + candidates.add(candidate); + break; + } if ( yield* fs.exists(candidate).pipe( Effect.catch((cause) => diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.ts index 594d5ad215b1a..f317cc22b3565 100644 --- a/packages/shared/src/relayClient.test.ts +++ b/packages/shared/src/relayClient.test.ts @@ -717,6 +717,45 @@ describe("RelayClient", () => { ); }); + it.effect.skipIf(windowsHost)( + "finds a PATH binary through an empty entry by its absolute path", + () => + run((baseDir) => + Effect.gen(function* () { + const cwd = `${baseDir}/work`; + const inCwd = `${cwd}/cloudflared`; + yield* writeExecutable(inCwd); + const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }); + const resolveWith = (searchPath: string) => { + const env = { PATH: searchPath }; + return manager.resolve.pipe( + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ env }), + ), + Effect.provideService(HostProcess.Environment, env), + Effect.provideService(HostProcess.WorkingDirectory, cwd), + ); + }; + const found = { + status: "available", + executablePath: inCwd, + source: "path", + version: RelayClient.CLOUDFLARED_VERSION, + }; + + expect(yield* resolveWith(`:${baseDir}/missing`)).toEqual(found); + expect(yield* resolveWith(`${baseDir}/missing:`)).toEqual(found); + const missing = { status: "missing", version: RelayClient.CLOUDFLARED_VERSION }; + // An empty PATH searches nothing, not even the working directory. + expect(yield* resolveWith("")).toEqual(missing); + // A whitespace entry is not an empty one. + expect(yield* resolveWith(` :${baseDir}/missing`)).toEqual(missing); + expect(yield* resolveWith(`${baseDir}/missing: `)).toEqual(missing); + }), + ), + ); + it.effect.skipIf(windowsHost)("reports an outdated override as missing", () => { const versions: Record = {}; return run( diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index 19e42955ea554..81838ea4f65a0 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -374,13 +374,21 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function const resolvePathExecutable = Effect.gen(function* () { // Read hydrated PATH directly; ConfigProvider may have cached it before fixPath. - const pathValue = (yield* HostProcess.Environment).PATH?.trim(); + const rawPathValue = (yield* HostProcess.Environment).PATH; + // POSIX keeps the raw value, so trimming never turns " :/bin" into an empty entry. + const pathValue = platform === "win32" ? rawPathValue?.trim() : rawPathValue; if (!pathValue) return null; const delimiter = platform === "win32" ? ";" : ":"; + const cwd = yield* HostProcess.WorkingDirectory; for (const directory of pathValue.split(delimiter)) { + // POSIX shells search the working directory for an empty entry. Resolve it now: the + // connector may be launched from elsewhere. + const workingDirectoryEntry = directory === "" && platform !== "win32"; const trimmed = directory.trim().replace(/^"|"$/gu, ""); - if (trimmed.length === 0) continue; - const candidate = path.join(trimmed, executableFileName(platform)); + if (trimmed.length === 0 && !workingDirectoryEntry) continue; + const candidate = workingDirectoryEntry + ? path.resolve(cwd, executableFileName(platform)) + : path.join(trimmed, executableFileName(platform)); if (!(yield* isExecutableFile(candidate))) continue; const available = yield* compatibleCandidate(candidate, "path"); if (available) return available; From 962bda2eb7580496c4d5a4459288ead92d9e829e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:24:28 -0800 Subject: [PATCH 69/74] test(web): open history documents without reloading the app in iframes (#41489) --- .../src/browserHistoryStore.browser.test.ts | 79 ++++++++----------- 1 file changed, 34 insertions(+), 45 deletions(-) diff --git a/apps/web/src/browserHistoryStore.browser.test.ts b/apps/web/src/browserHistoryStore.browser.test.ts index c0c22fc2558a4..92e16d76243e6 100644 --- a/apps/web/src/browserHistoryStore.browser.test.ts +++ b/apps/web/src/browserHistoryStore.browser.test.ts @@ -2,6 +2,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { resetBrowserHistoryForTests, useBrowserHistoryStore } from "./browserHistoryStore"; +import { randomUUID } from "./lib/utils"; const storageKey = "t3code:browser-history:v1"; const oldEntry = { url: "http://example.test/removed", lastVisitedAt: 1 }; @@ -117,8 +118,7 @@ it("refreshes the open history when another document adds a visit", async () => JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); - using documents = new DisposableStack(); - const otherStore = await openHistoryDocument(documents); + const otherStore = await openHistoryDocument(); await vi.waitFor(() => expect(otherStore.getState().byProjectKey).toEqual({ a: [page] })); otherStore.getState().recordVisit("a", page.url, page.lastVisitedAt); @@ -164,29 +164,15 @@ it("bounds saved thread mappings while keeping live registrations", async () => } }); -async function openHistoryDocument( - disposables: DisposableStack, - { withoutIndexedDB = false } = {}, -) { - const source = new URL(import.meta.url); - source.pathname = source.pathname.replace(/\.browser\.test\.ts$/, ".ts"); - source.search = ""; - const frame = document.createElement("iframe"); - disposables.defer(() => frame.remove()); - frame.srcdoc = `${withoutIndexedDB ? '' : ""} - `; - await new Promise((resolve) => { - frame.onload = () => resolve(); - document.body.append(frame); - }); - const store = ( - frame.contentWindow as (Window & { historyStore?: typeof useBrowserHistoryStore }) | null - )?.historyStore; - if (!store) throw new Error("The history document did not load."); - return store; +// A fresh module instance stands in for another tab: it gets its own store, IndexedDB connection +// and BroadcastChannel without an iframe reloading the app's whole module graph. +async function openHistoryDocument() { + const source = new URL("./browserHistoryStore.ts", import.meta.url); + source.searchParams.set("document", randomUUID()); + const module: typeof import("./browserHistoryStore") = await import( + /* @vite-ignore */ source.href + ); + return module.useBrowserHistoryStore; } function deleteHistoryDatabase() { @@ -210,14 +196,13 @@ it("moves the legacy snapshot into the shared database", async () => { JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const first = await openHistoryDocument(documents); + const first = await openHistoryDocument(); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); expect(localStorage.getItem(storageKey)).toBeNull(); first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), ); @@ -233,8 +218,7 @@ it("persists new visits from an open document after its history database is dele JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const first = await openHistoryDocument(documents); + const first = await openHistoryDocument(); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({ a: [page] })); first.getState().removeUrl("a", page.url); await vi.waitFor(() => expect(first.getState().byProjectKey).toEqual({})); @@ -243,7 +227,7 @@ it("persists new visits from an open document after its history database is dele first.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); await vi.waitFor(() => expect(first.getState().byProjectKey.b).toEqual([otherEntry])); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual({ b: [otherEntry] })); } finally { await resetHistoryFixture(); @@ -257,11 +241,7 @@ it("keeps overlapping visits from independent documents", async () => { JSON.stringify({ state: { byProjectKey: { a: [page] } }, version: 1 }), ); try { - using documents = new DisposableStack(); - const [first, second] = await Promise.all([ - openHistoryDocument(documents), - openHistoryDocument(documents), - ]); + const [first, second] = await Promise.all([openHistoryDocument(), openHistoryDocument()]); first.getState().recordVisit("a", oldEntry.url, oldEntry.lastVisitedAt); second.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); const expected = { a: [page, oldEntry], b: [otherEntry] }; @@ -272,7 +252,7 @@ it("keeps overlapping visits from independent documents", async () => { // A fresh document should read the committed visits even after the legacy seed is gone. localStorage.removeItem(storageKey); - const reopened = await openHistoryDocument(documents); + const reopened = await openHistoryDocument(); await vi.waitFor(() => expect(reopened.getState().byProjectKey).toEqual(expected)); } finally { await resetHistoryFixture(); @@ -282,16 +262,25 @@ it("keeps overlapping visits from independent documents", async () => { it("keeps visits saved while IndexedDB could not open", async () => { await resetHistoryFixture(); try { - using documents = new DisposableStack(); - const db = await openHistoryFixture(documents); + using fixture = new DisposableStack(); + const db = await openHistoryFixture(fixture); await writeHistoryFixture(db, { byProjectKey: { a: [page] }, projectKeyByThreadKey: {} }); - const offline = await openHistoryDocument(documents, { withoutIndexedDB: true }); - offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); - await vi.waitFor(() => - expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), - ); + vi.stubGlobal("indexedDB", { + open() { + throw new Error("blocked"); + }, + }); + try { + const offline = await openHistoryDocument(); + offline.getState().recordVisit("b", otherEntry.url, otherEntry.lastVisitedAt); + await vi.waitFor(() => + expect(storedHistory()).toHaveProperty("byProjectKey", { b: [otherEntry] }), + ); + } finally { + vi.unstubAllGlobals(); + } - const online = await openHistoryDocument(documents); + const online = await openHistoryDocument(); await vi.waitFor(() => expect(online.getState().byProjectKey).toEqual({ a: [page], b: [otherEntry] }), ); From f1e390665a119c59ca01492713fa161a5e07200b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:24:42 -0800 Subject: [PATCH 70/74] feat(scripts): server metrics reconnect a user's devices by default and keep the 20-client storm behind --stress (#41372) Co-authored-by: Claude Opus 5.5 --- docs/internals/16_performance-regressions.md | 2 + scripts/server-metrics-report.ts | 28 +++-- scripts/server-metrics.ts | 117 ++++++++++++------- 3 files changed, 98 insertions(+), 49 deletions(-) diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index 135fb95ea6905..befd6fa1c2dbb 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -40,6 +40,8 @@ heap, and first-request latency against a fake Anthropic API and the real `claud - 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. +- Upper bounds no user hits daily, such as 20 clients reconnecting at once, run only with + `--stress`; the default reconnect is a user's 3 devices holding 10 threads each. - Test macOS, Windows, and Linux with `--no-agent-scope`: Linux systemd agent scopes mask per-process polling paths that other platforms run. diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 70a6e52ec73c4..c0edb68319994 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -61,6 +61,15 @@ const WorkingPoint = Schema.Struct({ }); export type WorkingPoint = typeof WorkingPoint.Type; +const Reconnect = Schema.Struct({ + clients: Schema.Number, + threadsPerClient: Schema.optional(Schema.Number), + /** Drop to every subscription delivering its snapshot again. */ + resubscribedMs: Schema.Number, + loopDelayP99Ms: Schema.Number, + loopDelayMaxMs: Schema.Number, +}); + /** One pass over the scenarios. */ export const Measured = Schema.Struct({ /** What else the machine was doing during the pass; never compared, only warned about. */ @@ -77,13 +86,10 @@ export const Measured = Schema.Struct({ Schema.Struct({ /** The quiet window by subscribed thread count. */ attached: Schema.Record(Schema.String, Window), - /** Every client drops and reconnects at once. */ - storm: Schema.Struct({ - clients: Schema.Number, - resubscribedMs: Schema.Number, - loopDelayP99Ms: Schema.Number, - loopDelayMaxMs: Schema.Number, - }), + /** A user's few devices, each holding the shell, VCS status and threads, drop and reconnect. */ + reconnect: Schema.optional(Reconnect), + /** With --stress: 20 clients holding one thread each drop and reconnect at once. */ + storm: Schema.optional(Reconnect), }), ), /** @@ -265,7 +271,9 @@ export const NOISE_RULES: ReadonlyArray = [ informational(/^(rest|quiet|streaming|clients\.attached\.\d+)\.loopDelay(P99|Max)Ms$/), informational(/^(rest|quiet|clients\.attached\.\d+)\.gc(Count|PauseMs)$/), informational(/^(streaming|pipeline)\.gcPauseMs$/), - informational(/^(pipeline\.loopDelayMaxMs|clients\.storm\.loopDelayP99Ms|quiet\.cpuPct)$/), + informational( + /^(pipeline\.loopDelayMaxMs|clients\.(storm|reconnect)\.loopDelayP99Ms|quiet\.cpuPct)$/, + ), informational(/^scaling\.(cpuPct|wakeups)PerThread$/), informational(/^clients\.attached\.\d+\.(cpuPct|wakeupsPerSec)$/), informational(/^(firstWord\..*|pipeline\.turnEndMs)\.p90$/), @@ -294,7 +302,8 @@ export const NOISE_RULES: ReadonlyArray = [ { pattern: /^firstWord\./, floor: 600, gate: true }, { pattern: /^pipeline\.(toRequestMs|turnEndMs)\.median$/, floor: 300, gate: true }, { pattern: /^pipeline\.(toRequestMs\.p90|msPerTurn)$/, floor: 600, gate: true }, - { pattern: /^clients\.storm\.resubscribedMs$/, floor: 200, gate: true }, + // The reconnect had no A/A run yet and takes the storm's floors. + { pattern: /^clients\.(storm|reconnect)\.resubscribedMs$/, floor: 200, gate: true }, { pattern: /^rest\.cpuPct$/, floor: 1, gate: true }, { pattern: /cpuPct$/, floor: 3.5, gate: true }, { pattern: /^(rest|quiet)\.wakeupsPerSec$/, floor: 12, gate: true }, @@ -328,6 +337,7 @@ const isMetric = (metric: string) => metric === "busy.projects" || metric === "busy.ballastMB" || metric.endsWith(".clients") || + metric.endsWith(".threadsPerClient") || metric.endsWith(".threads") || metric === "busy.largeThread.messages" || metric.startsWith("scaling.points") diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 54fc28693b3fd..cf8b85fa4e146 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -95,7 +95,10 @@ const EDIT_MARKER = "[[edit-files]]"; const PIPELINE_TURNS = 50; /** Threads working at once in each window of the working scenario. */ const WORKING_THREADS = [5, 10, 20]; -/** Clients that drop and reconnect at once in the clients scenario. */ +/** A user's devices: clients that drop and reconnect at once, each holding this many threads. */ +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; /** Event-loop delay sampling interval; each sample wakes the loop once. */ const LOOP_RESOLUTION_MS = 10; @@ -1346,6 +1349,48 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }; }); +/** + * Attaches one client per entry, each holding the shell, VCS status and its threads, lets them + * settle, then drops all of them at once and reconnects them: the time until every subscription + * delivered its snapshot again, and the loop delay across it. + */ +const reconnectAll = Effect.fn("serverMetrics.reconnectAll")(function* ( + server: Server, + token: string, + clientThreads: ReadonlyArray>, +) { + // Each client gets its own scope so they can be dropped on cue; the server's scope still closes + // any left open when a step fails or is interrupted. + const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => + Scope.close(scope, exit), + ); + const attachAll = (scopes: ReadonlyArray) => + Effect.forEach( + scopes, + (scope, index) => + attachClient(server, token, clientThreads[index] ?? []).pipe(Scope.provide(scope)), + { concurrency: "unbounded" }, + ); + const clients = yield* Effect.forEach(clientThreads, () => clientScope); + const first = yield* attachAll(clients); + yield* Effect.sleep(Duration.seconds(10)); + yield* Effect.forEach(first, (client) => client.healthy, { discard: true }); + yield* server.loopStart; + const dropped = yield* nowMs; + yield* Effect.forEach(clients, (scope) => Scope.close(scope, Exit.void), { + concurrency: "unbounded", + discard: true, + }); + const reopened = yield* Effect.forEach(clientThreads, () => clientScope); + const second = yield* attachAll(reopened); + const resubscribedMs = Math.round((yield* nowMs) - dropped); + const loop = yield* server.loopRead; + // The first cohort again: a loss between its check and the drop happened in the reconnect. + yield* Effect.forEach([...first, ...second], (client) => client.healthy, { discard: true }); + yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { discard: true }); + return { resubscribedMs, loopDelayP99Ms: round(loop.p99), loopDelayMaxMs: round(loop.max) }; +}); + /** * Short turns back to back on one thread: how long a send takes to reach the API, how long the * end of the reply takes to become a finished run the CLI sees (turn end and checkpoint), the time @@ -1537,6 +1582,8 @@ interface RunOptions { /** A seeded base dir for the busy scenario. */ readonly seed: string | undefined; readonly ballastMB: number; + /** Also runs the upper-bound stress cases, such as the 20-client reconnect storm. */ + readonly stress: boolean; /** Where full CPU and allocation profiles go; none are written without it. */ readonly profileDir: string | undefined; } @@ -1640,7 +1687,11 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* withServer("clients", (server) => Effect.gen(function* () { const token = yield* server.issueToken; - const most = Math.max(STORM_CLIENTS, ...options.threads); + const most = Math.max( + RECONNECT_THREADS, + options.stress ? STORM_CLIENTS : 0, + ...options.threads, + ); const threads = yield* openThreads(server, 0, most); const attached: Record = {}; for (const count of options.threads) { @@ -1653,49 +1704,27 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } - // Each client gets its own scope so the storm can drop them on cue; the server's scope - // still closes any left open when a step fails or is interrupted. - const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => - Scope.close(scope, exit), + const reconnect = yield* reconnectAll( + server, + token, + Array.from({ length: RECONNECT_CLIENTS }, () => threads.slice(0, RECONNECT_THREADS)), ); // Every client holds the shell, VCS status and one thread, then all drop and come back. - const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => clientScope); - const first = yield* Effect.forEach( - clients, - (scope, index) => - attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), - { concurrency: "unbounded" }, - ); - yield* Effect.sleep(Duration.seconds(10)); - yield* Effect.forEach(first, (client) => client.healthy, { discard: true }); - yield* server.loopStart; - const dropped = yield* nowMs; - yield* Effect.forEach(clients, (scope) => Scope.close(scope, Exit.void), { - concurrency: "unbounded", - discard: true, - }); - const reopened = yield* Effect.forEach(clients, () => clientScope); - const second = yield* Effect.forEach( - reopened, - (scope, index) => - attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), - { concurrency: "unbounded" }, - ); - const resubscribedMs = Math.round((yield* nowMs) - dropped); - const loop = yield* server.loopRead; - // The first cohort again: a loss between its check and the drop happened in the storm. - yield* Effect.forEach([...first, ...second], (client) => client.healthy, { discard: true }); - yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { - discard: true, - }); + const storm = options.stress + ? yield* reconnectAll( + server, + token, + threads.slice(0, STORM_CLIENTS).map((thread) => [thread]), + ) + : undefined; measured.clients = { attached, - storm: { - clients: STORM_CLIENTS, - resubscribedMs, - loopDelayP99Ms: round(loop.p99), - loopDelayMaxMs: round(loop.max), + reconnect: { + clients: RECONNECT_CLIENTS, + threadsPerClient: RECONNECT_THREADS, + ...reconnect, }, + ...(storm ? { storm: { clients: STORM_CLIENTS, ...storm } } : {}), }; }), ); @@ -2112,6 +2141,12 @@ const runFlags = { ), Flag.withDefault(768), ), + stress: Flag.Boolean("stress").pipe( + Flag.withDefault(false), + Flag.withDescription( + "Also run upper bounds no user hits daily: clients drops 20 clients at once and reconnects them. Compare stress numbers only with stress numbers.", + ), + ), soak: Flag.Int("soak").pipe( Flag.withSchema(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), Flag.withDescription( @@ -2130,6 +2165,7 @@ interface RunFlags { readonly busyProjects: number; readonly busyThreads: number; readonly busyBallast: number; + readonly stress: boolean; } const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( @@ -2156,6 +2192,7 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( profileDir, seed: undefined, ballastMB: flags.busyBallast, + stress: flags.stress, }; return options; }); From 4280147f58227ec88a5113edf46731ba9ff85adc Mon Sep 17 00:00:00 2001 From: nettee Date: Mon, 23 Nov 2026 22:26:18 +0800 Subject: [PATCH 71/74] fix(cli): clarify provider-specific model option examples (#41484) --- apps/server/src/cli/thread.ts | 2 +- docs/user/outside-agents.md | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 7ae729b391edb..fc3476739d1b0 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -934,7 +934,7 @@ const threadStartCommand = Command.make("start", { ), option: Flag.String("option").pipe( Flag.withDescription( - "Model option as id=value, such as effort=high. Repeat for more. Needs --provider and --model.", + "Model option as id=value (Codex: reasoningEffort=high; Claude: effort=high). Ids depend on the model. Repeat for more. Needs --provider and --model.", ), Flag.atLeast(0), ), diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 30c8aba13ffb1..c322becf88531 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -173,9 +173,10 @@ started in the app are. `send` never interrupts: a busy thread gets the message as its next turn. Pass `-` as the message to read it from stdin. To choose the model, pass `--provider --model `. Add -`--option id=value` for each model option, such as `--option effort=high`. -Option ids and values depend on the model; `true` and `false` set on/off -options. +`--option id=value` for each model option. For reasoning effort, Codex uses +`--option reasoningEffort=high`, while Claude uses `--option effort=high`. +Option ids and allowed values depend on the provider and model; use those +reported by `orchestrator_capabilities`. `true` and `false` set on/off options. `--wait` prints the agent's reply. It exits 1 when the run fails or stops, and 2 when the agent waits for an answer you give in the app. Add `--json` for a From 36413ad9f668356db9eeb825711d58ece6c2aeb5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:26:34 -0800 Subject: [PATCH 72/74] feat(scripts): server metrics get a --quick profile, one-line failures and a guide to the scenarios (#41373) Co-authored-by: Claude Opus 5.5 --- docs/internals/16_performance-regressions.md | 2 + scripts/server-metrics-report.ts | 27 ++++ scripts/server-metrics.test.ts | 37 +++++ scripts/server-metrics.ts | 151 +++++++++++++++---- 4 files changed, 186 insertions(+), 31 deletions(-) diff --git a/docs/internals/16_performance-regressions.md b/docs/internals/16_performance-regressions.md index befd6fa1c2dbb..863ccc0c7b697 100644 --- a/docs/internals/16_performance-regressions.md +++ b/docs/internals/16_performance-regressions.md @@ -42,6 +42,8 @@ heap, and first-request latency against a fake Anthropic API and the real `claud server, not the agents, is the bottleneck. - Upper bounds no user hits daily, such as 20 clients reconnecting at once, run only with `--stress`; the default reconnect is a user's 3 devices holding 10 threads each. +- `--quick` shortens every window for a per-PR or nightly check; `compare` refuses to mix quick + and full runs. `server-metrics --help` says which scenario to trust for what. - Test macOS, Windows, and Linux with `--no-agent-scope`: Linux systemd agent scopes mask per-process polling paths that other platforms run. diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index c0edb68319994..296320bbc1e2a 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -325,6 +325,33 @@ export function noiseRule(metric: string, rules: ReadonlyArray = NOIS return rules.find((rule) => rule.pattern.test(metric)) ?? { floor: 0, gate: true }; } +/** An error and the errors it wraps as one line, outermost first, repeats left out. */ +export function describeFailure(error: unknown): string { + const parts: string[] = []; + const seen = new Set(); + for (let at = error; at !== undefined && at !== null && !seen.has(at);) { + seen.add(at); + if (typeof at !== "object") { + parts.push(String(at)); + break; + } + const tag = "_tag" in at && typeof at._tag === "string" ? at._tag : undefined; + const message = "message" in at && typeof at.message === "string" ? at.message.trim() : ""; + const text = message || tag || String(at); + if (!parts.some((part) => part.includes(text))) parts.push(text); + at = "cause" in at ? at.cause : undefined; + } + return parts.join(": "); +} + +/** Why two files cannot be compared at all: a quick run measures shorter windows than a full one. */ +export function profileMismatch(before: ServerMetrics, after: ServerMetrics) { + const profile = (metrics: ServerMetrics) => metrics.meta.profile ?? "full"; + return profile(before) === profile(after) + ? undefined + : `before is a ${profile(before)} run and after a ${profile(after)} one; compare quick runs only with quick runs`; +} + /** Throughput, where a drop is the regression. */ export const higherIsBetter = (metric: string) => metric.endsWith("PerMin"); diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index adc86fddce588..d45e4d5c613a6 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -5,12 +5,14 @@ import { compareMetrics, competingBetween, activityRenewalMissed, + describeFailure, heapGrowth, loadWarnings, nextActivityReport, noiseReport, noisePairProblem, parsePsCpuTime, + profileMismatch, parseRunSelection, pathRewrites, pathSpellings, @@ -347,6 +349,41 @@ describe("compareMetrics on the busy shell snapshot", () => { }); }); +describe("describeFailure", () => { + it.each([ + ["a plain error", new Error("boom"), "boom"], + [ + "an RPC error wrapping the server's", + new Error("RpcClientError", { cause: new Error("Command x was already handled") }), + "RpcClientError: Command x was already handled", + ], + ["a tagged error with no message", { _tag: "TimeoutError" }, "TimeoutError"], + [ + "a cause that repeats its wrapper", + new Error("lost: gone", { cause: new Error("gone") }), + "lost: gone", + ], + ["a string", "exit 1", "exit 1"], + ])("%s", (_name, error, expected) => { + expect(describeFailure(error)).toBe(expected); + }); +}); + +describe("profileMismatch", () => { + const withProfile = (profile?: string): ServerMetrics => ({ + meta: profile === undefined ? meta : { ...meta, profile }, + runs: [], + }); + it.each([ + ["two full runs", withProfile("full"), withProfile("full"), false], + ["a file from before profiles, against a full run", withProfile(), withProfile("full"), false], + ["two quick runs", withProfile("quick"), withProfile("quick"), false], + ["a full run against a quick one", withProfile(), withProfile("quick"), true], + ])("%s", (_name, before, after, refused) => { + expect(profileMismatch(before, after) !== undefined).toBe(refused); + }); +}); + describe("heapGrowth", () => { it("lists only constructors that grew, small growth included", () => { const before = new Map([ diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index cf8b85fa4e146..ef2b091607ce7 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -13,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; import * as Clock from "effect/Clock"; +import * as Cause from "effect/Cause"; import * as Console from "effect/Console"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -59,6 +60,7 @@ import { run } from "./scenarios/shell.ts"; import { compareMetrics, CpuProfile, + describeFailure, HeapProfile, HeapSnapshot, heapByConstructor, @@ -67,6 +69,7 @@ import { loadWarnings, noiseReport, noisePairProblem, + profileMismatch, round, ServerMetrics, slope, @@ -91,10 +94,41 @@ const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; /** A prompt holding this streams a reply that ends in a Write tool call, then a short answer. */ const EDIT_MARKER = "[[edit-files]]"; -/** Sequential turns in the pipeline scenario. */ -const PIPELINE_TURNS = 50; -/** Threads working at once in each window of the working scenario. */ -const WORKING_THREADS = [5, 10, 20]; +/** + * How long each scenario measures. `quick` keeps every scenario but shortens its windows, for a + * per-PR or nightly check; its numbers compare only with other quick runs. + */ +const PROFILES = { + full: { + /** Idle time before a quiet window, so startup and thread setup work has drained. */ + settleSeconds: 15, + windowSeconds: 30, + streamingSeconds: 60, + profileSeconds: 20, + /** Sequential turns in the pipeline scenario. */ + pipelineTurns: 50, + /** Threads working at once in each window of the working scenario. */ + workingThreads: [5, 10, 20], + workingWarmupSeconds: 10, + /** Long enough that most threads finish a turn inside it even at 20 working. */ + workingSeconds: 30, + threads: "0,5,10,20", + runs: 5, + }, + quick: { + settleSeconds: 5, + windowSeconds: 10, + streamingSeconds: 20, + profileSeconds: 5, + pipelineTurns: 15, + workingThreads: [5, 20], + workingWarmupSeconds: 5, + workingSeconds: 20, + threads: "0,10", + runs: 3, + }, +} as const; +type Profile = (typeof PROFILES)[keyof typeof PROFILES]; /** A user's devices: clients that drop and reconnect at once, each holding this many threads. */ const RECONNECT_CLIENTS = 3; const RECONNECT_THREADS = 10; @@ -1584,6 +1618,7 @@ interface RunOptions { readonly ballastMB: number; /** Also runs the upper-bound stress cases, such as the 20-client reconnect storm. */ readonly stress: boolean; + readonly profile: Profile; /** Where full CPU and allocation profiles go; none are written without it. */ readonly profileDir: string | undefined; } @@ -1613,9 +1648,21 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption name: string, body: (server: Server) => Effect.Effect, serverOptions: ServerOptions = {}, - ) => Effect.scoped(Effect.flatMap(startServer(environment, name, serverOptions), body)); + ) => + Effect.scoped(Effect.flatMap(startServer(environment, name, serverOptions), body)).pipe( + // Names the scenario and its cause in one line, instead of a stack from deep in the RPC client. + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.fail( + new MetricsError({ + message: `the ${name} scenario failed: ${describeFailure(Cause.squash(cause))}`, + }), + ), + ), + ); const profile = Effect.fn("serverMetrics.saveProfile")(function* (server: Server, name: string) { - const { summary, raw } = yield* server.profile(20); + const { summary, raw } = yield* server.profile(options.profile.profileSeconds); profiles[name] = summary; if (options.profileDir === undefined) return; yield* fs.makeDirectory(options.profileDir, { recursive: true }); @@ -1634,8 +1681,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption Effect.gen(function* () { measured.startup = { readyMs: server.readyMs }; if (wanted("rest")) { - yield* Effect.sleep(Duration.seconds(15)); - measured.rest = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + measured.rest = yield* server.measure(options.profile.windowSeconds); } if (wanted("firstWord")) { measured.firstWord = { @@ -1654,8 +1701,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption for (const threads of options.threads) { if (threads > open) yield* openThreads(server, open, threads - open); open = Math.max(open, threads); - yield* Effect.sleep(Duration.seconds(15)); - points.push({ threads, window: yield* server.measure(30) }); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + points.push({ threads, window: yield* server.measure(options.profile.windowSeconds) }); } const last = points.at(-1); if (last) measured.quiet = last.window; @@ -1698,8 +1745,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* Effect.scoped( Effect.gen(function* () { const client = yield* attachClient(server, token, threads.slice(0, count)); - yield* Effect.sleep(Duration.seconds(10)); - attached[`${count}`] = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds)); + attached[`${count}`] = yield* server.measure(options.profile.windowSeconds); yield* client.healthy; }), ); @@ -1733,7 +1780,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* withServer("working", (server) => Effect.gen(function* () { const token = yield* server.issueToken; - const counts = WORKING_THREADS; + const counts = options.profile.workingThreads; const threads = yield* openWorktreeThreads(server, Math.max(...counts)); const active: Record = {}; for (const [index, count] of counts.entries()) { @@ -1742,7 +1789,10 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption server, token, threads.slice(0, count), - { warmupSeconds: 10, windowSeconds: 30 }, + { + warmupSeconds: options.profile.workingWarmupSeconds, + windowSeconds: options.profile.workingSeconds, + }, 30_000 + index * 10_000, ); } @@ -1761,7 +1811,11 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption if (wanted("pipeline")) { yield* withServer("pipeline", (server) => Effect.gen(function* () { - measured.pipeline = yield* pipelineTurns(environment, server, PIPELINE_TURNS); + measured.pipeline = yield* pipelineTurns( + environment, + server, + options.profile.pipelineTurns, + ); }), ); } @@ -1793,7 +1847,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption return yield* new MetricsError({ message: "fewer than 5 replies started streaming" }); } yield* Effect.sleep(Duration.seconds(5)); - measured.streaming = yield* server.measure(60); + measured.streaming = yield* server.measure(options.profile.streamingSeconds); yield* profile(server, "streaming"); }), ); @@ -1807,8 +1861,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption (server) => Effect.gen(function* () { yield* server.ballast(options.ballastMB); - yield* Effect.sleep(Duration.seconds(30)); - const rest = yield* server.measure(30); + yield* Effect.sleep(Duration.seconds(options.profile.settleSeconds * 2)); + const rest = yield* server.measure(options.profile.windowSeconds); yield* server.assertIdle(server.startedAt); const shell = yield* loadShell(server, 5); const largest = server.largest; @@ -1818,7 +1872,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption const git = yield* Effect.raceFirst( Effect.gen(function* () { yield* Effect.sleep(Duration.seconds(5)); - const window = yield* server.measure(30); + const window = yield* server.measure(options.profile.windowSeconds); yield* profile(server, "busyGit"); return window; }), @@ -1866,8 +1920,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption yield* takeSample; nextSample += 120_000; } - const threadId = - threads[yield* Random.nextIntBetween(0, threads.length, { halfOpen: true })]; + // 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}.`); @@ -2044,6 +2098,7 @@ const metaFor = Effect.fn("serverMetrics.metaFor")(function* (options: RunOption yield* output("git", ["rev-parse", "--short=12", "HEAD"], options.checkout), ), noAgentScope: options.noAgentScope, + profile: options.profile === PROFILES.quick ? "quick" : "full", agentScope: platform === "linux" && !options.noAgentScope && @@ -2070,6 +2125,8 @@ const report = Effect.fn("serverMetrics.report")(function* ( after: ServerMetrics, threshold: number, ) { + const mismatch = profileMismatch(before, after); + if (mismatch !== undefined) return yield* new MetricsError({ message: mismatch }); const { table, regressed, improved, informational, compared, warnings } = compareMetrics( before, after, @@ -2107,12 +2164,20 @@ const runFlags = { ), runs: Flag.Int("runs").pipe( Flag.withSchema(PositiveInt), - Flag.withDescription("firstWord runs in each variant."), - Flag.withDefault(5), + Flag.withDescription("firstWord runs in each variant. Default 5, 3 with --quick."), + Flag.optional, ), threads: Flag.String("threads").pipe( - Flag.withDescription("Open thread counts the quiet scenario measures."), - Flag.withDefault("0,5,10,20"), + Flag.withDescription( + "Open thread counts the quiet and clients scenarios measure. Default 0,5,10,20; 0,10 with --quick.", + ), + Flag.optional, + ), + quick: Flag.Boolean("quick").pipe( + Flag.withDefault(false), + Flag.withDescription( + "Shorter windows, fewer turns and fewer points (about a third of the time), for a per-PR or nightly check. Compare quick runs only with quick runs.", + ), ), only: Flag.String("only").pipe( Flag.withDescription(`Scenarios to run, comma separated: ${SCENARIOS.join(", ")}.`), @@ -2157,8 +2222,9 @@ const runFlags = { }; interface RunFlags { readonly noAgentScope: boolean; - readonly runs: number; - readonly threads: string; + readonly runs: Option.Option; + readonly threads: Option.Option; + readonly quick: boolean; readonly only: Option.Option; readonly soak: number; readonly seedDir: Option.Option; @@ -2174,9 +2240,10 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( profileDir: string | undefined, ) { const path = yield* Path.Path; + const profile = flags.quick ? PROFILES.quick : PROFILES.full; const selection = parseRunSelection({ only: Option.getOrElse(flags.only, () => ""), - threads: flags.threads, + threads: Option.getOrElse(flags.threads, () => profile.threads), soak: flags.soak, scenarios: SCENARIOS, }); @@ -2185,7 +2252,7 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( const options: RunOptions = { checkout: path.resolve(checkout), noAgentScope: flags.noAgentScope, - runs: flags.runs, + runs: Option.getOrElse(flags.runs, () => profile.runs), threads, only, soakMinutes: flags.soak, @@ -2193,6 +2260,7 @@ const toRunOptions = Effect.fn("serverMetrics.toRunOptions")(function* ( seed: undefined, ballastMB: flags.busyBallast, stress: flags.stress, + profile, }; return options; }); @@ -2255,7 +2323,7 @@ const runCommand = Command.make( }, Effect.scoped), ).pipe( Command.withDescription( - "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", + "Measure a checkout's server: startup, rest and first word on one server, then quiet threads (with their cost per thread), clients, many threads working, the turn pipeline, streaming and an optional soak on servers of their own. Needs the real claude CLI on PATH; on Windows the native claude.exe from claude.ai/install.ps1, since an npm claude.cmd shim cannot be started without a shell.", ), ); @@ -2379,7 +2447,18 @@ const noiseCommand = Command.make( const serverMetricsCommand = Command.make("server-metrics").pipe( Command.withDescription( - "Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows.", + `Measure the server process against a fake Anthropic API and the real claude CLI, on Linux, macOS and Windows. + +Which scenario answers what: + working Many threads editing files at once, one client watching all: steer performance work by its loop delay, turn end and turns per minute. + pipeline One thread's overhead per turn: send to API request, reply end to run end. + clients What an attached client costs, and a user's 3 devices reconnecting. --stress adds the 20-client storm, an upper bound. + quiet Idle cost per open thread (the scaling fit); rest is an idle server. + streaming CPU and loop delay while 5 replies stream. + firstWord A new thread's time to the API; startup is time to the first answer. Latency on a shared machine is noisy. + busy Opt-in: a copy of your real database, read-only, for costs an empty one hides. + +Trust a change only from \`ab\` on one machine. compare gates on floors measured from A/A runs (\`noise\`), shows metrics too noisy to gate on without counting them, and warns when other processes loaded the machine; rerun then. --quick suits a per-PR or nightly check; decide on full runs.`, ), Command.withSubcommands([runCommand, abCommand, compareCommand, noiseCommand]), ); @@ -2393,6 +2472,16 @@ if (import.meta.main) { NodeSocket.layerWebSocketConstructor, ), ), + Effect.catchTags({ + MetricsError: (error) => + Console.error(`server-metrics: ${error.message}`).pipe( + Effect.andThen( + Effect.sync(() => { + process.exitCode = 1; + }), + ), + ), + }), NodeRuntime.runMain, ); } From 1bc44f2732ce0a24c0608626d59409f1a0893db4 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 23 Nov 2026 06:27:42 -0800 Subject: [PATCH 73/74] fix(server): analytics report every model name (#41237) Co-authored-by: Claude Opus 5.5 --- .../src/telemetry/ProviderDimensions.test.ts | 25 ++---- .../src/telemetry/ProviderDimensions.ts | 64 +++++---------- .../telemetry/ProviderUsageAnalytics.test.ts | 79 +++++-------------- .../src/telemetry/ProviderUsageAnalytics.ts | 8 +- docs/internals/08_product-analytics.md | 4 +- docs/user/telemetry.md | 8 +- 6 files changed, 57 insertions(+), 131 deletions(-) diff --git a/apps/server/src/telemetry/ProviderDimensions.test.ts b/apps/server/src/telemetry/ProviderDimensions.test.ts index 3959d7dc78e4b..e24bb480d1e24 100644 --- a/apps/server/src/telemetry/ProviderDimensions.test.ts +++ b/apps/server/src/telemetry/ProviderDimensions.test.ts @@ -7,20 +7,15 @@ const provider = ( instanceId: string, driver: string, models: ReadonlyArray<{ slug: string; isCustom: boolean }>, - auth: Record = {}, ) => ({ instanceId: ProviderInstanceId.make(instanceId), driver, - auth: { status: "authenticated", ...auth }, models, }) as unknown as ServerProvider; const providers = [ provider("work-codex", "codex", [{ slug: "gpt-5.5", isCustom: false }]), - provider("azure-codex", "codex", [{ slug: "gpt-acme-finetune", isCustom: false }], { - endpoint: "https://acme.example.com", - }), provider("claudeAgent", "claudeAgent", [ { slug: "claude-opus-5-5", isCustom: false }, { slug: "my-private-finetune", isCustom: true }, @@ -42,17 +37,13 @@ const thread = ( ...overrides, }); -it("omits custom, user-configured, endpoint-served, and unknown models and instance names", () => { +it("reports every model name but never instance names", () => { expect( agentToolProperties({ tool: "t3_thread_send", providers, caller: thread("claudeAgent", "my-private-finetune"), - targets: [ - thread("opencode", "ollama/acme-internal"), - thread("removed-instance", "gpt-5.5"), - thread("azure-codex", "gpt-acme-finetune"), - ], + targets: [thread("opencode", "ollama/acme-internal"), thread("removed-instance", "gpt-5.5")], outcome: { outcome: "ok" }, }).map(({ callerProvider, callerModel, targetProvider, targetModel }) => ({ callerProvider, @@ -63,22 +54,16 @@ it("omits custom, user-configured, endpoint-served, and unknown models and insta ).toEqual([ { callerProvider: "claudeAgent", - callerModel: undefined, + callerModel: "my-private-finetune", targetProvider: "opencode", - targetModel: undefined, + targetModel: "ollama/acme-internal", }, { callerProvider: "claudeAgent", - callerModel: undefined, + callerModel: "my-private-finetune", targetProvider: "unknown", targetModel: undefined, }, - { - callerProvider: "claudeAgent", - callerModel: undefined, - targetProvider: "codex", - targetModel: undefined, - }, ]); }); diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.ts index 497f1e660131b..7aa44cd46727b 100644 --- a/apps/server/src/telemetry/ProviderDimensions.ts +++ b/apps/server/src/telemetry/ProviderDimensions.ts @@ -13,8 +13,7 @@ export interface ProviderDimensions { /** * Anonymous provider and model for a model selection. Instance ids are - * user-defined, so only the driver kind is reported. The model is reported - * only when the selected instance's vendor catalog lists it. + * user-defined, so only the driver kind is reported. */ export function providerDimensions( providers: ReadonlyArray, @@ -22,15 +21,16 @@ export function providerDimensions( ): ProviderDimensions { const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); if (provider === undefined) return { provider: "unknown" }; - const model = vendorCatalogEntry(provider, [selection.model]); - return model === undefined - ? { provider: provider.driver } - : { provider: provider.driver, model: model.slug }; + return { provider: provider.driver, model: modelLabel(providers, selection.model) }; } const DATED_SNAPSHOT = /-\d{8}$/u; +// Absolute, home, relative, or Windows paths, such as a local GGUF file. Directories can name the user. +const FILE_PATH = /^(?:[/~]|\.{1,2}[/\\]|[A-Za-z]:[\\/])|\\/u; + +const fileName = (model: string) => + FILE_PATH.test(model) ? model.slice(model.search(/[^/\\]*$/u)) : model; -// The bundled manifest is reviewed in this repo. Vendor catalogs ship models before it does. const MANIFEST_LABELS: ReadonlyMap = new Map( Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) => catalog.models.flatMap((model) => @@ -39,43 +39,17 @@ const MANIFEST_LABELS: ReadonlyMap = new Map( ), ); -// Drivers whose model lists come from the vendor. OpenCode, Pi, and ACP agents list the -// user's own configuration, such as local Ollama tags. Codex and Claude also list -// early-access code names, so only slugs in the vendor's public family vouch for them. -const VENDOR_CATALOGS: ReadonlyMap = new Map([ - ["cursor", undefined], - ["grok", undefined], - ["antigravity", undefined], - ["codex", /^gpt-/u], - ["claudeAgent", /^claude-/u], -]); - -// A custom endpoint or gateway serves whatever names its owner chose. -const isVendorRouted = (auth: ServerProvider["auth"]) => - auth.endpoint === undefined && auth.type !== "customEndpoint" && auth.type !== "bedrock"; - -function vendorCatalogEntry(provider: ServerProvider, candidates: ReadonlyArray) { - if (!VENDOR_CATALOGS.has(provider.driver) || !isVendorRouted(provider.auth)) return undefined; - const family = VENDOR_CATALOGS.get(provider.driver); - return provider.models.find( - (entry) => - !entry.isCustom && - (family === undefined || family.test(entry.slug)) && - (candidates.includes(entry.slug) || - entry.aliases?.some((alias) => candidates.includes(alias)) === true), - ); -} - /** - * The vendor catalog slug that a native or routed model id names, such as - * `anthropic/claude-opus-5-5` or a dated snapshot. Models outside the bundled - * manifest and vendor-routed provider catalogs, including user-added ones and - * names a custom endpoint serves, return undefined. + * The model name analytics reports. A routed id, alias, or dated snapshot that the + * bundled manifest or a provider's model list knows, such as `anthropic/claude-opus-5-5` + * or `antigravity-default`, maps to its catalog slug. A file path reports only its file + * name. Any other id is reported as is. */ -export function catalogModelLabel( - providers: ReadonlyArray, - model: string, -): string | undefined { +export function modelLabel(providers: ReadonlyArray, model: string): string { + return fileName(catalogSlug(providers, model) ?? model); +} + +function catalogSlug(providers: ReadonlyArray, model: string) { const leaf = model.slice(model.lastIndexOf("/") + 1); const candidates = [model, leaf, leaf.replace(DATED_SNAPSHOT, "")]; for (const candidate of candidates) { @@ -83,7 +57,11 @@ export function catalogModelLabel( if (label !== undefined) return label; } for (const provider of providers) { - const match = vendorCatalogEntry(provider, candidates); + const match = provider.models.find( + (entry) => + candidates.includes(entry.slug) || + entry.aliases?.some((alias) => candidates.includes(alias)) === true, + ); if (match !== undefined) return match.slug; } return undefined; diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 0ce417e9a2c8b..14e4a8b68633b 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -15,7 +15,7 @@ import * as Layer from "effect/Layer"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; -import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { modelLabel } from "./ProviderDimensions.ts"; import { ProviderTurnAnalytics, RequestUsageLedger, @@ -26,29 +26,9 @@ import { } from "./ProviderUsageAnalytics.ts"; const providers = [ - // Vendor-routed Codex lists OpenAI's catalog, including early-access code names. - { - driver: "codex", - models: [{ slug: "gpt-6-sol" }, { slug: "gpt-6.2-sol" }, { slug: "nova-alpha" }], - }, - // A custom endpoint serves whatever its owner chose, including private deployments. - { - instanceId: "azure-codex", - driver: "codex", - auth: { endpoint: "https://acme.example.com" }, - models: [{ slug: "acme-azure-deployment" }, { slug: "gpt-acme-finetune" }], - }, - { - driver: "claudeAgent", - models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }, { slug: "claude-opus-6" }], - }, - { - instanceId: "claude-gateway", - driver: "claudeAgent", - auth: { type: "customEndpoint" }, - models: [{ slug: "claude-ops-internal" }], - }, - { driver: "opencode", models: [{ slug: "ollama/acme-internal" }] }, + { driver: "codex", models: [{ slug: "gpt-6-sol" }] }, + { driver: "pi", models: [{ slug: "/Users/jane/models/llama.gguf", aliases: ["pi-local"] }] }, + { driver: "claudeAgent", models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }] }, // Antigravity ships models before the bundled manifest lists them. { driver: "antigravity", @@ -58,25 +38,14 @@ const providers = [ ], }, ].map( - ({ - instanceId, - driver, - auth, - models, - }: { - instanceId?: string; - driver: string; - auth?: Record; - models: ReadonlyArray<{ slug: string; aliases?: ReadonlyArray }>; - }) => + ({ driver, models }) => ({ - instanceId: ProviderInstanceId.make(instanceId ?? driver), + instanceId: ProviderInstanceId.make(driver), driver, - auth: { status: "authenticated", ...auth }, models: models.map((model) => ({ ...model, isCustom: false })), }) as unknown as ServerProvider, ); -const label = (model: string) => catalogModelLabel(providers, model); +const label = (model: string) => modelLabel(providers, model); const at = (ms: number) => DateTime.makeUnsafe(ms); const complete = (input: number, output: number, extra: Partial = {}) => @@ -335,7 +304,7 @@ describe("provider usage reporting", () => { }); }); - it("reports routed catalog models and closed efforts only", () => { + it("reports every model name and closed efforts only", () => { const routed = (model: string, variant: string) => providerTurnProperties( { @@ -356,30 +325,22 @@ describe("provider usage reporting", () => { observedModel: "claude-opus-5-5", effort: "high", }); - for (const local of [ - routed("ollama/acme-internal", "secret-variant"), - routed("acme-azure-deployment", "high"), - ]) { - expect(local).not.toHaveProperty("model"); - expect(local).not.toHaveProperty("observedModel"); - } - expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort"); + const local = routed("ollama/acme-internal", "secret-variant"); + expect(local).toMatchObject({ + model: "ollama/acme-internal", + observedModel: "ollama/acme-internal", + }); + expect(local).not.toHaveProperty("effort"); }); - it("reports vendor catalog models the bundled manifest does not list", () => { + it("maps provider catalog aliases to their slug and file paths to their file name", () => { expect(label("gemini-4-hydrogen")).toBe("gemini-4-hydrogen"); expect(label("antigravity-default")).toBe("gemini-4-neon"); - expect(label("gemini-4-unlisted")).toBeUndefined(); - expect(label("gpt-6.2-sol")).toBe("gpt-6.2-sol"); - expect(label("claude-opus-6")).toBe("claude-opus-6"); - for (const hidden of [ - "nova-alpha", - "acme-azure-deployment", - "gpt-acme-finetune", - "claude-ops-internal", - ]) { - expect(label(hidden)).toBeUndefined(); - } + expect(label("/Users/jane/models/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("~/models/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("C:\\Users\\jane\\qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("../jane/qwen-coder.gguf")).toBe("qwen-coder.gguf"); + expect(label("pi-local")).toBe("llama.gguf"); }); it("reports closed service tiers from a tier option or a fast mode toggle", () => { diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts index ce7f29ba1f8d5..a281f40479b55 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -26,7 +26,7 @@ import { } from "@t3tools/shared/model"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; -import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { modelLabel } from "./ProviderDimensions.ts"; // Bump when a field changes meaning, so reports can split old and new rows. const REPORT_VERSION = 2; @@ -74,8 +74,8 @@ export interface RunSettledReport { } type Properties = Readonly>; -/** Maps a native model id to a vendor catalog label, or undefined to keep it out. */ -export type ModelLabeler = (model: string) => string | undefined; +/** Maps a native model id to the name analytics reports. */ +export type ModelLabeler = (model: string) => string; const TERMINAL_STATUSES: ReadonlySet = new Set([ "completed", @@ -403,7 +403,7 @@ export const layer = Layer.effect( registry.getProviders, (providers): ModelLabeler => (model) => - catalogModelLabel(providers, model), + modelLabel(providers, model), ); return { runStarted: Effect.fn("ProviderTurnAnalytics.runStarted")((input) => diff --git a/docs/internals/08_product-analytics.md b/docs/internals/08_product-analytics.md index 24cb8b04e39f9..375f6be84b857 100644 --- a/docs/internals/08_product-analytics.md +++ b/docs/internals/08_product-analytics.md @@ -28,7 +28,9 @@ an authenticated connection does not count as product use. - Payloads stay strictly to product metadata, closed contract enums, and normalized measurements: never attach prompts, file paths, credentials, raw provider payloads, device names, conversation - IDs, user-named provider instance IDs, or non-vendor/custom model names. + IDs, or user-named provider instance IDs. Model IDs are reported as the provider used them, + including custom models; known aliases and routed IDs map to one catalog slug, and a model + that is a file path reports only its file name. - The sole exception is opt-in `agent.feedback`, which [`FeedbackService`](../../apps/server/src/feedback/FeedbackService.ts) scrubs of paths, private values, and secret-shaped strings, and only attaches bounded conversation traces when the user diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 4c6b3f20eaad5..be7fdd938ff06 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -6,8 +6,8 @@ uses, the server also sends hashed account identifiers: your T3 Connect account, Claude accounts when you are signed in, and a random identifier for each device that connects. The endpoint keeps a copy of each event and forwards events to PostHog. Events include the provider, model, reasoning effort, permission mode, turn and request results, duration, release channel, and token counts when -available. Child-agent token counts are reported separately from the main agent's. Model names -are sent only when they appear in a provider's public model list. +available. Child-agent token counts are reported separately from the main agent's. Events include +the model ID the provider used, including custom models and models served by a custom endpoint. Product events do not include prompts, responses, file contents, authentication tokens, conversation IDs, raw provider events, or child-agent output. The one exception is [agent feedback](#agent-feedback), @@ -52,8 +52,8 @@ Before anything is saved, T3 Code removes file paths (when text mentions one, th goes with it), your user name, machine name, project title, branch, and git remote, and anything that looks like a key, token, email address, or URL with a password. It cannot recognise your code or a name written in a sentence, so only include the conversation when it holds nothing you would -not send. Reports from agents also name the provider, and the model when it is from the provider's -public model list. No thread IDs or project IDs are sent. +not send. Reports from agents also name the provider and the model. No thread IDs or project IDs +are sent. Reports are saved on your machine first, and a declined one is not saved at all; its card keeps only what you would have sent without the conversation. When product usage From 6be5502b258f9ee9454af66ecaf5c93c7ea4a08c Mon Sep 17 00:00:00 2001 From: T3 Code PR Stack <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:46:53 +0100 Subject: [PATCH 74/74] fix(web): pass the fork's remote-open test through upstream's saved routes Upstream #27236 replaced resolveRemoteOpenState's sshTarget input with the environment's saved routes. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/remoteOpenFork.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/remoteOpenFork.test.ts b/apps/web/src/remoteOpenFork.test.ts index 0bcf2e1eb3319..22201bf449b10 100644 --- a/apps/web/src/remoteOpenFork.test.ts +++ b/apps/web/src/remoteOpenFork.test.ts @@ -23,7 +23,7 @@ describe("paired environment open over its active route", () => { expect( resolveRemoteOpenState({ target, - sshTarget: null, + routes: [], isDesktopRenderer: true, remoteOpenTargets: [{ kind: "tailscale", host: "smart.tail1234.ts.net" }], hostEnvironmentId: "environment-desktop",