From 135c78a27882e84683242a48793c09fa1490a495 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 01:03:32 -0600 Subject: [PATCH 001/118] fix(cli): expand ~ paths in t3 thread --output-schema (#41271) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 16 ++++++++++++++++ apps/server/src/cli/thread.ts | 6 ++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index bb0906a9c6919..3e38b6885e9d9 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -27,6 +27,7 @@ import { latestRunError, launchModelSelection, readLatestMessages, + readOutputSchema, resolveProject, threadCommand, type ThreadTools, @@ -524,6 +525,21 @@ it.effect("start rejects a repeated --option before reaching the server", () => ), ); +it.effect("--output-schema reads a ~/ path from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-schema-" }); + yield* fs.writeFileString(path.join(home, "schema.json"), '{"type":"object"}'); + + const output = yield* readOutputSchema(Option.some("~/schema.json")).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + ); + + assert.deepStrictEqual(output, { outputSchema: { type: "object" } }); + }).pipe(Effect.provide(NodeServices.layer)), +); + /** Serves t3_thread_read pages the way the server does: positions count every item. */ const timelineTools = (types: ReadonlyArray) => { const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type })); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 1d81dcc6bd7cb..f57f1eed163f4 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -846,14 +846,16 @@ const outputSchemaFlag = Flag.String("output-schema").pipe( const decodeOutputSchema = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)), ); -const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* ( +export const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* ( path: Option.Option, ) { if (Option.isNone(path)) return {}; const fileSystem = yield* FileSystem.FileSystem; const usage = () => new ThreadUsageError({ detail: `${path.value} does not hold a JSON Schema object.` }); - const text = yield* fileSystem.readFileString(path.value).pipe(Effect.mapError(usage)); + const text = yield* fileSystem + .readFileString(yield* expandHomePath(path.value)) + .pipe(Effect.mapError(usage)); return { outputSchema: yield* decodeOutputSchema(text).pipe(Effect.mapError(usage)) }; }); const messageArgument = Argument.String("message").pipe( From c8f8ad17ac50f4edfbc138969e1154fc0678494f Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 01:11:26 -0600 Subject: [PATCH 002/118] fix(web): RTF previews open files that declare code page 0 or 866 (#41277) Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 8 ++++++++ apps/web/src/components/files/extendedDocumentPreview.ts | 2 ++ 2 files changed, 10 insertions(+) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index c2b6aa0b306d7..53783c7ded6a3 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -296,6 +296,14 @@ Third}`; if (mac.type !== "document") throw new Error("Expected document"); expect(mac.pages[0]!.html).toBe("

Café Crème

"); } + for (const [rtf, expected] of [ + [String.raw`{\rtf1\ansi\ansicpg0 Caf\'e9}`, "

Café

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

Привет

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

Café

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

Привет

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

€5 café

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

pridržana

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

Привет

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

b

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

Not Found

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

Percent-encoded rootfile chapter text.

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

Correct primary chapter

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

Wrong alternate chapter

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

Hello

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

Hello

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

Encoded question mark chapter text.

", + }, + expected: ["Encoded question mark chapter text."], + absent: ["[Skipped document part", "[Extracted text truncated"], + }, { ext: "epub", parts: { From 0ea0db39e272a472f26b97e9bfc3a6c7805112f2 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 12:01:33 -0600 Subject: [PATCH 107/118] fix(shared): PascalCase test doubles like MockTransport.ts count as mocks (#41561) Co-authored-by: Julius Marminge --- packages/shared/src/changedFileKind.test.ts | 5 +++++ packages/shared/src/changedFileKind.ts | 7 ++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/changedFileKind.test.ts b/packages/shared/src/changedFileKind.test.ts index f16ad777d895c..f77db79426740 100644 --- a/packages/shared/src/changedFileKind.test.ts +++ b/packages/shared/src/changedFileKind.test.ts @@ -6,6 +6,11 @@ describe("classifyChangedFile", () => { it.each([ ["src/contest.py", "code"], ["test/fixtures/pr.json", "mocks"], + ["src/MockTransport.ts", "mocks"], + ["src/FakeClock.ts", "mocks"], + ["src/Foo.Mock.ts", "mocks"], + ["src/Mockup.ts", "code"], + ["src/Stubborn.ts", "code"], ["pnpm-lock.yaml", "generated"], ["convex/_generated/api.d.ts", "generated"], ["src/agent.eval.ts", "tests"], diff --git a/packages/shared/src/changedFileKind.ts b/packages/shared/src/changedFileKind.ts index 7da5ba5cb0c11..dca226bd06fc8 100644 --- a/packages/shared/src/changedFileKind.ts +++ b/packages/shared/src/changedFileKind.ts @@ -47,8 +47,9 @@ const GENERATED_NAME = /(\.generated\.|\.gen\.|\.g\.dart$|\.pb\.go$|_pb2(_grpc)?\.py$|\.pb\.(cc|h)$|\.min\.(js|css)$|\.(js|css)\.map$)/; const GENERATED_DIRS = new Set(["__generated__", "_generated", "generated"]); -const MOCK_NAME = - /(\.snap$|\.(mocks?|fixtures?|stubs?|fakes?)\.[^.]+$|^(mocks?|fixtures?|stubs?|fakes?)([-_.A-Z]|$))/; +const MOCK_NAME = /(\.snap$|\.(mocks?|fixtures?|stubs?|fakes?)\.[^.]+$)/i; +// Case-sensitive after the prefix: `MockClock.ts` is a mock, `Mockup.ts` is not. +const MOCK_PREFIX = /^([Mm]ocks?|[Ff]ixtures?|[Ss]tubs?|[Ff]akes?)([-_.A-Z]|$)/; const MOCK_DIRS = new Set([ "__fixtures__", "__mocks__", @@ -99,7 +100,7 @@ export function classifyChangedFile(path: string): ChangedFileKind { const inDir = (set: ReadonlySet) => dirs.some((dir) => set.has(dir)); if (GENERATED_FILES.has(name.toLowerCase()) || GENERATED_NAME.test(name) || inDir(GENERATED_DIRS)) return "generated"; - if (MOCK_NAME.test(name) || inDir(MOCK_DIRS)) return "mocks"; + if (MOCK_NAME.test(name) || MOCK_PREFIX.test(name) || inDir(MOCK_DIRS)) return "mocks"; if (TEST_NAME.test(name) || CLASS_TEST_NAME.test(name) || inDir(TEST_DIRS)) return "tests"; if (DOCS_NAME.test(name) && !NOT_DOCS_NAME.test(name)) return "docs"; return "code"; From 7f0e736cdba5987e2bc9a9e82e03cfde2d80b62a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 10:21:19 -0800 Subject: [PATCH 108/118] fix(server): GitHub issue URLs with no project on their host name the missing project (#41581) --- apps/server/src/issue/IssueService.test.ts | 21 +++++++++++++++++++++ apps/server/src/issue/IssueService.ts | 5 ++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 26d02c06bfe66..f658c26f6c63c 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -349,6 +349,27 @@ describe("IssueService", () => { }), ); + it.effect( + "does not call a GitHub issue URL unbrowsable when no project is a GitHub checkout", + () => + Effect.gen(function* () { + // A plain folder project, while GitHub itself is a supported tracker. + const service = yield* makeService({ + projects: [project({ id: "folder" })], + trackers: [fakeTracker()], + }); + const resolved = yield* service + .resolveUrl("https://github.com/acme/web/issues/1", "folder" as ProjectId) + .pipe(Effect.result); + if (resolved._tag === "Failure") { + expect(resolved.failure).not.toMatchObject({ + _tag: "IssueUnavailableError", + reason: "tracker-unsupported", + }); + } + }), + ); + it.effect("resolves both legacy Azure work item URLs through the bound project", () => Effect.gen(function* () { const tracker = IssueTrackerKind.make("azure-devops"); diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 01d8b47382eef..1a913c9b0725f 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -824,7 +824,10 @@ const make = Effect.gen(function* () { if (standalone === null) { const found = serve(onTracker); if (found === null) { - return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + return yield* new IssueOperationError({ + operation: "resolveUrl", + detail: `No project in T3 Code is on ${link.host}. Add any ${link.host} project to read its issues.`, + }); } return found.resolved; } From c42fffcf703a639a5dd9a61873e8dc2205afb4e7 Mon Sep 17 00:00:00 2001 From: Kalven Schraut Date: Mon, 23 Nov 2026 12:23:04 -0600 Subject: [PATCH 109/118] fix(server): stop surviving background work after rollback --- .../BackgroundWorkStop.integration.test.ts | 25 +++++++++++++------ .../src/orchestration-v2/Orchestrator.ts | 18 ++++++------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts index 2faa33ec8fcba..2308dc620a401 100644 --- a/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts +++ b/apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts @@ -40,6 +40,7 @@ const stopEarlierBackgroundWork = ({ wakeAfterStop = false, failedStart = false, stopWithQueue, + laterRunStatus = "queued", olderStart = false, backgroundWorkAfterStop, stalledRun, @@ -49,6 +50,7 @@ const stopEarlierBackgroundWork = ({ readonly failedStart?: boolean; readonly backgroundWorkAfterStop?: "running" | "unknown"; readonly stopWithQueue?: "thread.stop" | "run.interrupt"; + readonly laterRunStatus?: "queued" | "rolled_back"; readonly olderStart?: boolean; readonly workflowMember?: boolean; readonly stalledRun?: "missing-session-terminal" | "returned-interrupt" | "superseded-attempt"; @@ -989,12 +991,17 @@ const stopEarlierBackgroundWork = ({ yield* sink.write({ events: [ { - id: EventId.make("queue-held"), + id: EventId.make("later-run-status"), type: "run.updated", threadId, runId: queued.id, occurredAt: now, - payload: { ...queued, queueHeld: true }, + payload: { + ...queued, + status: laterRunStatus, + queueHeld: laterRunStatus === "queued", + completedAt: laterRunStatus === "rolled_back" ? now : null, + }, }, { id: EventId.make("latest-run-settled"), @@ -1059,8 +1066,8 @@ const stopEarlierBackgroundWork = ({ assert.equal(after.runs.find((run) => run.id === watcherRun.runId)?.status, "interrupted"); } if (stopWithQueue !== undefined) { - assert.equal(after.runs.at(-1)?.status, "queued"); - assert.equal(after.runs.at(-1)?.queueHeld, true); + assert.equal(after.runs.at(-1)?.status, laterRunStatus); + assert.equal(after.runs.at(-1)?.queueHeld, laterRunStatus === "queued"); assert.lengthOf(started, 1); } assert.deepEqual( @@ -1127,9 +1134,13 @@ it.effect("Stop preserves the roster when the background work probe fails", () = stopEarlierBackgroundWork({ failedStart: true, backgroundWorkAfterStop: "unknown" }), ); -it.effect.each(["thread.stop", "run.interrupt"] as const)( - "%s stops background work when a later message is queued", - (stopType) => stopEarlierBackgroundWork({ stopWithQueue: stopType }), +it.effect.each([ + ["thread.stop", "queued"], + ["run.interrupt", "queued"], + ["thread.stop", "rolled_back"], + ["run.interrupt", "rolled_back"], +] as const)("%s stops background work when a later run is %s", ([stopType, laterRunStatus]) => + stopEarlierBackgroundWork({ stopWithQueue: stopType, laterRunStatus }), ); it.effect.each(["thread.stop", "run.interrupt"] as const)( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ee056d4b5d73d..1d97c59ca8570 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -890,6 +890,10 @@ function hasLiveRun(projection: Pick): return projection.runs.some(isLiveRun); } +function latestRunForBackgroundWork(runs: ReadonlyArray) { + return runs.findLast((run) => run.status !== "queued" && run.status !== "rolled_back"); +} + function withPullRequestWatch( link: ThreadPullRequestLink, watch: ThreadPullRequestWatch | undefined, @@ -4692,9 +4696,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio !runningRunExists && backgroundWorkHoldsCompletion( derivePendingBackgroundWork({ - latestRun: projection.runs.findLast( - (run) => run.status !== "queued" && run.status !== "rolled_back", - ), + latestRun: latestRunForBackgroundWork(projection.runs), providerThreads: projection.providerThreads, turnItems: projection.turnItems.filter( (item) => item.type !== "subagent" || item.origin !== "app_owned", @@ -13915,7 +13917,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? undefined : projection.providerThreads.find((candidate) => candidate.id === run?.providerThreadId); const hasBackgroundWork = - run?.id === projection.runs.findLast((candidate) => candidate.status !== "queued")?.id && + run !== undefined && + run.id === latestRunForBackgroundWork(projection.runs)?.id && derivePendingBackgroundWork({ latestRun: run, providerThreads: projection.providerThreads, @@ -14519,12 +14522,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) ? Effect.void : Ref.update(effects, (existing) => [...existing, delegatedTasksStopEffect(command)]); - const latestRun = projection.runs.findLast((run) => run.status !== "queued"); + const latestRun = latestRunForBackgroundWork(projection.runs); const target = - projection.runs.findLast( - (run) => - run.status === "preparing" || run.status === "starting" || run.status === "running", - ) ?? + projection.runs.findLast(isLiveRun) ?? (derivePendingBackgroundWork({ latestRun, providerThreads: projection.providerThreads, From a369642c1c5c7a9a1e6b906167e3309005ad23e4 Mon Sep 17 00:00:00 2001 From: Victor Date: Mon, 23 Nov 2026 12:32:01 -0600 Subject: [PATCH 110/118] fix(web): keys pressed on a focused video stay with the player (#41578) Co-authored-by: Julius Marminge --- .../components/chat/composerFocusRedirect.ts | 1 + .../chat/useChatShortcuts.browser.test.tsx | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/apps/web/src/components/chat/composerFocusRedirect.ts b/apps/web/src/components/chat/composerFocusRedirect.ts index cb187e73ea6a7..2fc544a31c9b4 100644 --- a/apps/web/src/components/chat/composerFocusRedirect.ts +++ b/apps/web/src/components/chat/composerFocusRedirect.ts @@ -12,6 +12,7 @@ const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [ "button", "a[href]", "summary", + "video[controls]", '[role="application"]', '[role="button"]', '[role="checkbox"]', diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx index 61127d1a9d9c8..378bc2b5cce74 100644 --- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx +++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx @@ -245,3 +245,21 @@ it("runs right panel commands from inside a side chat pane, but not thread comma expect(ran).toEqual(["toggle", "close", "toggle"]); }); + +it("leaves keys to a focused video player with controls", async () => { + const composerKeys: string[] = []; + await using _screen = await render( + <> + +