From 7379f1969b0f4b579327cf81299ef8cc3ddf8e9c Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:04:04 +0100 Subject: [PATCH 001/112] fix(web): keypad navigation works with NumLock off (#37175) Co-authored-by: Julius Marminge --- apps/web/src/terminal/ghostty/core.test.ts | 44 +++++---- apps/web/src/terminal/ghostty/keyCodes.ts | 27 +++++- ...rminal-numlock-off-keypad-navigates.e2e.ts | 90 +++++++++++++++++++ 3 files changed, 143 insertions(+), 18 deletions(-) create mode 100644 scripts/scenarios/terminal-numlock-off-keypad-navigates.e2e.ts diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index 147af94a10d1..b17b86b96d3c 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -130,28 +130,40 @@ describe("GhosttyTerminalCore snapshots", () => { }); it.each([ + { code: "Numpad1", key: "End", expected: "\x1b[F" }, + { code: "Numpad5", key: "Clear", expected: "\x1b[E" }, + { code: "Numpad8", key: "ArrowUp", expected: "\x1b[A" }, + { code: "NumpadDecimal", key: "Delete", expected: "\x1b[3~" }, + { mode: "\x1b[?1h", code: "Numpad8", key: "ArrowUp", expected: "\x1bOA" }, + { mode: "\x1b[>1u", code: "Numpad8", key: "ArrowUp", expected: "\x1b[57419u" }, + { mode: "\x1b=\x1b[?1035l", code: "Numpad8", key: "8", numLock: true, expected: "\x1bOx" }, + { mode: "\x1b[>1u", code: "Numpad8", key: "8", numLock: true, expected: "8" }, { code: "", key: "Backspace", expected: "\x7f" }, { code: "Unidentified", key: "Backspace", expected: "\x7f" }, { code: "Backspace", key: "Backspace", expected: "\x7f" }, { code: "Delete", key: "Backspace", expected: "\x1b[3~" }, { code: "", key: "a", expected: "a" }, { code: "", key: "Unidentified", expected: "" }, - ])("encodes key $key with physical code '$code'", async ({ code, key, expected }) => { - const core = await createCore(); - const event = { - code, - key, - repeat: false, - shiftKey: false, - ctrlKey: false, - altKey: false, - metaKey: false, - isComposing: false, - getModifierState: () => false, - } as unknown as KeyboardEvent; - - expect(core.encodeKey(event)).toBe(expected); - }); + ])( + "encodes key $key with physical code '$code'", + async ({ mode = "", code, key, numLock = false, expected }) => { + const core = await createCore(); + core.write(mode); + const event = { + code, + key, + repeat: false, + shiftKey: false, + ctrlKey: false, + altKey: false, + metaKey: false, + isComposing: false, + getModifierState: (modifier: string) => modifier === "NumLock" && numLock, + } as unknown as KeyboardEvent; + + expect(core.encodeKey(event)).toBe(expected); + }, + ); it.each(["", "\x1b[>1u"])("encodes macOS Option text with keyboard mode %j", async (mode) => { using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); diff --git a/apps/web/src/terminal/ghostty/keyCodes.ts b/apps/web/src/terminal/ghostty/keyCodes.ts index bb13c09c8d2e..d70fe13463c0 100644 --- a/apps/web/src/terminal/ghostty/keyCodes.ts +++ b/apps/web/src/terminal/ghostty/keyCodes.ts @@ -190,9 +190,32 @@ export function ghosttyKeyForCode(code: string): number { return codeToGhosttyKey.get(code) ?? 0; } +// With NumLock off, keypad digits report navigation keys; Ghostty encodes those as keypad variants. +const NUMPAD_NAVIGATION_KEYS = new Map( + ( + [ + ["ArrowDown", "NumpadArrowDown"], + ["ArrowLeft", "NumpadArrowLeft"], + ["ArrowRight", "NumpadArrowRight"], + ["ArrowUp", "NumpadArrowUp"], + ["Clear", "NumpadBegin"], + ["Delete", "NumpadDelete"], + ["End", "NumpadEnd"], + ["Home", "NumpadHome"], + ["Insert", "NumpadInsert"], + ["PageDown", "NumpadPageDown"], + ["PageUp", "NumpadPageUp"], + ] as const + ).map(([key, code]) => [key, ghosttyKeyForCode(code)]), +); + export function ghosttyKeyForEvent(event: Pick): number { - // Android browsers can omit the physical code for keys such as Backspace. - return ghosttyKeyForCode(event.code) || ghosttyKeyForCode(event.key); + return ( + (event.code.startsWith("Numpad") && NUMPAD_NAVIGATION_KEYS.get(event.key)) || + ghosttyKeyForCode(event.code) || + // Android browsers can omit the physical code for keys such as Backspace. + ghosttyKeyForCode(event.key) + ); } export interface GhosttyKeyboardLayoutMap { diff --git a/scripts/scenarios/terminal-numlock-off-keypad-navigates.e2e.ts b/scripts/scenarios/terminal-numlock-off-keypad-navigates.e2e.ts new file mode 100644 index 000000000000..4b4652aa2d7a --- /dev/null +++ b/scripts/scenarios/terminal-numlock-off-keypad-navigates.e2e.ts @@ -0,0 +1,90 @@ +/// +// The DOM lib types the function this scenario runs in the page. +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { runPromise, test, WEB } from "./t3.ts"; + +// A raw-mode program turns on application cursor and keypad modes as ncurses keypad(TRUE) does, +// asks for DECCKM so its reply marks when the terminal has applied them, and logs what it reads. +const PROBE = String.raw`import { appendFileSync, writeFileSync } from "node:fs"; + +const log = new URL("received", import.meta.url); +writeFileSync(log, ""); +process.stdin.setRawMode(true); +process.stdin.on("data", (chunk) => { + appendFileSync(log, chunk); + if (chunk.includes("x")) { + process.stdout.write("\x1b[?1l\x1b>"); + process.stdin.setRawMode(false); + process.exit(0); + } +}); +process.stdout.write("\x1b[?1h\x1b=\x1b[?1$p"); +`; + +const READY = "\x1b[?1;1$y"; +// Keypad keys as a browser reports them with NumLock off: the physical digit, the navigation key. +const KEYPAD = [ + { code: "Numpad8", key: "ArrowUp" }, + { code: "Numpad1", key: "End" }, + { code: "NumpadDecimal", key: "Delete" }, +]; + +test( + "NumLock-off keypad navigation keys reach a terminal program", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo", { "keypad-probe.mjs": PROBE }); + const thread = await t3.thread({ project, title: "Keypad", messages: ["hello"] }); + const read = (file: string) => + runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readFileString(`${project}/${file}`); + }).pipe(Effect.orElseSucceed(() => "")), + ); + await t3.open(thread); + + await screen.getByRole("button", "Toggle terminal drawer").tap(); + const terminal = screen.getByLabel("Terminal input"); + + // Input sent before the shell runs is dropped, so retype until it lands. + await expect + .poll( + async () => { + await terminal.focus(); + await browser.keyboard.type(`echo ready > '${project}/shell-ready'`); + await browser.keyboard.press("Enter"); + return read("shell-ready"); + }, + { timeout: 30_000 }, + ) + .toBe("ready\n"); + + await terminal.focus(); + await browser.keyboard.type(`'${process.execPath}' '${project}/keypad-probe.mjs'`); + await browser.keyboard.press("Enter"); + await expect.poll(() => read("received"), { timeout: 15_000 }).toBe(READY); + + // The e2e keyboard cannot press a keypad key with NumLock off, so send the events Chromium reports. + await browser.evaluate((keys) => { + const input = document.activeElement; + if (!input) throw new Error("Terminal input lost focus"); + for (const init of keys) { + for (const type of ["keydown", "keyup"]) { + const options = { ...init, location: 3, bubbles: true, cancelable: true }; + input.dispatchEvent(new KeyboardEvent(type, options)); + } + } + return null; + }, KEYPAD); + await browser.keyboard.type("x"); + await app.screenshot("after-keypad"); + + await expect + .poll(() => read("received"), { timeout: 10_000 }) + .toBe(`${READY}\x1bOA\x1bOF\x1b[3~x`); + }, +); From 8897a6ebe194b2d22955cda8936f519c484b35a9 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:17:55 +0100 Subject: [PATCH 002/112] fix(web): keep thread mentions when editing sent messages (#37183) --- .../web/src/components/ChatView.logic.test.ts | 77 +++++++++++++++++++ apps/web/src/components/chat/chatViewSend.ts | 13 +++- .../components/chat/composerPromptHistory.ts | 7 +- ...edit-from-here-keeps-thread-mention.e2e.ts | 32 ++++++++ 4 files changed, 122 insertions(+), 7 deletions(-) create mode 100644 scripts/scenarios/edit-from-here-keeps-thread-mention.e2e.ts diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index d9877b83c01b..d1ff164f16a9 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,3 +1,11 @@ +import { rewindToMessage } from "./chat/chatViewSend"; +import * as session from "../state/session"; +import { + environmentContextRecord, + environmentContextReference, + threadContextReference, +} from "../lib/composerContextRecords"; +import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { prepareRevertedMessageAttachments, boundAttachmentIds, @@ -909,6 +917,75 @@ describe("waitForRevertedMessage", () => { afterEach(() => vi.restoreAllMocks()); + it("restores the rewound message's thread and machine mentions beside the existing draft", async () => { + const { state, projection } = projectionAtom(); + vi.spyOn(session, "readPreparedConnection").mockReturnValue({ + httpBaseUrl: "http://localhost", + } as never); + useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} }); + const thread = (id: string, title: string) => + threadContextRecord( + { environmentId: threadRef.environmentId, threadId: ThreadId.make(id) }, + title, + ); + const drafted = thread("drafted-thread", "Drafted thread"); + const mentioned = thread("referenced-thread", "Other thread"); + const machine = environmentContextRecord(EnvironmentId.make("env-2"), "Build box"); + useComposerDraftStore.getState().addThreadContexts(threadRef, [drafted]); + const draftPrompt = useComposerDraftStore.getState().getComposerDraft(threadRef)!.prompt; + const sentPrompt = ensureInlineContextReferences("Review", [ + threadContextReference(mentioned), + environmentContextReference(machine), + ]).trim(); + + const result = await rewindToMessage({ + message: { + id: messageId, + role: "user", + runId: projection.messages[0]!.runId, + streaming: false, + createdAt: "2026-03-29T00:00:10.000Z", + updatedAt: "2026-03-29T00:00:10.000Z", + text: sentPrompt, + context: { version: 1, records: [mentioned, machine] }, + }, + environmentId: threadRef.environmentId, + routeThreadRef: threadRef, + threadId: threadRef.threadId, + turnCount: 1, + restoreFiles: false, + checkpoint: undefined, + draftTarget: threadRef, + composerHasPendingAttachments: false, + createAssetUrl: async () => { + throw new Error("No attachment expected"); + }, + revertThreadCheckpoint: async () => { + appAtomRegistry.set(state, { + data: Option.some({ + ...projection, + providerThreads: projection.providerThreads.map((providerThread) => ({ + ...providerThread, + lastRunOrdinal: 1, + })), + runs: projection.runs.map((run) => + run.ordinal > 1 ? { ...run, status: "rolled_back" as const } : run, + ), + }), + }); + return AsyncResult.success(undefined); + }, + }); + + const prompt = `${draftPrompt}\n\n${sentPrompt}`; + expect(result).toEqual({ error: null, prompt }); + expect(useComposerDraftStore.getState().getComposerDraft(threadRef)).toMatchObject({ + prompt, + threadContexts: [drafted, mentioned], + environmentContexts: [machine], + }); + }); + it("rejects with the projected reason when the rollback fails for good", async () => { const { state, projection } = projectionAtom(); const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {}); diff --git a/apps/web/src/components/chat/chatViewSend.ts b/apps/web/src/components/chat/chatViewSend.ts index 58f12549d15f..079e6d18d5ee 100644 --- a/apps/web/src/components/chat/chatViewSend.ts +++ b/apps/web/src/components/chat/chatViewSend.ts @@ -46,7 +46,7 @@ import { waitForRevertedMessage, } from "../ChatView.logic"; import { readPreparedConnection } from "../../state/session"; -import { recallableComposerPrompt } from "./composerPromptHistory"; +import { recallComposerMessage } from "./composerPromptHistory"; // Kept per route so a send in flight, and the multiple-model selections, survive // ChatView remounting while the user navigates. @@ -151,8 +151,8 @@ export async function startFanoutThread(input: { } /** - * Reverts the thread to before `message` and puts that message's text and - * attachments back in the composer draft. Returns the restored prompt, or the + * Reverts the thread to before `message` and puts that message's text, mentions + * and attachments back in the composer draft. Returns the restored prompt, or the * error to show; on error the draft is untouched. */ export async function rewindToMessage(input: { @@ -221,7 +221,7 @@ export async function rewindToMessage(input: { if (result._tag === "Failure") throw squashAtomCommandFailure(result); }); const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? ""; - const restoredPrompt = recallableComposerPrompt(message.text); + const { prompt: restoredPrompt, mentions } = recallComposerMessage(message); const nextPrompt = restoredPrompt.length === 0 ? currentPrompt @@ -229,6 +229,11 @@ export async function rewindToMessage(input: { ? `${currentPrompt}\n\n${restoredPrompt}` : restoredPrompt; store.setPrompt(draftTarget, nextPrompt); + // The restored prompt already carries the chips; these add only their records. + store.addThreadContexts(draftTarget, mentions.threadContexts, { appendReference: false }); + store.addEnvironmentContexts(draftTarget, mentions.environmentContexts, { + appendReference: false, + }); const images: ComposerImageAttachment[] = []; const restoredFiles: ComposerFileAttachment[] = []; files.forEach((file, index) => { diff --git a/apps/web/src/components/chat/composerPromptHistory.ts b/apps/web/src/components/chat/composerPromptHistory.ts index a4f4ed62a7c0..65244d9259b8 100644 --- a/apps/web/src/components/chat/composerPromptHistory.ts +++ b/apps/web/src/components/chat/composerPromptHistory.ts @@ -141,8 +141,9 @@ export function recallableComposerPrompt( return trimmed; } -function recallMessage( - message: ComposerPromptHistoryMessage, +/** A sent message's text as the composer can hold it, with the mention records its chips need. */ +export function recallComposerMessage( + message: Pick, ): Pick { const records = message.context?.records ?? []; const threadRecords = records.filter(isThreadContextRecord); @@ -172,7 +173,7 @@ export function buildComposerPromptHistoryEntries( if (message.role !== "user") continue; // Automations and other agents send user-role messages; recall only what the user typed. if (resolveUserMessagePresentation(message).attribution !== null) continue; - const { prompt, mentions } = recallMessage(message); + const { prompt, mentions } = recallComposerMessage(message); if (prompt.length === 0) continue; const entry = { id: message.id, prompt, mentions }; const previous = entries[entries.length - 1]; diff --git a/scripts/scenarios/edit-from-here-keeps-thread-mention.e2e.ts b/scripts/scenarios/edit-from-here-keeps-thread-mention.e2e.ts new file mode 100644 index 000000000000..677d34522d7c --- /dev/null +++ b/scripts/scenarios/edit-from-here-keeps-thread-mention.e2e.ts @@ -0,0 +1,32 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Edit from here puts a sent message back with its thread mention", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + await t3.thread({ project, title: "Release notes", messages: ["Draft the notes"] }); + const thread = await t3.thread({ project, title: "Review work", messages: ["Start"] }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @Release"); + await screen.getByRole("option", "Release notes", { exact: false }).tap(); + await expect(composer).toContainText("Release notes"); + await browser.keyboard.press("Enter"); + + // The seeded message came from the CLI, which the timeline attributes to an agent: only the + // message sent here offers Edit from here. + const editFromHere = screen.getByRole("button", "Edit from here"); + await expect(editFromHere).toHaveCount(1, { timeout: 60_000 }); + await expect(editFromHere).toBeEnabled({ timeout: 60_000 }); + await editFromHere.tap(); + await screen.getByRole("button", "Revert and keep changes").tap(); + + await expect(composer).toContainText("Review"); + await app.screenshot("restored-draft"); + await expect(composer).toContainText("Release notes"); + }, +); From dcaedc980034008cdf99fe18340cd3018869f154 Mon Sep 17 00:00:00 2001 From: Katya Date: Sun, 15 Nov 2026 13:23:29 +0100 Subject: [PATCH 003/112] fix(server): skills linked by a SessionStart hook appear in the $ picker in the same session (#37165) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 76 +++++ .../Adapters/ClaudeAdapterV2.ts | 16 +- .../src/provider/Drivers/ClaudeDriver.ts | 8 + .../src/provider/ProviderRegistry.test.ts | 290 ++++++++++++++++++ apps/server/src/provider/ProviderRegistry.ts | 87 +++++- .../client-runtime/src/providerSkills.test.ts | 35 ++- packages/client-runtime/src/providerSkills.ts | 14 +- .../client-runtime/src/state/server.test.ts | 10 + packages/client-runtime/src/state/server.ts | 19 +- packages/contracts/src/server.ts | 5 + packages/provider-core/src/server/driver.ts | 6 + 11 files changed, 533 insertions(+), 33 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 419b5a340389..4bb712aa9ffc 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3550,6 +3550,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { > & Partial>; readonly environment?: NodeJS.ProcessEnv; + readonly onSessionInit?: (cwd: string) => Effect.Effect; readonly subagentLaunchToolUseId?: string; readonly subagentModel?: string; readonly nativeSessionId?: string; @@ -3625,6 +3626,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { path: yield* Path.Path, random: yield* SecureRandom.SecureRandom, idAllocator, + ...(options?.onSessionInit ? { onSessionInit: options.onSessionInit } : {}), ...(options?.routeModelCatalog ? { routeModelCatalog: options.routeModelCatalog } : {}), continuationRequests: { offer: (request) => @@ -4167,6 +4169,80 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("reports the session cwd on each process's first init, not on repeated inits", () => + Effect.gen(function* () { + const initCwds: Array = []; + const harness = yield* makeWakeHarnessWithOptions({ + freshQueueOnReopen: true, + close: (queue) => Queue.shutdown(queue), + onSessionInit: (cwd) => + Effect.sync(() => { + initCwds.push(cwd); + }), + }); + // The CLI may report a resolved path, not the cwd clients key their snapshots on. + const init = (uuid: string) => + claudeSdkFrame({ + type: "system", + subtype: "init", + cwd: "/private/workspace", + session_id: WAKE_NATIVE_SESSION, + uuid, + }); + const latest = (): OrchestrationV2ProviderThread => { + const event = harness.events.findLast( + (candidate) => candidate.type === "provider_thread.updated", + ); + return event?.type === "provider_thread.updated" + ? event.providerThread + : harness.providerThread; + }; + const turn = (ordinal: number) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: latest(), + now: DateTime.makeUnsafe(0), + attemptId: RunAttemptId.make(`session-init-${ordinal}`), + text: `Turn ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + }); + yield* harness.runtime.startTurn(turn(1)); + assert.deepEqual(initCwds, []); + yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000701")); + assert.deepEqual(initCwds, ["/workspace"]); + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); + // The CLI repeats init on every turn of one process; its startup hooks ran once. + yield* harness.runtime.startTurn(turn(2)); + yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000702")); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000703", result: "Two." }), + ); + yield* Queue.take(harness.terminalReceipts); + assert.deepEqual(initCwds, ["/workspace"]); + yield* harness.runtime.interruptTurn({ + providerThread: latest(), + providerTurnId: lastProviderTurn(harness.events).id, + requestRuntimeRestart: true, + }); + yield* harness.runtime.startTurn(turn(3)); + assert.equal(harness.processQueues.length, 2); + yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000704")); + assert.deepEqual(initCwds, ["/workspace", "/workspace"]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("resumes the session a /clear selected after the Claude process is replaced", () => Effect.gen(function* () { const harness = yield* makeWakeHarnessWithOptions({ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index a83be3cd0152..e8cfd9d8ce08 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5468,6 +5468,11 @@ export interface ClaudeAdapterV2Options { readonly queryRunner: ClaudeAgentSdkQueryRunnerShape; readonly scopedLimitNames?: Ref.Ref; readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"]; + /** + * Called with the requested cwd on a process's first init message, after its synchronous + * SessionStart hooks have run, so cwd-keyed workspace scans can be refreshed. + */ + readonly onSessionInit?: (cwd: string) => Effect.Effect; /** * Applies Claude Code's reported model ids for a turn's cwd, so turns send ids its backend * accepts. Defaults to the catalog unchanged. @@ -12812,11 +12817,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Stream.runForEach((message) => sdkMessageLock.withPermits(1)( Effect.suspend(() => { + let firstInit = false; if ( message.type === "system" && message.subtype === "init" && !context.receivedInit ) { + firstInit = true; context.openedPermissionMode = message.permissionMode ?? context.openedPermissionMode; context.receivedInit = true; @@ -12855,7 +12862,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( resultsReportingNewContextWindow.add(message); } } - return handleSdkMessage({ query: querySession, message }); + const handled = handleSdkMessage({ query: querySession, message }); + const reportedCwd = turnInput.runtimePolicy.cwd; + if (!firstInit || reportedCwd === null || !adapterOptions.onSessionInit) { + return handled; + } + return adapterOptions.onSessionInit(reportedCwd).pipe(Effect.andThen(handled)); }), ), ), @@ -14385,7 +14397,7 @@ export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")( input: ProviderAdapterDriverCreateInput, hooks: Pick< ClaudeAdapterV2Options, - "scopedLimitNames" | "onUsageLimits" | "modelCatalog" | "routeModelCatalog" + "scopedLimitNames" | "onUsageLimits" | "onSessionInit" | "modelCatalog" | "routeModelCatalog" > = {}, ) { const { instanceId, environment, enabled, config } = input; diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index d75b1cad8640..5bedffe9242b 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -1,13 +1,16 @@ import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts"; import * as Cache from "effect/Cache"; +import type * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; @@ -167,6 +170,9 @@ export const ClaudeDriver: ProviderDriver(); + yield* Effect.addFinalizer(() => Queue.end(workspaceRescans)); const orchestrationAdapter = yield* createClaudeAdapterV2( { instanceId, @@ -179,6 +185,7 @@ export const ClaudeDriver: ProviderDriver snapshot.applyUsageLimits(update), + onSessionInit: (cwd) => Queue.offer(workspaceRescans, cwd).pipe(Effect.asVoid), modelCatalog, routeModelCatalog: modelRoutes.route, }, @@ -412,6 +419,7 @@ export const ClaudeDriver: ProviderDriver snapshot.getSnapshot.pipe( Effect.flatMap((machineSnapshot) => diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index c42d78b237d4..27c1cd15a8d7 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -156,6 +156,135 @@ const layerBackgroundPolicyAlwaysRun = Layer.mock(BackgroundPolicy.BackgroundPol shouldRunOpportunisticWork: Effect.succeed(true), }); +const makeWorkspaceRescanHarness = Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("claude"); + const driver = ProviderDriverKind.make("claudeCode"); + const provider = { + instanceId, + driver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "1970-01-01T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const scans = yield* Queue.unbounded<{ + readonly cwd: string; + readonly result: Deferred.Deferred; + }>(); + const makeInstance = Effect.gen(function* () { + const rescans = yield* Queue.unbounded(); + const reports = yield* Queue.unbounded(); + const instance: ProviderInstance = { + instanceId, + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: "claude:rescan-test" }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(provider), + refresh: Effect.succeed(provider), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + // A pull-based stream pulls the next report only after the registry queued the last. + workspaceRescans: Stream.fromQueue(rescans).pipe( + Stream.tap((cwd) => Queue.offer(reports, cwd)), + ), + snapshotForCwd: (cwd) => + Effect.gen(function* () { + const result = yield* Deferred.make(); + yield* Queue.offer(scans, { cwd, result }); + return yield* Deferred.await(result); + }), + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }; + return { instance, rescans, reports }; + }); + const first = yield* makeInstance; + const instances = yield* Ref.make([first.instance]); + const changes = yield* PubSub.unbounded(); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const services = yield* Layer.build( + ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), + Layer.provideMerge( + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, { + getInstance: (id) => + Ref.get(instances).pipe(Effect.map((all) => all.find((i) => i.instanceId === id))), + listInstances: Ref.get(instances), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }), + ), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-workspace-rescan-" })), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ).pipe(Scope.provide(scope)); + const registry = yield* ProviderRegistry.ProviderRegistry.pipe(Effect.provide(services)); + const snapshot = (name: string): ProviderWorkspaceSnapshot => ({ + ...provider, + skills: [{ name, path: `/workspace/${name}/SKILL.md`, enabled: true }], + }); + const nextScan = Effect.fnUntraced(function* (cwd: string) { + const scan = yield* Queue.take(scans); + assert.equal(scan.cwd, cwd); + return (name: string) => Deferred.succeed(scan.result, snapshot(name)); + }); + const refresh = (cwd: string, fresh = false) => + registry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh }); + const seed = Effect.fnUntraced(function* (cwd: string) { + const pending = yield* refresh(cwd).pipe(Effect.forkChild); + const complete = yield* nextScan(cwd); + yield* complete("initial"); + yield* Fiber.join(pending); + }); + // A later requested cwd reaching the serial consumer proves the previous rescan settled, + // including when that rescan correctly publishes no change. Seed "/barrier" first; it rescans + // to the skills it was seeded with, so it never stamps workspaceRescannedAt. + const drainRescans = Effect.gen(function* () { + yield* Queue.offer(first.rescans, "/barrier"); + const complete = yield* nextScan("/barrier"); + yield* complete("initial"); + }); + const skillsOf = (cwd: string) => + Effect.map(registry.getProviders, (providers) => + providers[0]?.workspaceSnapshots?.find((s) => s.cwd === cwd)?.skills?.map((s) => s.name), + ); + const rescannedAtOf = Effect.map( + registry.getProviders, + (providers) => providers[0]?.workspaceRescannedAt, + ); + return { + first, + makeInstance, + instances, + changes, + registry, + scans, + nextScan, + refresh, + seed, + drainRescans, + skillsOf, + rescannedAtOf, + }; +}); + function selectDescriptor( id: string, label: string, @@ -931,6 +1060,20 @@ it.layer( unchanged.workspaceSnapshots?.map((snapshot) => snapshot.cwd), ["/project", "/plain"], ); + // A machine health refresh must not read as a rescan, nor erase the last one. + const rescanned = { ...withCatalog, workspaceRescannedAt: "2026-03-25T00:01:00.000Z" }; + assert.equal( + ProviderRegistry.mergeProviderSnapshot(rescanned, provider).workspaceRescannedAt, + "2026-03-25T00:01:00.000Z", + ); + assert.equal( + ProviderRegistry.mergeProviderSnapshot(rescanned, { + ...provider, + workspaceRescannedAt: "2026-03-25T00:02:00.000Z", + }).workspaceRescannedAt, + "2026-03-25T00:02:00.000Z", + ); + assert.equal(unchanged.workspaceRescannedAt, undefined); const changed = ProviderRegistry.mergeProviderSnapshot(withCatalog, { ...provider, models: [machineModel, addedModel], @@ -2285,6 +2428,153 @@ it.layer( }), ); + it.effect("rescans a requested cwd whose snapshot is still current", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* h.seed("/workspace"); + assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]); + yield* Queue.offer(h.first.rescans, "/workspace"); + const complete = yield* h.nextScan("/workspace"); + yield* complete("hook"); + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/workspace"), ["hook"]); + // Clients that fetched the old skills are told to fetch again. + const scannedAt = (yield* h.registry.getProviders)[0]?.workspaceSnapshots?.find( + (snapshot) => snapshot.cwd === "/workspace", + )?.checkedAt; + assert.isString(scannedAt); + assert.equal(yield* h.rescannedAtOf, scannedAt); + }), + ); + + it.effect("stamps a rescan whose awaited scan already published the change", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* h.seed("/workspace"); + const ordinary = yield* h.refresh("/workspace", true).pipe(Effect.forkChild); + const completeOrdinary = yield* h.nextScan("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + yield* Queue.take(h.first.reports); + // Let the consumer reach its wait on the running scan. + yield* TestClock.adjust(0); + yield* completeOrdinary("hook"); + yield* Fiber.join(ordinary); + const completeRescan = yield* h.nextScan("/workspace"); + yield* completeRescan("hook"); + yield* h.drainRescans; + assert.isString(yield* h.rescannedAtOf); + }), + ); + + it.effect("leaves workspaceRescannedAt unset when a rescan changes nothing", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* h.seed("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + const complete = yield* h.nextScan("/workspace"); + yield* complete("initial"); + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]); + assert.equal(yield* h.rescannedAtOf, undefined); + }), + ); + + it.effect("starts no scan for a reported cwd nobody requested", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + yield* Queue.offer(h.first.rescans, "/unrequested"); + // The next scan being the barrier's shows the report started none. + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/unrequested"), undefined); + }), + ); + + it.effect("rescans after an initial scan in flight when the hook report arrives", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + const initial = yield* h.refresh("/workspace").pipe(Effect.forkChild); + const completeInitial = yield* h.nextScan("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + yield* Queue.take(h.first.reports); + // Let the consumer reach its wait on the running scan. + yield* TestClock.adjust(0); + yield* completeInitial("initial"); + // The requesting client's reply is its only copy of the scan, so the rescan must not + // supersede it. + const reply = yield* Fiber.join(initial); + assert.deepEqual( + reply[0]?.workspaceSnapshots + ?.find((s) => s.cwd === "/workspace") + ?.skills?.map((s) => s.name), + ["initial"], + ); + const completeRescan = yield* h.nextScan("/workspace"); + yield* completeRescan("hook"); + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/workspace"), ["hook"]); + }), + ); + + it.effect("lets a fresh refresh started while a rescan waits keep its own result", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/barrier"); + const initial = yield* h.refresh("/workspace").pipe(Effect.forkChild); + const completeInitial = yield* h.nextScan("/workspace"); + yield* Queue.offer(h.first.rescans, "/workspace"); + yield* Queue.take(h.first.reports); + // Let the consumer reach its wait on the running scan. + yield* TestClock.adjust(0); + const fresh = yield* h.refresh("/workspace", true).pipe(Effect.forkChild); + const completeFresh = yield* h.nextScan("/workspace"); + yield* completeInitial("initial"); + yield* completeFresh("fresh"); + yield* Fiber.join(initial); + const reply = yield* Fiber.join(fresh); + assert.deepEqual( + reply[0]?.workspaceSnapshots + ?.find((s) => s.cwd === "/workspace") + ?.skills?.map((s) => s.name), + ["fresh"], + ); + // The rescan joins the fresh scan, so the next scan started is the barrier's. + yield* h.drainRescans; + assert.deepEqual(yield* h.skillsOf("/workspace"), ["fresh"]); + }), + ); + + it.effect("ignores a queued rescan from a replaced instance", () => + Effect.gen(function* () { + const h = yield* makeWorkspaceRescanHarness; + yield* h.seed("/workspace"); + const replacement = yield* h.makeInstance; + const rebuilt = yield* h.registry.streamChanges.pipe( + Stream.filter((providers) => providers[0]?.workspaceSnapshots === undefined), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + yield* Ref.set(h.instances, [replacement.instance]); + yield* PubSub.publish(h.changes, undefined); + yield* Fiber.join(rebuilt); + yield* h.seed("/workspace"); + yield* h.seed("/barrier"); + // The forwarder pulls the second report only after queueing the first. + yield* Queue.offerAll(h.first.rescans, ["/workspace", "/workspace"]); + yield* Queue.take(h.first.reports); + yield* Queue.take(h.first.reports); + yield* Queue.offer(replacement.rescans, "/barrier"); + // A scan started for the stale report would come before the barrier's. + const completeBarrier = yield* h.nextScan("/barrier"); + yield* completeBarrier("barrier"); + assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]); + }), + ); + it.effect("scans scanCwd and keys the workspace snapshot by cwd", () => Effect.gen(function* () { const driver = ProviderDriverKind.make("codex"); diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 8a7ff0ac7fd3..f1ae2e51637c 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -20,6 +20,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -329,6 +330,10 @@ export const mergeProviderSnapshot = ( : previousWorkspaceSnapshots !== undefined ? { workspaceSnapshots: previousWorkspaceSnapshots } : {}), + ...(nextProvider.workspaceRescannedAt === undefined && + previousProvider.workspaceRescannedAt !== undefined + ? { workspaceRescannedAt: previousProvider.workspaceRescannedAt } + : {}), ...(shouldRetainMissingOpenCodeMetadata(nextProvider) ? { slashCommands: @@ -481,6 +486,10 @@ export const layer = Layer.effect( const workspaceRefreshesRef = yield* Ref.make< ReadonlyMap>> >(new Map()); + const workspaceRescans = yield* Queue.unbounded<{ + readonly instance: ProviderInstance; + readonly cwd: string; + }>(); const maintenanceActionStatesRef = yield* Ref.make< ReadonlyMap< ProviderInstanceId, @@ -501,7 +510,11 @@ export const layer = Layer.effect( cacheDir: config.providerStatusCacheDir, instanceId: key, }).pipe(Effect.provideService(Path.Path, path)); - const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider; + const { + workspaceSnapshots: _workspaceSnapshots, + workspaceRescannedAt: _workspaceRescannedAt, + ...machineProvider + } = provider; yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), @@ -927,6 +940,11 @@ export const layer = Layer.effect( yield* Stream.runForEach(source.streamChanges, (provider) => correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)), ).pipe(Effect.forkScoped); + if (instance.workspaceRescans) { + yield* Stream.runForEach(instance.workspaceRescans, (cwd) => + Queue.offer(workspaceRescans, { instance, cwd }), + ).pipe(Effect.forkScoped); + } } yield* Effect.yieldNow; @@ -1043,7 +1061,25 @@ export const layer = Layer.effect( readonly cwd: string; readonly scanCwd?: string; readonly fresh?: boolean; + // Set by an instance's own report that its workspace skills changed. + readonly rescan?: ProviderInstance; }) { + const workspaceSnapshotOf = (candidate: ServerProvider | undefined) => + candidate?.workspaceSnapshots?.find((s) => s.cwd === input.cwd); + // What clients saw before the awaited scan, which may already have published the change. + const heldBeforeWait = input.rescan + ? workspaceSnapshotOf( + (yield* Ref.get(providersRef)).find( + (candidate) => candidate.instanceId === input.instanceId, + ), + ) + : undefined; + // A rescan waits for a running scan, which may have read files before the hook linked them. + // Claims are read before snapshots: a scan publishes before it releases its claim. + const runningScan = input.rescan + ? (yield* Ref.get(workspaceRefreshesRef)).get(input.rescan)?.get(input.cwd) + : undefined; + if (runningScan) yield* Deferred.await(runningScan); if (input.fresh) { yield* updateProviders((providers) => providers.map((candidate) => @@ -1055,14 +1091,13 @@ export const layer = Layer.effect( } const providers = yield* Ref.get(providersRef); const provider = providers.find((candidate) => candidate.instanceId === input.instanceId); - const workspaceSnapshotOf = (candidate: ServerProvider | undefined) => - candidate?.workspaceSnapshots?.find((s) => s.cwd === input.cwd); const scannedFrom = workspaceSnapshotOf(provider); const now = yield* DateTime.now; if ( !provider || !provider.enabled || (!input.fresh && + !input.rescan && scannedFrom && !isProviderWorkspaceSnapshotPending(scannedFrom) && isProviderWorkspaceSnapshotCurrent(scannedFrom, DateTime.toEpochMillis(now))) @@ -1074,6 +1109,10 @@ export const layer = Layer.effect( const instance = yield* instanceRegistry.getInstance(input.instanceId); const snapshotForCwd = instance?.snapshotForCwd; if (!instance || !snapshotForCwd) return providers; + // A report never enrolls a cwd nobody requested, nor outlives the instance that made it. + if (input.rescan && (input.rescan !== instance || (!runningScan && !scannedFrom))) { + return providers; + } const token = yield* Deferred.make(); // A machine refresh can change this cwd's snapshot, so the scan publishes against the result. const refreshMachineSnapshot = input.fresh @@ -1104,18 +1143,31 @@ export const layer = Layer.effect( if (Ref.getUnsafe(workspaceRefreshesRef).get(instance)?.get(input.cwd) !== token) { return currentProviders; } - return currentProviders.map((candidate) => - candidate.instanceId === input.instanceId && - Equal.equals(workspaceSnapshotOf(candidate), scanBase) - ? upsertProviderWorkspaceSnapshot(candidate, input.cwd, { - ...scopedSnapshot, - checkedAt: scannedAt, - // Without driver command discovery, retain previous commands after failed health checks and retry. - slashCommandsPending: - scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error", - }) - : candidate, - ); + return currentProviders.map((candidate) => { + if ( + candidate.instanceId !== input.instanceId || + !Equal.equals(workspaceSnapshotOf(candidate), scanBase) + ) { + return candidate; + } + const scanned = upsertProviderWorkspaceSnapshot(candidate, input.cwd, { + ...scopedSnapshot, + checkedAt: scannedAt, + // Without driver command discovery, retain previous commands after failed health checks and retry. + slashCommandsPending: + scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error", + }); + // Clients keep fetched snapshots, so a changed rescan must tell them to fetch again. + const rescanned = workspaceSnapshotOf(scanned); + const held = heldBeforeWait ?? scanBase; + return input.rescan && + !( + Equal.equals(rescanned?.skills, held?.skills) && + Equal.equals(rescanned?.slashCommands, held?.slashCommands) + ) + ? { ...scanned, workspaceRescannedAt: scannedAt } + : scanned; + }); }); }), ), @@ -1158,6 +1210,11 @@ export const layer = Layer.effect( } return yield* Fiber.join(claim.scan); }); + yield* Stream.runForEach(Stream.fromQueue(workspaceRescans), ({ instance, cwd }) => + refreshWorkspaceSnapshot({ instanceId: instance.instanceId, cwd, rescan: instance }).pipe( + Effect.ignoreCause({ log: true }), + ), + ).pipe(Effect.forkScoped); const invalidateModelCaches = Effect.fn("ProviderRegistry.invalidateModelCaches")(function* ( input: Parameters[0], diff --git a/packages/client-runtime/src/providerSkills.test.ts b/packages/client-runtime/src/providerSkills.test.ts index acd4a4904c1d..143efdbe7869 100644 --- a/packages/client-runtime/src/providerSkills.test.ts +++ b/packages/client-runtime/src/providerSkills.test.ts @@ -176,16 +176,25 @@ describe("provider workspace snapshot refresh atom", () => { | null | Promise | null>; - function setup(initialProviders: ReadonlyArray, initialResponses?: Response[]) { + function setup( + initialProviders: ReadonlyArray, + initialResponses?: Response[], + // The client drops a reply whose provider changed while it was in flight. + options?: { readonly droppedReplies?: number }, + ) { + let droppedReplies = options?.droppedReplies ?? 0; const providersAtom = Atom.make | null>(initialProviders); const responses: Response[] = [...(initialResponses ?? [])]; const run = vi.fn(async () => { const providers = await (responses.shift() ?? (() => null))(); - return providers === null - ? AsyncResult.failure<{ providers: ReadonlyArray }, string>( - Cause.fail("offline"), - ) - : AsyncResult.success({ providers }); + if (providers === null) { + return AsyncResult.failure<{ providers: ReadonlyArray }, string>( + Cause.fail("offline"), + ); + } + if (droppedReplies > 0) droppedReplies -= 1; + else registry.set(providersAtom, providers); + return AsyncResult.success({ providers }); }); const family = createProviderWorkspaceSnapshotRefreshAtomFamily({ providers: () => providersAtom, @@ -243,6 +252,20 @@ describe("provider workspace snapshot refresh atom", () => { }, ); + it("asks again at once when the client dropped a complete reply", async () => { + vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") }); + const scanned = withSnapshot("2026-01-01T00:00:00.000Z"); + const { registry, atom, run, unmount } = setup(noSnapshot, [() => scanned, () => scanned], { + droppedReplies: 1, + }); + await vi.advanceTimersByTimeAsync(0); + expect(run).toHaveBeenCalledTimes(2); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(false); + registry.refresh(atom); + expect(run).toHaveBeenCalledTimes(2); + unmount(); + }); + it("keeps the TTL guard for a newly scanned catalog when the client clock is ahead", async () => { vi.useFakeTimers({ now: Date.parse("2026-01-01T01:00:00.000Z") }); const { registry, atom, run, unmount } = setup(withSnapshot("2026-01-01T00:00:00.000Z"), [ diff --git a/packages/client-runtime/src/providerSkills.ts b/packages/client-runtime/src/providerSkills.ts index 0f91fc29f74e..e7dfb12feafe 100644 --- a/packages/client-runtime/src/providerSkills.ts +++ b/packages/client-runtime/src/providerSkills.ts @@ -235,6 +235,7 @@ function failProviderWorkspaceSnapshotRefresh( state: ProviderWorkspaceSnapshotRefreshState, requestedAt: number, now: number, + cooldownMs = WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS, ): ProviderWorkspaceSnapshotRefreshState { // A newer request, or a snapshot loss, already superseded this one. if (state.requestedAt !== requestedAt) return state; @@ -243,7 +244,7 @@ function failProviderWorkspaceSnapshotRefresh( return { ...state, requestedAt: null, - retryNotBefore: now + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS, + retryNotBefore: cooldownMs === 0 ? null : now + cooldownMs, failedAttempts, }; } @@ -335,14 +336,15 @@ export function createProviderWorkspaceSnapshotRefreshAtomFamily(input: { // Outlives this build on purpose: a rebuild must not drop the retry. // Once nothing subscribes, the retry state dies with the node; writing // would recreate and rebuild it, which scans again with no subscriber. - const retryLater = () => { + const retry = (cooldownMs?: number) => { const node = registry.getNodes().get(refreshAtom); if (node === undefined || node.canBeRemoved) return; registry.set(refreshAtom, (state) => // @effect-diagnostics-next-line globalDate:off - failProviderWorkspaceSnapshotRefresh(state, now, Date.now()), + failProviderWorkspaceSnapshotRefresh(state, now, Date.now(), cooldownMs), ); }; + const retryLater = () => retry(); void runAtomCommand( registry, input.refreshProviders, @@ -361,7 +363,11 @@ export function createProviderWorkspaceSnapshotRefreshAtomFamily(input: { (hasCurrentProviderWorkspaceSnapshot(refreshedProvider, cwd, completedAt) || snapshot?.checkedAt !== (provider && resolveProviderWorkspaceSnapshot(provider, cwd))?.checkedAt); - if (!refreshed) retryLater(); + if (!refreshed) return retryLater(); + // A reply is dropped when the provider changed while it was in flight, such as a + // SessionStart rescan; ask again at once for the snapshot that change produced. + const held = findProvider(registry.get(input.providers(environmentId))); + if (!hasCompleteProviderWorkspaceSnapshot(held, cwd)) retry(0); }, retryLater); return plan.state; }, diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index daec4ac7087e..e6ce1725cc15 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -1286,6 +1286,16 @@ describe("server state projection", () => { ).providers[0]?.workspaceSnapshots, ).toBeUndefined(); + // A server rescan that changed the skills retires the snapshot fetched before it. + expect( + withFetchedWorkspaceSnapshots( + configWith(true, [ + { ...provider(claude), workspaceRescannedAt: "2026-10-25T00:09:00.000Z" }, + ] as unknown as ServerConfig["providers"]), + fetched, + ).providers[0]?.workspaceSnapshots, + ).toBeUndefined(); + // A catalog digest stands for the lists: loading them keeps the snapshot, a new digest retires it. const digested = (catalogDigest: string, slashCommands: ReadonlyArray<{ name: string }> = []) => ({ ...provider(claude, undefined, slashCommands), catalogDigest }) as ReturnType< diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index a8c22d24d755..cbc4de0beac7 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -747,8 +747,9 @@ export function resolveServerConfigValue( } /** - * The provider-wide fields a workspace snapshot builds on. A live session, a sign-out, or a - * /usage-limits change shows up here, so a snapshot fetched before it no longer applies. + * The provider-wide fields a workspace snapshot builds on. A live session, a sign-out, a + * /usage-limits change, or a server rescan that changed the skills shows up here, so a snapshot + * fetched before it no longer applies. */ const snapshotBasis = (provider: ServerProviderEntry | undefined) => provider && { @@ -758,6 +759,9 @@ const snapshotBasis = (provider: ServerProviderEntry | undefined) => ...(provider.catalogDigest === undefined ? { slashCommands: provider.slashCommands, skills: provider.skills } : { catalogDigest: provider.catalogDigest }), + ...(provider.workspaceRescannedAt === undefined + ? {} + : { workspaceRescannedAt: provider.workspaceRescannedAt }), }; interface FetchedWorkspaceSnapshot { @@ -1582,6 +1586,11 @@ export function createServerEnvironmentAtoms( refreshProviders: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:refresh-providers", tag: WS_METHODS.serverRefreshProviders, + // A rescan during the request must leave the stored basis behind the new stamp. + onStart: ({ environmentId, input }, registry) => + registry + .get(configValueAtom(environmentId)) + ?.providers.find((provider) => provider.instanceId === input.instanceId), execute: (input, registry, environmentId) => { const { instanceId, cwd } = input; const provider = @@ -1603,7 +1612,7 @@ export function createServerEnvironmentAtoms( : {}), }); }, - onSuccess: ({ environmentId, input }, registry, result) => + onSuccess: ({ environmentId, input }, registry, result, startedProvider) => Effect.sync(() => { const { instanceId, cwd } = input; if (instanceId === undefined || cwd === undefined) return; @@ -1625,9 +1634,7 @@ export function createServerEnvironmentAtoms( current, { instanceId, cwd, fresh: input.fresh === true }, result.providers, - registry - .get(configValueAtom(environmentId)) - ?.providers.find((provider) => provider.instanceId === instanceId), + startedProvider, ), ); }), diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index b46a2823e915..144d2814b880 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -276,6 +276,11 @@ export const ServerProvider = Schema.Struct({ ), skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))), workspaceSnapshots: Schema.optionalKey(Schema.Array(ServerProviderWorkspaceSnapshot)), + /** + * Set when the server rescanned a workspace after a session start and its skills or commands + * changed. Clients holding fetched workspace snapshots for this provider fetch them again. + */ + workspaceRescannedAt: Schema.optionalKey(IsoDateTime), usageLimits: Schema.optional(ServerProviderUsageLimits), versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory), compatibilityAdvisory: Schema.optionalKey(ServerProviderCompatibilityAdvisory), diff --git a/packages/provider-core/src/server/driver.ts b/packages/provider-core/src/server/driver.ts index ac5ea46f39f1..c0474da3b55d 100644 --- a/packages/provider-core/src/server/driver.ts +++ b/packages/provider-core/src/server/driver.ts @@ -14,6 +14,7 @@ import type { import type * as Effect from "effect/Effect"; import type * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; +import type * as Stream from "effect/Stream"; import type * as ProviderAdapter from "./ProviderAdapter.ts"; import type { ProviderAuthController } from "./auth.ts"; @@ -48,6 +49,11 @@ export interface ProviderInstance { readonly snapshotForCwd?: ( cwd: string, ) => Effect.Effect; + /** + * Cwds whose workspace skills may have changed. The registry rescans only cwds already + * requested. The stream must end when the instance is torn down. + */ + readonly workspaceRescans?: Stream.Stream; readonly refreshModels?: () => Effect.Effect; readonly invalidateCaches?: Effect.Effect; /** Moves a long-lived service onto a newly updated binary before its version is read back. */ From 2becf31b640695216df4156f48239ddf35a7983c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Nov 2026 04:33:39 -0800 Subject: [PATCH 004/112] fix(server): Windows spawn workers no longer leak a short child's output pipe to a sibling (#37180) --- apps/server/src/process/SpawnWorker.test.ts | 32 ++++++++++++++++++ apps/server/src/process/SpawnWorker.ts | 36 ++++++++++++++++++--- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/apps/server/src/process/SpawnWorker.test.ts b/apps/server/src/process/SpawnWorker.test.ts index 27d31aa69c17..9c88d4f586c4 100644 --- a/apps/server/src/process/SpawnWorker.test.ts +++ b/apps/server/src/process/SpawnWorker.test.ts @@ -138,6 +138,38 @@ describe("SpawnWorker", () => { }).pipe(Effect.scoped, Effect.provide(layer)), ); + it.live("a short child's output ends while a sibling launched beside it still runs", () => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const untilStdin = + "process.stdout.write('ready');process.stdin.once('data',()=>process.exit(0))"; + // Workers that own a child stay alive, as beside a running agent, so each round's two + // launches land on two warm workers at once. + yield* Effect.all( + Array.from({ length: 4 }, () => + Effect.gen(function* () { + const holder = yield* spawner.spawn(node(untilStdin)); + expect(yield* holder.stdout.pipe(Stream.take(1), text)).toBe("ready"); + }), + ), + { concurrency: "unbounded" }, + ); + for (let round = 0; round < 20; round++) { + const [sibling, output] = yield* Effect.all( + [ + spawner.spawn(node(untilStdin, [], { stdin: { stream: Stream.never } })), + spawner + .spawn(node("process.stdout.write('ok')")) + .pipe(Effect.flatMap((child) => text(child.stdout))), + ], + { concurrency: "unbounded" }, + ); + expect(output).toBe("ok"); + expect(yield* sibling.isRunning).toBe(true); + } + }).pipe(Effect.scoped, Effect.provide(layer)), + ); + it.live("kills running commands, detached or not, and on scope interruption", () => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/apps/server/src/process/SpawnWorker.ts b/apps/server/src/process/SpawnWorker.ts index a43868b6d7b4..5a391ab18ca1 100644 --- a/apps/server/src/process/SpawnWorker.ts +++ b/apps/server/src/process/SpawnWorker.ts @@ -60,10 +60,27 @@ type FromWorker = } | { readonly type: "close"; readonly id: number }; +// Windows makes a child's stdio pipes inheritable for the length of its CreateProcess, so a child +// another worker launches meanwhile inherits them and holds the first child's output open. Every +// pool's workers take this lock around spawn(); it holds the owning worker's threadId. +const windowsSpawnLock = new Int32Array(new SharedArrayBuffer(4)); + // Inline source runs from bundles, asar archives and single-executable builds without module files. const workerSource = ` -const { parentPort } = require("node:worker_threads"); +const { parentPort, threadId, workerData } = require("node:worker_threads"); const { spawn } = require("node:child_process"); +const { lock } = workerData; +const locked = (launch) => { + if (lock === undefined) return launch(); + // Wait on the owner compareExchange saw: an unlock after it changes the value, so no wakeup is lost. + for (let owner; (owner = Atomics.compareExchange(lock, 0, 0, threadId)) !== 0; ) Atomics.wait(lock, 0, owner); + try { + return launch(); + } finally { + Atomics.store(lock, 0, 0); + Atomics.notify(lock, 0, 1); + } +}; const children = new Map(); const post = (message, transfer) => parentPort.postMessage(message, transfer); const serialize = (error) => { @@ -78,7 +95,7 @@ parentPort.on("message", (request) => { if (request.type === "spawn") { let child; try { - child = spawn(request.command, request.args, request.options); + child = locked(() => spawn(request.command, request.args, request.options)); } catch (error) { post({ type: "error", id, error: serialize(error) }); return; @@ -290,13 +307,19 @@ class SpawnWorker { readonly worker: NodeWorkerThreads.Worker; readonly children = new Map(); readonly pool: SpawnWorkerPool; + /** Node sets `worker.threadId` to -1 once the thread exits, so keep the id the lock holds. */ + readonly threadId: number; /** Launches sent but not yet answered; the worker is inside CreateProcess for one of them. */ launching = 0; closed = false; constructor(pool: SpawnWorkerPool) { this.pool = pool; - this.worker = new NodeWorkerThreads.Worker(workerSource, { eval: true }); + this.worker = new NodeWorkerThreads.Worker(workerSource, { + eval: true, + workerData: { lock: pool.platform === "win32" ? windowsSpawnLock : undefined }, + }); + this.threadId = this.worker.threadId; this.worker.on("message", (message: FromWorker) => this.onMessage(message)); this.worker.on("error", (error) => this.fail(error)); this.worker.on("exit", () => this.fail(new Error("The process launcher thread exited."))); @@ -426,7 +449,12 @@ class SpawnWorker { if (this.closed) return; this.closed = true; this.pool.workers.delete(this); - void this.worker.terminate(); + void this.worker.terminate().then(() => { + // The thread may have died holding the lock, or between its unlock and notify, or after + // a notify woke it: free the lock and wake every waiter so none sleeps on a free lock. + Atomics.compareExchange(windowsSpawnLock, 0, this.threadId, 0); + Atomics.notify(windowsSpawnLock, 0); + }); } } From be8c4c6d9fdb2f14066447b158f9706f5a76e483 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:45:39 +0100 Subject: [PATCH 005/112] fix(web): repaint terminal when programs change default colors (#37193) Co-authored-by: Julius Marminge --- apps/web/src/terminal/ghostty/core.test.ts | 37 +++++++- apps/web/src/terminal/ghostty/core.ts | 9 +- apps/web/src/terminal/ghostty/surface.ts | 6 ++ ...-program-background-repaints-screen.e2e.ts | 91 +++++++++++++++++++ 4 files changed, 141 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/terminal-program-background-repaints-screen.e2e.ts diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index b17b86b96d3c..7958475ea54e 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -248,7 +248,7 @@ describe("GhosttyTerminalCore snapshots", () => { ]); }); - it("paints ANSI colors from the theme palette and repaints them on theme change", async () => { + it("paints ANSI colors from the theme palette and repaints them when the theme or a program changes colors", async () => { const core = await createCore(); const theme = { foreground: { r: 255, g: 255, b: 255 }, @@ -266,6 +266,41 @@ describe("GhosttyTerminalCore snapshots", () => { cells = core.snapshot().rowData[0]!.cells; expect(cells[0]!.foreground).toEqual({ r: 1, g: 9, b: 2 }); expect(cells[1]!.foreground).toEqual({ r: 255, g: 0, b: 0 }); + + // Inverse, default and explicit-background cells, cached before a program sets OSC 10/11. + core.resetAndWrite("\x1b[7mI\x1b[0mD\x1b[48;2;9;8;7mB\x1b[0m\r\n"); + core.snapshot(); + const colors = () => { + const { background, rowData } = core.snapshot(); + return { + background, + cells: rowData[0]!.cells + .slice(0, 3) + .map(({ foreground, background }) => ({ foreground, background })), + }; + }; + const programForeground = { r: 17, g: 34, b: 51 }; + const programBackground = { r: 68, g: 85, b: 102 }; + const explicitBackground = { r: 9, g: 8, b: 7 }; + core.write("\x1b]10;rgb:11/22/33\x07\x1b]11;rgb:44/55/66\x07"); + expect(colors()).toEqual({ + background: programBackground, + cells: [ + { foreground: programBackground, background: programForeground }, + { foreground: programForeground, background: programBackground }, + { foreground: programForeground, background: explicitBackground }, + ], + }); + + core.write("\x1b]110\x07\x1b]111\x07"); + expect(colors()).toEqual({ + background: theme.background, + cells: [ + { foreground: theme.background, background: theme.foreground }, + { foreground: theme.foreground, background: theme.background }, + { foreground: theme.foreground, background: explicitBackground }, + ], + }); }); it("preserves Unicode and split ANSI parser state across batched renderer reads", async () => { diff --git a/apps/web/src/terminal/ghostty/core.ts b/apps/web/src/terminal/ghostty/core.ts index dae62e989d3f..119156cc5655 100644 --- a/apps/web/src/terminal/ghostty/core.ts +++ b/apps/web/src/terminal/ghostty/core.ts @@ -248,6 +248,8 @@ export class GhosttyTerminalCore { private cellQuery = 0; private scrollbar = 0; private rows: GhosttyRow[] = []; + // Defaults the cached rows resolved; Ghostty marks no row dirty when OSC 10/11 change them. + private rowColors: Pick | null = null; private disposed = false; private keyboardLayoutMap: GhosttyKeyboardLayoutMap | undefined; @@ -865,9 +867,14 @@ export class GhosttyTerminalCore { ); const cols = this.getU16(RENDER_DATA.cols); const rowCount = this.getU16(RENDER_DATA.rows); - const dirty = this.getU32(RENDER_DATA.dirty); const foreground = this.getColor(RENDER_DATA.foreground, { r: 229, g: 231, b: 235 }); const background = this.getColor(RENDER_DATA.background, { r: 0, g: 0, b: 0 }); + const colorsChanged = + this.rowColors !== null && + (!sameColor(this.rowColors.foreground, foreground) || + !sameColor(this.rowColors.background, background)); + this.rowColors = { foreground, background }; + const dirty = colorsChanged ? 2 : this.getU32(RENDER_DATA.dirty); const cursorHasValue = this.getBool(RENDER_DATA.cursorHasValue); const cursor = cursorHasValue ? this.getColor(RENDER_DATA.cursor, foreground) : foreground; const cursorInViewport = this.getBool(RENDER_DATA.cursorInViewport); diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts index 537f7bb524e5..6e86cf9ee3ec 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -5,6 +5,7 @@ import { collectWrappedTerminalLinkLine, extractTerminalLinks } from "../../term import { GHOSTTY_CELL_WIDE, GhosttyTerminalCore, + ghosttyColorsEqual, type GhosttyCell, type GhosttyScrollbar, type GhosttySnapshot, @@ -2043,7 +2044,12 @@ export class GhosttyTerminalSurface { this.canvasConfigured = true; this.canvasDevicePixelRatio = canvasConfiguration.ratio; } + const previousBackground = this.snapshot?.background; this.snapshot = this.core.snapshot(); + // Only a full render repaints the padding around the rows in the new default background. + if (previousBackground && !ghosttyColorsEqual(previousBackground, this.snapshot.background)) { + this.forceFullRender = true; + } if (!this.blinkEnabled()) this.cursorOn = true; // Move the origin only on full repaint; dirty-row updates cannot mix origins. const scrollState = this.readScrollbarState(); diff --git a/scripts/scenarios/terminal-program-background-repaints-screen.e2e.ts b/scripts/scenarios/terminal-program-background-repaints-screen.e2e.ts new file mode 100644 index 000000000000..b847073711ee --- /dev/null +++ b/scripts/scenarios/terminal-program-background-repaints-screen.e2e.ts @@ -0,0 +1,91 @@ +/// +// The DOM lib types the function this scenario runs in the page. +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { runPromise, test, WEB } from "./t3.ts"; + +// A raw-mode process prints rows, then on `b` sets the default background with OSC 11. +const PROGRAM = String.raw`import { writeFileSync } from "node:fs"; + +const state = new URL("state", import.meta.url); +process.stdin.setRawMode(true); +process.stdout.write("\x1b[2J\x1b[HROW ONE\r\nROW TWO\r\nROW THREE\r\nROW FOUR\r\n"); +writeFileSync(state, "ready"); +process.stdin.on("data", (chunk) => { + const key = chunk.toString(); + if (key === "b") { + process.stdout.write("\x1b]11;rgb:44/55/66\x07", () => writeFileSync(state, "changed")); + } + if (key === "x") { + process.stdin.setRawMode(false); + process.exit(0); + } +}); +`; + +test( + "A program setting the terminal's default background repaints the whole screen", + WEB, + async ({ t3, app, browser, screen }) => { + await browser.emulateMedia({ colorScheme: "dark" }); + const project = await t3.project("colors", { "program.mjs": PROGRAM }); + const thread = await t3.thread({ project, title: "Colors", messages: ["hello"] }); + const read = (file: string) => + runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readFileString(`${project}/${file}`); + }).pipe(Effect.orElseSucceed(() => "")), + ); + await t3.open(thread); + await screen.getByRole("button", "Toggle terminal drawer").tap(); + const terminal = screen.getByLabel("Terminal input"); + + // Input sent before the shell runs is dropped, so retype until it lands. + await expect + .poll( + async () => { + await terminal.focus(); + await browser.keyboard.type(`echo ready > '${project}/shell-ready'`); + await browser.keyboard.press("Enter"); + return read("shell-ready"); + }, + { timeout: 30_000 }, + ) + .toBe("ready\n"); + + await terminal.focus(); + await browser.keyboard.type(`'${process.execPath}' '${project}/program.mjs'`); + await browser.keyboard.press("Enter"); + await expect.poll(() => read("state"), { timeout: 15_000 }).toBe("ready"); + await app.screenshot("before-background"); + + await terminal.focus(); + await browser.keyboard.type("b"); + await expect.poll(() => read("state"), { timeout: 15_000 }).toBe("changed"); + await app.screenshot("after-background"); + + // Sample the padding above the rows, a cell beside the printed rows, and the canvas bottom. + const pixels = await browser.evaluate(() => { + const canvas = document + .querySelector('[aria-label="Terminal input"]')! + .parentElement!.querySelector("canvas")!; + const context = canvas.getContext("2d")!; + const at = (x: number, y: number) => [...context.getImageData(x, y, 1, 1).data]; + return { + padding: at(canvas.width - 2, 1), + row: at(canvas.width - 20, Math.floor(canvas.height / 2)), + bottom: at(canvas.width - 2, canvas.height - 1), + }; + }); + await browser.keyboard.type("x"); + const programBackground = [68, 85, 102, 255]; + expect(pixels).toEqual({ + padding: programBackground, + row: programBackground, + bottom: programBackground, + }); + }, +); From cb251b9abc1403aa02e21e400d0b7f396a195e3c Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:47:53 +0100 Subject: [PATCH 006/112] fix(web): composer suggestions stay reachable in short windows (#37179) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- apps/web/src/components/chat/ChatComposer.tsx | 2 +- .../chat/ComposerCommandMenuLayer.tsx | 17 ++- apps/web/src/components/ui/autocomplete.tsx | 3 +- scripts/scenarios/composer-menu.ts | 105 ++++++++++++++++++ ...ow-file-suggestions-reach-last-file.e2e.ts | 29 +++++ ...w-file-suggestions-reach-first-file.e2e.ts | 32 ++++++ 6 files changed, 181 insertions(+), 7 deletions(-) create mode 100644 scripts/scenarios/composer-menu.ts create mode 100644 scripts/scenarios/short-window-file-suggestions-reach-last-file.e2e.ts create mode 100644 scripts/scenarios/shrunk-window-file-suggestions-reach-first-file.e2e.ts diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index dd0fe8461ff2..2499ddf7c227 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -3517,7 +3517,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) )} > {isStashMenuOpen && !composerMenuOpen && ( - + (null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- positions the menu from the composer's DOM rect, tracking window resize, scroll and ancestor resizes useLayoutEffect(() => { - const anchor = props.anchor; if (!anchor) return; const updatePosition = () => { @@ -47,10 +49,15 @@ export function ComposerCommandMenuLayer(props: { return; } const composerOverlap = rootFontSizePx + 1; + const spaceAbove = rect.top + composerOverlap; + const bottom = window.innerHeight - spaceAbove; + const floorHeight = Math.max(96, spaceAbove - 24); + const maxHeight = canOverflowTop ? floorHeight : Math.min(floorHeight, window.innerHeight); const next = { - bottom: window.innerHeight - rect.top - composerOverlap, + // With too little room above, the menu slides down over the composer instead of past the window top. + bottom: canOverflowTop ? bottom : Math.min(bottom, window.innerHeight - maxHeight), left: rect.left + drawerInset, - maxHeight: Math.max(96, rect.top - 24 + composerOverlap), + maxHeight, width, }; setPosition((current) => @@ -73,9 +80,9 @@ export function ComposerCommandMenuLayer(props: { window.removeEventListener("resize", updatePosition); window.removeEventListener("scroll", updatePosition, true); }; - }, [props.anchor]); + }, [anchor, canOverflowTop]); - if (!props.anchor || !position) return null; + if (!anchor || !position) return null; return createPortal(
+ // A flex column lets the viewport shrink with a height-capped parent instead of overflowing it. + +// Helpers for composer suggestion scenarios in short windows; the DOM lib types their page code. +import type { Browser } from "@e2e-dev/web"; +import { expect, type Screen } from "e2e"; + +import type { T3 } from "./t3.ts"; + +const FILE_NAMES = Array.from( + { length: 40 }, + (_, index) => `entry-${String(index + 1).padStart(2, "0")}.ts`, +); + +/** Seeds a project with enough files to overflow the menu and opens a thread in it. */ +export async function openThreadWithManyFiles(t3: T3) { + const files = Object.fromEntries(FILE_NAMES.map((name) => [`src/${name}`, `export {};\n`])); + const project = await t3.project("demo", files); + const thread = await t3.thread({ project, title: "Short window", messages: ["hello"] }); + await t3.open(thread); +} + +/** Types a fourteen-line draft, then opens the `@` file suggestions at its end. */ +export async function openFileSuggestionsUnderTallDraft(browser: Browser, screen: Screen) { + // A phone-width window collapses the composer until it is tapped. + await screen.getByRole("button", "Expand composer").tap(); + await screen.getByRole("textbox").tap(); + for (let line = 1; line <= 14; line += 1) { + await browser.keyboard.type(`line ${line}`); + if (line < 14) await browser.keyboard.press("Shift+Enter"); + } + await browser.keyboard.press("Control+End"); + await browser.keyboard.type(" @"); + await expect + .poll(() => + browser.evaluate( + () => document.querySelectorAll('[data-composer-command-drawer] [role="option"]').length, + ), + ) + .toBeGreaterThan(FILE_NAMES.length); +} + +/** Wheels the suggestions from a point inside the visible drawer until they reach that end. */ +export async function wheelSuggestions(browser: Browser, direction: "up" | "down") { + const point = await browser.evaluate(() => { + const layer = document.querySelector('[data-composer-drawer-layer="true"]'); + if (!layer) return null; + const rect = layer.getBoundingClientRect(); + const top = Math.max(rect.top, 0); + const bottom = Math.min(rect.bottom, window.innerHeight); + return { x: rect.left + rect.width / 2, y: top + (bottom - top) / 3 }; + }); + expect(point).not.toBeNull(); + await browser.mouse.move(point!.x, point!.y); + // Wheel scrolling lands a frame or more later, so keep wheeling until the list is at its end. + await expect + .poll(async () => { + await browser.mouse.wheel(0, direction === "down" ? 4000 : -4000); + return browser.evaluate((direction) => { + const viewport = document.querySelector( + '[data-composer-command-drawer] [data-slot="scroll-area-viewport"]', + ); + if (!viewport) return false; + return direction === "down" + ? viewport.scrollTop >= viewport.scrollHeight - viewport.clientHeight - 1 + : viewport.scrollTop <= 0; + }, direction); + }) + .toBe(true); +} + +/** + * The first suggestion or last file row, and its center when the whole row is visible + * and a click there lands on it, otherwise `null`. + */ +export const findHittableRow = (browser: Browser, which: "first" | "last-file") => + browser.evaluate( + ({ which, names }) => { + const options = [ + ...document.querySelectorAll('[data-composer-command-drawer] [role="option"]'), + ]; + const row = + which === "first" + ? options[0] + : options.findLast((option) => + names.some((name) => option.textContent?.startsWith(name)), + ); + if (!row) return { label: null, point: null }; + const text = row.textContent ?? ""; + const label = names.find((name) => text.startsWith(name)) ?? text; + const rect = row.getBoundingClientRect(); + const viewport = row.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect(); + const top = Math.max(0, viewport?.top ?? 0); + const bottom = Math.min(window.innerHeight, viewport?.bottom ?? window.innerHeight); + if (rect.top < top - 1 || rect.bottom > bottom + 1) return { label, point: null }; + const point = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; + const hit = document.elementFromPoint(point.x, point.y)?.closest('[role="option"]') === row; + return { label, point: hit ? point : null }; + }, + { which, names: [...FILE_NAMES, "README.md"] }, + ); + +export async function clickAt(browser: Browser, point: { readonly x: number; readonly y: number }) { + await browser.mouse.move(point.x, point.y); + await browser.mouse.down(); + await browser.mouse.up(); +} diff --git a/scripts/scenarios/short-window-file-suggestions-reach-last-file.e2e.ts b/scripts/scenarios/short-window-file-suggestions-reach-last-file.e2e.ts new file mode 100644 index 000000000000..01b5ed306c79 --- /dev/null +++ b/scripts/scenarios/short-window-file-suggestions-reach-last-file.e2e.ts @@ -0,0 +1,29 @@ +import { expect } from "e2e"; + +import { + clickAt, + findHittableRow, + openFileSuggestionsUnderTallDraft, + openThreadWithManyFiles, + wheelSuggestions, +} from "./composer-menu.ts"; +import { test, WEB } from "./t3.ts"; + +test( + "In a short window, file suggestions wheel down to a last file the pointer can pick", + WEB, + async ({ t3, app, browser, screen }) => { + await browser.setViewport({ width: 375, height: 500 }); + await openThreadWithManyFiles(t3); + await openFileSuggestionsUnderTallDraft(browser, screen); + + await wheelSuggestions(browser, "down"); + await app.screenshot("scrolled-to-bottom"); + const last = await findHittableRow(browser, "last-file"); + expect(last.label).toBe("README.md"); + expect(last.point).not.toBeNull(); + + await clickAt(browser, last.point!); + await expect(screen.getByRole("textbox")).toContainText("README.md"); + }, +); diff --git a/scripts/scenarios/shrunk-window-file-suggestions-reach-first-file.e2e.ts b/scripts/scenarios/shrunk-window-file-suggestions-reach-first-file.e2e.ts new file mode 100644 index 000000000000..cf3087b2e122 --- /dev/null +++ b/scripts/scenarios/shrunk-window-file-suggestions-reach-first-file.e2e.ts @@ -0,0 +1,32 @@ +import { expect } from "e2e"; + +import { + clickAt, + findHittableRow, + openFileSuggestionsUnderTallDraft, + openThreadWithManyFiles, + wheelSuggestions, +} from "./composer-menu.ts"; +import { test, WEB } from "./t3.ts"; + +test( + "After the window shrinks, file suggestions wheel up to a first suggestion the pointer can pick", + WEB, + async ({ t3, app, browser, screen }) => { + await browser.setViewport({ width: 375, height: 500 }); + await openThreadWithManyFiles(t3); + await openFileSuggestionsUnderTallDraft(browser, screen); + await browser.keyboard.press("Escape"); + await browser.keyboard.press("Backspace"); + await browser.keyboard.type("@"); + + await browser.setViewport({ width: 375, height: 300 }); + await wheelSuggestions(browser, "up"); + await app.screenshot("scrolled-to-top"); + const first = await findHittableRow(browser, "first"); + expect(first.point).not.toBeNull(); + + await clickAt(browser, first.point!); + await expect(screen.getByRole("textbox")).toContainText(first.label!); + }, +); From 6071022cb71b92c761bc06aabff6865243fa956c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Nov 2026 04:52:35 -0800 Subject: [PATCH 007/112] fix(server): Claude session name follows thread renames without waiting for the next turn (#37185) --- .../Adapters/ClaudeAdapterV2.ts | 55 ++++--- ...laudeAutomaticDelivery.integration.test.ts | 147 ++++++++++++++++++ .../src/orchestration-v2/EffectOutbox.ts | 5 + .../src/orchestration-v2/EffectWorker.test.ts | 1 + .../src/orchestration-v2/EffectWorker.ts | 13 ++ .../src/orchestration-v2/Orchestrator.ts | 17 ++ .../ProviderRuntimeRecoveryService.test.ts | 1 + .../ProviderTurnControlService.ts | 22 +++ .../src/server/ProviderAdapter.ts | 5 + 9 files changed, 248 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index e8cfd9d8ce08..bced035fed01 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -6390,6 +6390,28 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); }); + // `claude --resume` shows the native title. A failed or timed-out rename forgets the + // applied title so the next turn, even after a restart, sends it again. + const applySessionTitle = Effect.fn("ClaudeAdapterV2.applySessionTitle")(function* ( + query: ClaudeAgentSdkQuerySession, + nativeThreadId: string, + title: string, + ) { + if (appliedSessionTitles.get(nativeThreadId) === title) return; + const renamed = yield* query + .renameSession(title) + .pipe(Effect.timeout("10 seconds"), Effect.isSuccess); + if (renamed) { + appliedSessionTitles.set(nativeThreadId, title); + } else { + appliedSessionTitles.delete(nativeThreadId); + } + const remembered = (yield* Ref.get(lastProviderThreadByNativeThread)).get(nativeThreadId); + if (remembered !== undefined) { + yield* rememberProviderThread(remembered); + } + }); + const rosterForNativeThread = ( all: ReadonlyMap>, nativeThreadId: string, @@ -13029,24 +13051,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.provideService(Path.Path, path), ); const querySession = yield* openQuery(turnInput, nativeThreadId, queryPolicy); - // `claude --resume` shows the native title. A failed or timed-out rename forgets the - // applied title so the next turn, even after a restart, sends it again. - if (appliedSessionTitles.get(nativeThreadId) !== turnInput.appThread.title) { - const renamed = yield* querySession.query - .renameSession(turnInput.appThread.title) - .pipe(Effect.timeout("10 seconds"), Effect.isSuccess); - if (renamed) { - appliedSessionTitles.set(nativeThreadId, turnInput.appThread.title); - } else { - appliedSessionTitles.delete(nativeThreadId); - } - const remembered = (yield* Ref.get(lastProviderThreadByNativeThread)).get( - nativeThreadId, - ); - if (remembered !== undefined) { - yield* rememberProviderThread(remembered); - } - } + yield* applySessionTitle(querySession.query, nativeThreadId, turnInput.appThread.title); const autoCompactWindow = yield* resolveAutoCompactWindow( querySession.settingsCwd, turnInput.modelSelection, @@ -14029,6 +14034,20 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), ); }), + applyThreadTitle: Effect.fn("ClaudeAdapterV2.applyThreadTitle")(function* ({ + providerThread, + title, + }) { + const live = yield* Ref.get(queryContext); + if ( + live === null || + live.stopping || + live.nativeThreadId !== providerThread.nativeThreadRef?.nativeId + ) { + return; + } + yield* applySessionTitle(live.query, live.nativeThreadId, title); + }), stopTask: Effect.fn("ClaudeAdapterV2.stopTask")(function* ({ providerThread, taskId }) { const liveQuery = yield* Ref.get(queryContext); const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId); diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 0fead24d9779..1fa7047aff42 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -607,6 +607,153 @@ it.effect("applies an effort change to the running Claude query without waiting ), ); +const renamedClaudeSessionTitles = (options: { readonly renameDuringStartup: boolean }) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("claude-live-rename"); + const sdkMessages = yield* Queue.unbounded(); + const renames: string[] = []; + const startupEntered = yield* Deferred.make(); + const startupReleased = yield* Deferred.make(); + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: modelSelection.instanceId, + settings, + environment: {}, + attachmentsDir: cwd, + fileSystem: yield* FileSystem.FileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator: yield* IdAllocator.IdAllocatorV2, + queryRunner: { + allocateSessionId: Effect.succeed(sessionId), + open: () => + Effect.succeed({ + messages: Stream.fromQueue(sdkMessages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + renameSession: (title) => + Effect.sync(() => { + renames.push(title); + }), + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.die("a rename must not interrupt the turn"), + close: Effect.void, + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + return yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make("thread:live-rename"); + const running = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:live-rename"), + title: "Seed title", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("first"), + threadId, + messageId: MessageId.make("first"), + text: "Keep working.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const rename = orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("rename"), + threadId, + title: "Renamed title", + }); + if (options.renameDuringStartup) { + const starting = yield* worker.drain().pipe(Effect.forkScoped); + yield* Deferred.await(startupEntered); + yield* rename; + yield* Deferred.succeed(startupReleased, undefined); + yield* Fiber.join(starting); + yield* Fiber.join(running); + } else { + yield* worker.drain(); + yield* Fiber.join(running); + assert.deepEqual(renames, []); + yield* rename; + } + yield* worker.drain(); + return renames; + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "claude-live-rename" }, + ProviderAdapterRegistry.layerSingle({ + ...adapter, + openSession: (input) => + options.renameDuringStartup + ? Deferred.succeed(startupEntered, undefined).pipe( + Effect.andThen(Deferred.await(startupReleased)), + Effect.andThen(adapter.openSession(input)), + ) + : adapter.openSession(input), + }), + { runEffectWorker: false }, + ), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ); + +it.effect("renames the running Claude session when the thread is renamed mid-turn", () => + Effect.gen(function* () { + assert.deepEqual(yield* renamedClaudeSessionTitles({ renameDuringStartup: false }), [ + "Renamed title", + ]); + }), +); + +it.effect("renames the Claude session when the thread is renamed while it starts", () => + Effect.gen(function* () { + assert.deepEqual(yield* renamedClaudeSessionTitles({ renameDuringStartup: true }), [ + "Renamed title", + ]); + }), +); + const backgroundTaskStarted = (taskId: string) => frame({ type: "system", diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 66ae3d65d248..69fd60684bbc 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -50,6 +50,10 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ providerThreadId: ProviderThreadId, modelSelection: ModelSelection, }), + Schema.Struct({ + type: Schema.Literal("provider-session.apply-thread-title"), + title: Schema.String, + }), Schema.Struct({ type: Schema.Literal("provider-turn.start"), runId: RunId, @@ -150,6 +154,7 @@ export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [ export const PROCESS_BOUND_EFFECT_TYPES = [ "provider-session.apply-model-selection", + "provider-session.apply-thread-title", "provider-turn.start", "provider-turn.interrupt", "provider-turn.steer", diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 94444eb8e5c6..428d7d47066a 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -102,6 +102,7 @@ function layerExecutorFor(input: { interrupt: input.interrupt ?? (() => Effect.void), steer: () => Effect.void, applyModelSelection: () => Effect.void, + applyThreadTitle: () => Effect.void, interruptAndAwaitTerminal: (request) => record( request.replacementProviderSessionId === undefined diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 41b2d234f26b..c6aa09efd5e6 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -222,6 +222,19 @@ export const layerExecutor: Layer.Layer< }), ), ); + case "provider-session.apply-thread-title": + return providerTurnControl + .applyThreadTitle({ threadId: effect.threadId, title: effect.request.title }) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); case "provider-turn.start": return startRun(effect, effect.request.runId, willRetry).pipe( Effect.mapError( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 53f726bf4628..5257330e2cb5 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -5312,6 +5312,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } } + // Queued even while no session is live: it runs after any in-flight turn start publishes one. + if ( + (command.type === "thread.metadata.update" || + command.type === "thread.title.regeneration.complete") && + updatedThread.title !== thread.title + ) { + yield* Ref.update(effects, (existing) => [ + ...existing, + { + id: `effect:${command.commandId}:provider-session.apply-thread-title`, + commandId: command.commandId, + threadId: command.threadId, + request: { type: "provider-session.apply-thread-title", title: updatedThread.title }, + } satisfies PendingOrchestrationEffectV2, + ]); + } + if (command.type === "thread.metadata.update" && command.regenerateTitle === true) { yield* Ref.update(effects, (existing) => [ ...existing, diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts index f08a3a038be6..0a1e71f78d09 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts @@ -901,6 +901,7 @@ it.effect( assert.equal(summary.retiredEffects, 2); assert.deepEqual(committedInput?.cancelUnsettledEffects?.effectTypes, [ "provider-session.apply-model-selection", + "provider-session.apply-thread-title", "provider-turn.start", "provider-turn.interrupt", "provider-turn.steer", diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts index 5de7f965474b..f9727734bf87 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.ts @@ -84,6 +84,16 @@ export interface ProviderTurnControlServiceV2Shape { | ProviderSessionManager.ProviderSessionManagerV2Error | ProviderAdapter.ProviderAdapterV2Error >; + /** Best effort: a provider thread that is no longer live picks the title up when its next turn starts. */ + readonly applyThreadTitle: (input: { + readonly threadId: ThreadId; + readonly title: string; + }) => Effect.Effect< + void, + | ProjectionStore.ProjectionStoreV2Error + | ProviderSessionManager.ProviderSessionManagerV2Error + | ProviderAdapter.ProviderAdapterV2Error + >; readonly interruptAndAwaitTerminal: (input: { readonly threadId: ThreadId; readonly providerSessionId: ProviderSessionId; @@ -249,6 +259,18 @@ export const layer: Layer.Layer< }); }, ), + applyThreadTitle: Effect.fn("ProviderTurnControlService.applyThreadTitle")(function* (input) { + const { thread, providerThreads } = yield* projections.getThreadRecords(input.threadId, [ + "providerThreads", + ]); + const providerThread = providerThreads.find( + (candidate) => candidate.id === thread.activeProviderThreadId, + ); + if (!providerThread?.providerSessionId) return; + const session = yield* sessions.get(providerThread.providerSessionId); + if (Option.isNone(session) || session.value.applyThreadTitle === undefined) return; + yield* session.value.applyThreadTitle({ providerThread, title: input.title }); + }), interrupt: Effect.fn("ProviderTurnControlService.interrupt")( function* (input) { const loaded = yield* load({ ...input, operation: "interrupt" }); diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 58f177397406..80d3ef8a5285 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -750,6 +750,11 @@ export interface ProviderAdapterV2SessionRuntime { readonly providerThread: OrchestrationV2ProviderThread; readonly modelSelection: ModelSelection; }) => Effect.Effect; + /** Renames the provider's native session while its process is running; otherwise the next turn does. */ + readonly applyThreadTitle?: (input: { + readonly providerThread: OrchestrationV2ProviderThread; + readonly title: string; + }) => Effect.Effect; readonly stopTask?: (input: { readonly providerThread: OrchestrationV2ProviderThread; readonly taskId: string; From 6d3f6423a341b315a091567aee5ab34a3b8b0373 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 15 Nov 2026 13:52:47 +0100 Subject: [PATCH 008/112] fix(web): Enter sends when a panel-conditioned shortcut is inactive (#37198) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 1 + apps/web/src/components/chat/ChatComposer.tsx | 6 +- .../src/components/chat/composerCommandKey.ts | 3 + apps/web/src/composer-logic.test.ts | 14 +++++ apps/web/src/composer-logic.ts | 9 ++- ...panel-conditioned-enter-still-sends.e2e.ts | 59 +++++++++++++++++++ 6 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/panel-conditioned-enter-still-sends.e2e.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 34d3f7244a49..67638fc4e63c 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3726,6 +3726,7 @@ export default function ChatView(props: ChatViewProps) { resolvedTheme={resolvedTheme} settings={settings} keybindings={keybindings} + getShortcutContext={getShortcutContextStable} terminalOpen={Boolean(terminalUiState.terminalOpen)} gitCwd={gitCwd} pullRequestProjectId={ diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2499ddf7c227..ff14154dccb8 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -142,7 +142,7 @@ import { useDictationSubmissionShortcut } from "../../speech/useDictationSubmiss import { useEnvironmentSpeechInput } from "../../speech/useEnvironmentSpeechInput"; import { ComposerSpeechButton, ComposerSpeechRecordingPill } from "./ComposerSpeechButton"; import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; -import { shortcutLabelForCommand } from "../../keybindings"; +import { shortcutLabelForCommand, type ShortcutMatchContext } from "../../keybindings"; import { type TerminalContextDraft, type TerminalContextSelection, @@ -420,6 +420,7 @@ export interface ChatComposerProps { resolvedTheme: "light" | "dark"; settings: UnifiedSettings; keybindings: ResolvedKeybindingsConfig; + getShortcutContext: (eventTarget: EventTarget | null) => ShortcutMatchContext; terminalOpen: boolean; gitCwd: string | null; pullRequestProjectId: ProjectId | null; @@ -533,6 +534,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) resolvedTheme, settings, keybindings, + getShortcutContext, terminalOpen, gitCwd, pullRequestProjectId, @@ -2199,6 +2201,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const intent = composerSubmissionIntentForKey({ event, keybindings, + context: getShortcutContext(event.target), isSoftwareKeyboardOpen, isDraftThread: routeKind === "draft", isRunning: phase === "running" || phase === "connecting", @@ -2318,6 +2321,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => composerCommandKeyHandler({ keybindings, + getShortcutContext, sendShortcut: settings.sendShortcut, routeKind, phase, diff --git a/apps/web/src/components/chat/composerCommandKey.ts b/apps/web/src/components/chat/composerCommandKey.ts index 243b69d09e4d..549c3ee12f65 100644 --- a/apps/web/src/components/chat/composerCommandKey.ts +++ b/apps/web/src/components/chat/composerCommandKey.ts @@ -40,6 +40,7 @@ import type { Dispatch, RefObject, SetStateAction } from "react"; */ export function composerCommandKeyHandler(input: { readonly keybindings: ChatComposerProps["keybindings"]; + readonly getShortcutContext: ChatComposerProps["getShortcutContext"]; readonly sendShortcut: ChatComposerProps["settings"]["sendShortcut"]; readonly routeKind: ChatComposerProps["routeKind"]; readonly phase: ChatComposerProps["phase"]; @@ -101,6 +102,7 @@ export function composerCommandKeyHandler(input: { }) { const { keybindings, + getShortcutContext, sendShortcut, routeKind, phase, @@ -223,6 +225,7 @@ export function composerCommandKeyHandler(input: { const submissionIntent = composerSubmissionIntentForKey({ event, keybindings, + context: getShortcutContext(event.target), isSoftwareKeyboardOpen, isDraftThread: routeKind === "draft", isRunning: phase === "running" || phase === "connecting", diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts index e7ec86822a54..8a714a4c572d 100644 --- a/apps/web/src/composer-logic.test.ts +++ b/apps/web/src/composer-logic.test.ts @@ -98,6 +98,7 @@ describe("formatAssistantCitationForComposer", () => { describe("composerSubmissionIntentForKey", () => { const input = { keybindings: DEFAULT_RESOLVED_KEYBINDINGS, + context: {}, platform: "Linux", isSoftwareKeyboardOpen: false, isDraftThread: false, @@ -244,6 +245,19 @@ describe("composerSubmissionIntentForKey", () => { }, ); + it("sends on Enter when a binding conditioned on !rightPanelOpen is inactive", () => { + const keybindings = mergeWithDefaultKeybindings( + compileResolvedKeybindingsConfig([ + { key: "enter", command: "commandPalette.toggle", when: "!rightPanelOpen" }, + ]), + ); + const conditioned = { ...input, keybindings, sendShortcut: "enter" as const, event: enter }; + expect(composerSubmissionIntentForKey(conditioned)).toBeNull(); + expect( + composerSubmissionIntentForKey({ ...conditioned, context: { rightPanelOpen: true } }), + ).toBe("foreground"); + }); + it.each([ { isSoftwareKeyboardOpen: true }, { event: { ...enter, isComposing: true } }, diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.ts index 37fef411897f..ca266c77e0d4 100644 --- a/apps/web/src/composer-logic.ts +++ b/apps/web/src/composer-logic.ts @@ -15,7 +15,11 @@ import { type ComposerPromptSegment, } from "./composer-editor-mentions"; -import { resolveShortcutCommand, type ShortcutEventLike } from "./keybindings"; +import { + resolveShortcutCommand, + type ShortcutEventLike, + type ShortcutMatchContext, +} from "./keybindings"; export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill"; export type ComposerSlashCommand = "model" | "side" | "btw" | "clear"; @@ -59,6 +63,8 @@ export function composerRequiresModifier( export function composerSubmissionIntentForKey(input: { event: ShortcutEventLike & { isComposing?: boolean; keyCode?: number; repeat?: boolean }; keybindings: ResolvedKeybindingsConfig; + /** The when-clause context ChatView's shortcut listeners see, so both resolve Enter alike. */ + context: Partial; platform?: string; isSoftwareKeyboardOpen: boolean; isDraftThread: boolean; @@ -73,6 +79,7 @@ export function composerSubmissionIntentForKey(input: { const command = resolveShortcutCommand(event, input.keybindings, { ...(input.platform === undefined ? {} : { platform: input.platform }), context: { + ...input.context, composerFocus: true, draftThreadRoute: input.isDraftThread, turnRunning: input.isRunning === true, diff --git a/scripts/scenarios/panel-conditioned-enter-still-sends.e2e.ts b/scripts/scenarios/panel-conditioned-enter-still-sends.e2e.ts new file mode 100644 index 000000000000..f837946e7565 --- /dev/null +++ b/scripts/scenarios/panel-conditioned-enter-still-sends.e2e.ts @@ -0,0 +1,59 @@ +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +// A saved rule that binds Enter to the command palette only while the right panel is closed. +const panelConditionedEnter = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const keybindingsPath = (yield* Path.Path).join(T3_HOME, "userdata/keybindings.json"); + const original = (yield* fs.exists(keybindingsPath)) + ? yield* fs.readFileString(keybindingsPath) + : null; + return { + save: fs.writeFileString( + keybindingsPath, + '[{ "key": "enter", "command": "commandPalette.toggle", "when": "!rightPanelOpen" }]\n', + ), + restore: + original === null + ? fs.remove(keybindingsPath, { force: true }) + : fs.writeFileString(keybindingsPath, original), + }; +}); + +test( + "Enter sends from the composer while the right panel is open and a rule binds it when closed", + WEB, + async ({ t3, app, screen }) => { + const keybindings = await runPromise(panelConditionedEnter); + try { + await runPromise(keybindings.save); + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Panel work", messages: ["Start"] }); + + // The settings list shows the rule once the server has loaded the saved file. + await t3.open("/settings/keybindings"); + await screen + .getByRole("button", "Edit shortcut for Command Palette: Toggle: Enter") + .waitFor(); + + await t3.open(thread); + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", { name: "Toggle right panel", pressed: true }).waitFor(); + + const composer = screen.getByTestId("composer-editor"); + await composer.tap(); + await composer.pressSequentially("Hello with the panel open"); + await composer.press("Enter"); + await app.screenshot("after-enter"); + await expect(composer).toHaveText(""); + await expect(screen.getByText("Hello with the panel open")).toBeVisible(); + } finally { + await runPromise(keybindings.restore); + } + }, +); From 7e69e880b630ceb372e22a41987543d997771269 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Nov 2026 05:00:17 -0800 Subject: [PATCH 009/112] fix(server): project search starts working once a slow content index finishes building (#37138) --- .../workspace/WorkspaceSearchIndex.test.ts | 177 ++++++++++ .../src/workspace/WorkspaceSearchIndex.ts | 304 ++++++++++++++++-- 2 files changed, 451 insertions(+), 30 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 6c4e873f12b4..13ccf443fb10 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -12,6 +12,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { PROJECT_FAVICON_EXTENSIONS, isProjectFaviconPath } from "@t3tools/shared/projectFavicon"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import { ChildProcessSpawner } from "effect/process"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -294,6 +295,182 @@ it.effect("continues whole-word searches after a filtered grep page", () => ).pipe(Effect.provide(testLayer)), ); +it.live("answers content searches with git grep while a slow content index builds", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const vcsProcess = yield* VcsProcess.VcsProcess; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-content-warmup-" }); + yield* vcsProcess.run({ operation: "test.gitInit", command: "git", args: ["init"], cwd }); + yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), "ignored.txt\n"); + yield* fileSystem.makeDirectory(path.join(cwd, "src")); + yield* fileSystem.writeFileString( + path.join(cwd, "src/a.ts"), + "const Needle = 1;\r\nneedles(a.b);\nnone\n", + ); + yield* fileSystem.writeFileString(path.join(cwd, "ignored.txt"), "needle\n"); + // fff leaves out what `.ignore` excludes, so git results must leave it out too. + yield* fileSystem.writeFileString(path.join(cwd, ".ignore"), "out/\n"); + yield* fileSystem.makeDirectory(path.join(cwd, "out/deep"), { recursive: true }); + yield* fileSystem.writeFileString(path.join(cwd, "out/deep/g.txt"), "needle\n"); + + let isWarmupComplete = false; + const grep = vi.fn(async () => ({ + ok: true as const, + value: { + items: [], + totalMatched: 0, + totalFilesSearched: 0, + totalFiles: 0, + filteredFileCount: 0, + nextCursor: null, + } satisfies GrepResult, + })); + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })), + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false, isWarmupComplete }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + grepAsync: grep, + } as unknown as FileFinder; + const noPcreFinder = { + ...finder, + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + } as unknown as FileFinder; + vi.spyOn(FileFinder, "create") + .mockReturnValueOnce({ ok: true, value: finder }) + .mockReturnValueOnce({ ok: true, value: noPcreFinder }) + .mockReturnValueOnce({ ok: true, value: noPcreFinder }) + .mockReturnValueOnce({ ok: true, value: noPcreFinder }); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd, "content"); + const search = (input: Partial[0]>) => + searchIndex.searchContents({ + query: "needle", + limit: 10, + caseSensitive: false, + wholeWord: false, + useRegex: false, + ...input, + }); + + expect(yield* search({})).toEqual({ + matches: [ + { + path: "src/a.ts", + lineNumber: 1, + lineContent: "const Needle = 1;", + matchRanges: [{ start: 6, end: 12 }], + }, + { + path: "src/a.ts", + lineNumber: 2, + lineContent: "needles(a.b);", + matchRanges: [{ start: 0, end: 6 }], + }, + ], + truncated: false, + }); + expect((yield* search({ caseSensitive: true, wholeWord: true })).matches).toEqual([]); + expect((yield* search({ query: "a.b" })).matches.map((match) => match.matchRanges)).toEqual([ + [{ start: 8, end: 11 }], + ]); + expect( + (yield* search({ query: "ne+dles?", useRegex: true })).matches.map( + (match) => match.matchRanges, + ), + ).toEqual([[{ start: 6, end: 12 }], [{ start: 0, end: 7 }]]); + expect( + (yield* search({ query: "[a-z]e", useRegex: true })).matches.map( + (match) => match.matchRanges, + ), + ).toEqual([ + [{ start: 4, end: 6 }], + [ + { start: 6, end: 8 }, + { start: 10, end: 12 }, + ], + [ + { start: 0, end: 2 }, + { start: 4, end: 6 }, + ], + [{ start: 2, end: 4 }], + ]); + const invalid = yield* search({ query: "a.b(", useRegex: true }); + expect(invalid.matches).toEqual([]); + expect(invalid.regexFallbackError).toBeDefined(); + expect(yield* search({ limit: 1 })).toMatchObject({ truncated: true }); + expect(grep).not.toHaveBeenCalled(); + + // When git cannot give regex results or their ranges, fff answers once ready instead. + const failingGitIndex = ( + failingArgument: string, + stderr: string, + output: { readonly exitCode: number; readonly stdout: string } = { + exitCode: 128, + stdout: "", + }, + ) => + WorkspaceSearchIndex.make(cwd, "content").pipe( + Effect.provideService( + VcsProcess.VcsProcess, + VcsProcess.VcsProcess.of({ + run: (input) => + input.args.includes(failingArgument) + ? Effect.succeed({ + exitCode: ChildProcessSpawner.ExitCode(output.exitCode), + stdout: output.stdout, + stderr, + stdoutTruncated: output.exitCode === 0, + stderrTruncated: false, + }) + : vcsProcess.run(input), + }), + ), + ); + const regexInput = { + query: "ne+dles?", + limit: 10, + caseSensitive: false, + wholeWord: true, + useRegex: true, + }; + const noPcreIndex = yield* failingGitIndex( + "-P", + "fatal: cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE\n", + ); + expect((yield* noPcreIndex.searchContents(regexInput)).regexFallbackError).toBeUndefined(); + expect(grep).toHaveBeenCalledTimes(1); + const noRangesIndex = yield* failingGitIndex("-o", "fatal: unexpected failure\n"); + yield* noRangesIndex.searchContents(regexInput); + expect(grep).toHaveBeenCalledTimes(2); + // Ranges output cut off after line 1: line 2 is left out and the result says so. + const cutRangesIndex = yield* failingGitIndex("-o", "", { + exitCode: 0, + stdout: "src/a.ts\u00001\u00007\u0000Needle\nsrc/a.ts\u00002", + }); + expect(yield* cutRangesIndex.searchContents(regexInput)).toEqual({ + matches: [ + { + path: "src/a.ts", + lineNumber: 1, + lineContent: "const Needle = 1;", + matchRanges: [{ start: 6, end: 12 }], + }, + ], + truncated: true, + }); + + isWarmupComplete = true; + yield* search({}); + expect(grep).toHaveBeenCalledTimes(3); + expect(finder.destroy).not.toHaveBeenCalled(); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + function fakeSymlinkFinder( directories: ReadonlyArray, options: { diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index fd92420396e4..858c420c72fb 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -57,6 +57,9 @@ const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000; const WORKSPACE_INDEX_IDLE_TTL = "15 minutes"; const CONTENT_SEARCH_TIME_BUDGET_MS = 250; const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100; +const GIT_GREP_MAX_OUTPUT_BYTES = 4 * 1024 * 1024; +// fff's lineContent cap; matches past it are reported without ranges. +const CONTENT_LINE_MAX_LENGTH = 512; const SYMLINK_SCAN_CONCURRENCY = 16; // A scan no watcher can invalidate is reused this long, so typing does not rescan every folder. const UNWATCHED_SYMLINK_SCAN_TTL_MS = 2_000; @@ -294,6 +297,47 @@ function mapContentMatchRanges( })); } +function escapeRegExp(input: string): string { + return input.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&"); +} + +// Git before 2.55 reports wrong `--column` values for every match after a line's first, so +// later matches are found by their text, searching on from the end of the previous one. +function locateRegexMatches( + line: string, + matches: { readonly column: number; readonly texts: ReadonlyArray } | undefined, +): Array { + if (!matches) return []; + const lineBytes = Buffer.from(line); + const ranges: Array = []; + let start = matches.column - 1; + for (const text of matches.texts) { + const textBytes = Buffer.from(text); + if (ranges.length > 0) start = lineBytes.indexOf(textBytes, ranges.at(-1)![1]); + if (start < 0) break; + ranges.push([start, start + textBytes.length]); + } + return ranges; +} + +// `git grep -z` records: NUL-separated fields, one record per line; a truncated last line is dropped. +function parseGitGrepRecords( + stdout: string, + fieldCount: number, + truncated: boolean, +): Array> { + const lines = stdout.split("\n"); + if (truncated || lines.at(-1) === "") lines.pop(); + const records: Array> = []; + for (const line of lines) { + const fields = line.split("\0"); + if (fields.length < fieldCount) continue; + // Only the last field (the line or match text) can contain NUL bytes. + records.push([...fields.slice(0, fieldCount - 1), fields.slice(fieldCount - 1).join("\0")]); + } + return records; +} + // Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges. function isWholeWordRange( line: string, @@ -576,26 +620,30 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }).pipe(Effect.orDie), ); let initialScanTimedOut = false; + // The content index reads every file, which takes minutes where antivirus scans each open, + // so content searches do not wait for it; git grep answers until it is ready. + let contentIndexPending = variant === "content"; const vcsProcess = yield* VcsProcess.VcsProcess; let ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows); - yield* waitForIndexReady( - cwd, - finder, - ({ reason, cause }) => - new WorkspaceSearchIndexCreateFailed({ - cwd, - reason, - cause, - }), - ).pipe( - // The scan keeps running on this finder; failing here would destroy it and cache the failure. - Effect.catchTags({ - WorkspaceSearchIndexScanTimedOut: () => - Effect.sync(() => { - initialScanTimedOut = true; + if (variant === "paths") { + yield* waitForIndexReady( + cwd, + finder, + ({ reason, cause }) => + new WorkspaceSearchIndexCreateFailed({ + cwd, + reason, + cause, }), - }), - ); + ).pipe( + Effect.catchTags({ + WorkspaceSearchIndexScanTimedOut: () => + Effect.sync(() => { + initialScanTimedOut = true; + }), + }), + ); + } // fff's isScanning takes the picker lock too, so progress is read off the JS thread. const isScanning = Effect.promise(async () => { @@ -608,10 +656,203 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }); const hasIncompleteInitialScan = () => (initialScanTimedOut ? isScanning : Effect.succeed(false)); + const isContentIndexReady = Effect.fn("WorkspaceSearchIndex.isContentIndexReady")(function* () { + if (!contentIndexPending) return true; + const progress = yield* Effect.promise(() => + finder.getScanProgressAsync().catch(() => undefined), + ); + if (progress?.ok && !progress.value.isScanning && progress.value.isWarmupComplete) { + contentIndexPending = false; + } + return !contentIndexPending; + }); + + const runGitGrep = Effect.fn("WorkspaceSearchIndex.runGitGrep")(function* ( + pattern: string, + options: { + readonly regexMode: boolean; + readonly ignoreCase: boolean; + readonly maxMatchesPerFile: number; + readonly onlyMatching: boolean; + }, + ) { + return yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.gitGrep", + command: "git", + args: [ + "-c", + "core.quotePath=false", + "-c", + "core.fsmonitor=false", + "grep", + "--untracked", + "--no-color", + "-I", + "-n", + "-z", + "-m", + String(options.maxMatchesPerFile), + ...(options.onlyMatching ? ["-o", "--column"] : []), + ...(options.ignoreCase ? ["-i"] : []), + options.regexMode ? "-P" : "-F", + "-e", + pattern, + ], + cwd, + allowNonZeroExit: true, + // Defender scanning fff's warmup reads slows git too; a late answer beats a failure. + timeoutMs: 30_000, + maxOutputBytes: GIT_GREP_MAX_OUTPUT_BYTES, + outputMode: "truncate", + appendTruncationMarker: false, + }) + .pipe(Effect.option); + }); + + // fff leaves out what `.ignore` files exclude, which git cannot evaluate; the nearest + // `.ignore` that matches a path or one of its folders decides, as in decideByIgnoreFiles. + const makeIgnoreFileFilter = () => { + const ignoreFiles = new Map(); + const readIgnoreFile = Effect.fn("WorkspaceSearchIndex.readIgnoreFile")(function* ( + directory: string, + ) { + if (ignoreFiles.has(directory)) return ignoreFiles.get(directory); + const contents = yield* fileSystem + .readFileString(path.join(cwd, directory, ".ignore")) + .pipe(Effect.option); + const file = Option.isSome(contents) ? parseIgnoreFile(contents.value) : undefined; + ignoreFiles.set(directory, file); + return file; + }); + return Effect.fn("WorkspaceSearchIndex.isExcludedByIgnoreFiles")(function* ( + relativePath: string, + ) { + const segments = relativePath.split("/"); + for (let depth = 1; depth <= segments.length; depth += 1) { + const candidate = segments.slice(0, depth).join("/"); + for (let ancestor = depth - 1; ancestor >= 0; ancestor -= 1) { + const directory = segments.slice(0, ancestor).join("/"); + const file = yield* readIgnoreFile(directory); + const relative = directory ? candidate.slice(directory.length + 1) : candidate; + const decision = file?.decide(relative, depth < segments.length); + if (decision === "ignored") return true; + if (decision === "included") break; + } + } + return false; + }); + }; + + // fff's grep before its content index is ready opens every file itself, as slowly as the build. + // None when git cannot search this folder (not a repository, git missing, no PCRE for a regex). + const searchContentsWithGit = Effect.fn("WorkspaceSearchIndex.searchContentsWithGit")(function* ( + input: Omit, + ): Effect.fn.Return> { + const options = { + ignoreCase: !input.caseSensitive, + maxMatchesPerFile: CONTENT_SEARCH_MAX_MATCHES_PER_FILE, + onlyMatching: false, + }; + let regexMode = input.useRegex; + let regexFallbackError: string | undefined; + let result = yield* runGitGrep(input.query, { ...options, regexMode }); + if (regexMode && Option.isSome(result) && result.value.exitCode === 128) { + if (/USE_LIBPCRE|Perl-compatible/i.test(result.value.stderr)) return Option.none(); + // fff searches an invalid pattern as a literal and reports why. + regexFallbackError = result.value.stderr.trim().split("\n")[0] || "Invalid regex"; + regexMode = false; + result = yield* runGitGrep(input.query, { ...options, regexMode }); + } + if (Option.isNone(result) || result.value.exitCode > 1) return Option.none(); + + // Per line: the first match's byte column and every match's text, in order. + const regexMatches = new Map(); + let rangesTruncated = false; + if (regexMode) { + // Ranges come from git too: running the user's pattern in JS could backtrack without bound. + const ranges = yield* runGitGrep(input.query, { ...options, regexMode, onlyMatching: true }); + // Without ranges, whole-word filtering would drop every hit and report no matches. + if (Option.isNone(ranges) || ranges.value.exitCode > 1) return Option.none(); + rangesTruncated = ranges.value.stdoutTruncated; + if (ranges.value.exitCode === 0) { + for (const record of parseGitGrepRecords( + ranges.value.stdout, + 4, + ranges.value.stdoutTruncated, + )) { + const [relativePath, lineNumber, column, text] = record as [ + string, + string, + string, + string, + ]; + const key = `${relativePath}\0${lineNumber}`; + const lineMatches = regexMatches.get(key); + if (lineMatches) lineMatches.texts.push(text); + else regexMatches.set(key, { column: Number(column), texts: [text] }); + } + } + } + const literal = regexMode + ? undefined + : new RegExp(escapeRegExp(input.query), input.caseSensitive ? "gu" : "giu"); + + const isExcludedByIgnoreFiles = makeIgnoreFileFilter(); + const matches: Array = []; + let rangesCutOff = false; + for (const record of parseGitGrepRecords( + result.value.stdout, + 3, + result.value.stdoutTruncated, + )) { + const [relativePath, lineNumber, rawLine] = record as [string, string, string]; + if (yield* isExcludedByIgnoreFiles(relativePath)) continue; + const key = `${relativePath}\0${lineNumber}`; + // Lines past the cut-off of a truncated ranges run have no ranges; stop there instead. + if (rangesTruncated && !regexMatches.has(key)) { + rangesCutOff = true; + break; + } + const lineContent = (rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine).slice( + 0, + CONTENT_LINE_MAX_LENGTH, + ); + const matchRanges = ( + literal + ? Array.from(lineContent.matchAll(literal), (match) => ({ + start: match.index, + end: match.index + match[0].length, + })) + : mapContentMatchRanges( + lineContent, + locateRegexMatches(lineContent, regexMatches.get(key)), + ) + ).filter( + (range) => + range.end <= lineContent.length && + (!input.wholeWord || isWholeWordRange(lineContent, range)), + ); + if (input.wholeWord && matchRanges.length === 0) continue; + matches.push({ + path: relativePath, + lineNumber: Number(lineNumber), + lineContent, + matchRanges, + }); + if (matches.length > input.limit) break; + } + return Option.some({ + matches: matches.slice(0, input.limit), + truncated: matches.length > input.limit || result.value.stdoutTruncated || rangesCutOff, + ...(regexFallbackError !== undefined ? { regexFallbackError } : {}), + }); + }); + const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* ( query: string, pageSize: number, - operation: "directorySearch" | "fileSearch" | "getScanProgress" | "grep" | "mixedSearch", + operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch", execute: () => Promise>, ): Effect.fn.Return { // fff's searches wait on its picker lock, which its watcher can hold for minutes. @@ -1038,20 +1279,23 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( const searchContents: WorkspaceSearchIndex["Service"]["searchContents"] = Effect.fn( "WorkspaceSearchIndex.searchContents", )(function* (input) { - if (initialScanTimedOut) { - const progress = yield* runSearch(input.query, input.limit, "getScanProgress", () => - finder.getScanProgressAsync(), + if (!(yield* isContentIndexReady())) { + const gitResult = yield* searchContentsWithGit(input); + if (Option.isSome(gitResult)) return gitResult.value; + yield* waitForIndexReady( + cwd, + finder, + ({ reason, cause }) => + new WorkspaceSearchIndexSearchFailed({ + cwd, + queryLength: input.query.length, + pageSize: input.limit, + reason, + cause, + }), ); - // Files the first scan has not indexed yet would read as "No results found". - if (!progress.isWarmupComplete) { - return yield* new WorkspaceSearchIndexScanTimedOut({ - cwd, - timeout: WORKSPACE_INDEX_SCAN_TIMEOUT, - }); - } - initialScanTimedOut = false; + contentIndexPending = false; } - let { searchQuery, regexMode } = buildContentSearchQuery(input); const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS; // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing. From 304cf149c8cb5e2c1ab921428773361752d7aff2 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:01:50 +0100 Subject: [PATCH 010/112] fix(web): terminal file links preserve numeric filename suffixes (#37201) Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- .../src/process/externalLauncher.test.ts | 47 ++++++++- apps/server/src/process/externalLauncher.ts | 43 ++++++-- apps/web/src/editorPreferences.test.ts | 22 +++++ apps/web/src/editorPreferences.ts | 7 +- apps/web/src/hooks/useFileMetadata.ts | 14 ++- apps/web/src/terminal-links.test.ts | 23 ++++- apps/web/src/terminal-links.ts | 20 ++-- packages/contracts/src/editor.ts | 9 +- ...minal-file-uri-opens-its-exact-file.e2e.ts | 98 +++++++++++++++++++ 9 files changed, 253 insertions(+), 30 deletions(-) create mode 100644 scripts/scenarios/terminal-file-uri-opens-its-exact-file.e2e.ts diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index f215fe4ebc6a..8ce873733d44 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -117,8 +117,8 @@ it.effect.skipIf(windowsHost)("opens home-relative targets using the server home const spawned: ChildProcess.StandardCommand[] = []; yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; - for (const cwd of ["~/Applications/My App.app", "/Applications/My App.app"]) { - yield* launcher.launchEditor({ editor: "file-manager", cwd }); + for (const cwd of ["~/Applications/My App.app", "/Applications/My App.app", "/tmp/a:12"]) { + yield* launcher.launchEditor({ editor: "file-manager", cwd, position: { line: 5 } }); } yield* launcher.launchEditor({ editor: "vscode", cwd: "~/notes/todo.md:3" }); yield* launcher.launchEditor({ @@ -141,6 +141,7 @@ it.effect.skipIf(windowsHost)("opens home-relative targets using the server home [ ["/Users/server/Applications/My App.app"], ["/Applications/My App.app"], + ["/tmp/a:12"], ["--goto", "/Users/server/notes/todo.md:3"], ["/Users/server/notes", "--line", "3", "/Users/server/notes/todo.md"], ], @@ -203,12 +204,20 @@ it.effect.skipIf(windowsHost)( const path = yield* Path.Path; const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); const project = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-project-" }); - const codePath = path.join(binDir, "code"); - yield* fileSystem.writeFileString(codePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(codePath, 0o755); + for (const name of ["code", "zeditor", "idea"]) { + const executable = path.join(binDir, name); + yield* fileSystem.writeFileString(executable, "#!/bin/sh\n"); + yield* fileSystem.chmod(executable, 0o755); + } const colonProject = path.join(project, "build:2026"); yield* fileSystem.makeDirectory(colonProject); const file = `${path.join(project, "file.ts")}:3:7`; + const exactFile = path.join(project, "a:12"); + yield* fileSystem.writeFileString(exactFile, "exact"); + yield* fileSystem.makeDirectory(`${exactFile}:1:1`); + const positionedFile = path.join(project, "position.txt"); + yield* fileSystem.writeFileString(positionedFile, "position"); + yield* fileSystem.writeFileString(`${positionedFile}:7`, "collision"); const spawned: ChildProcess.StandardCommand[] = []; yield* Effect.gen(function* () { @@ -216,6 +225,27 @@ it.effect.skipIf(windowsHost)( yield* launcher.launchEditor({ editor: "vscode", cwd: project }); yield* launcher.launchEditor({ editor: "vscode", cwd: file }); yield* launcher.launchEditor({ editor: "vscode", cwd: colonProject }); + for (const position of [{}, { line: 5 }]) { + yield* launcher.launchEditor({ editor: "vscode", cwd: exactFile, position }); + } + + yield* launcher.launchEditor({ editor: "zed", cwd: exactFile, position: {} }); + yield* launcher.launchEditor({ + editor: "zed", + cwd: positionedFile, + position: { line: 5, column: 3 }, + }); + yield* launcher.launchEditor({ editor: "zed", cwd: positionedFile, position: { line: 7 } }); + yield* launcher.launchEditor({ + editor: "vscode", + cwd: `${project}/exponent:1e3`, + position: { line: 5 }, + }); + yield* launcher.launchEditor({ + editor: "idea", + cwd: exactFile, + position: { line: 5, column: 3 }, + }); }).pipe( Effect.provide( layerTest({ @@ -233,6 +263,13 @@ it.effect.skipIf(windowsHost)( ["--new-window", project], ["--goto", file], ["--new-window", colonProject], + [exactFile], + [exactFile], + [exactFile], + [`${positionedFile}:5:3`], + [positionedFile], + [`${project}/exponent:1e3`], + ["--line", "5", "--column", "2", exactFile], ], ); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index 2bdb7bd3db4d..caa6664a1ba8 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -142,17 +142,37 @@ function resolveCommandEditorArgs( target: string, isDirectory: boolean, projectRoot: string | undefined, + position: LaunchEditorInput["position"], ): ReadonlyArray { - const parsedTarget = parseTargetPathAndPosition(target); + const parsedTarget = + position === undefined + ? parseTargetPathAndPosition(target) + : Option.fromUndefinedOr(position.line).pipe( + Option.map((line) => ({ + path: target, + line: String(line), + column: Option.fromUndefinedOr(position.column).pipe(Option.map(String)), + })), + ); + const positionedTarget = Option.match(parsedTarget, { + onNone: () => target, + onSome: ({ path, line, column }) => [path, line, ...Option.toArray(column)].join(":"), + }); switch (editor.launchStyle) { case "direct-path": - return [target]; + return [positionedTarget]; case "goto": // An existing folder wins over a position: `build:2026` is a legal folder name. // Without a window flag, VS Code's window settings may replace the user's last active window. if (isDirectory) return ["--new-window", target]; - return Option.isSome(parsedTarget) ? ["--goto", target] : [target]; + // VS Code splits every numeric colon segment, including ones inside the filename. + if ( + position !== undefined && + target.split(":").some((segment) => !Number.isNaN(Number(segment))) + ) + return [target]; + return Option.isSome(parsedTarget) ? ["--goto", positionedTarget] : [target]; case "line-column": return Option.match(parsedTarget, { onNone: () => [target], @@ -526,6 +546,18 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor }); } + const target = input.cwd; + let position = input.position; + if (editorDef.id === "zed" && position?.line !== undefined) { + // Zed resolves existing paths before positions, so ambiguous spellings must stay literal. + const collision = + /:\d+(?=:|$)/.test(target) || + (yield* (yield* FileSystem.FileSystem) + .exists(`${target}:${position.line}${position.column ? `:${position.column}` : ""}`) + .pipe(Effect.orElseSucceed(() => true))); + if (collision) position = {}; + } + if (editorDef.commands) { const resolved = yield* resolveEditorCommand(editorDef, env); if (Option.isNone(resolved)) { @@ -537,7 +569,7 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( const { command, baseArgs } = resolved.value; const isDirectory = editorDef.launchStyle === "goto" && - (yield* (yield* FileSystem.FileSystem).stat(input.cwd).pipe( + (yield* (yield* FileSystem.FileSystem).stat(target).pipe( Effect.map((info) => info.type === "Directory"), Effect.orElseSucceed(() => false), )); @@ -547,7 +579,7 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( command, args: [ ...baseArgs, - ...resolveCommandEditorArgs(editorDef, input.cwd, isDirectory, input.projectRoot), + ...resolveCommandEditorArgs(editorDef, target, isDirectory, input.projectRoot, position), ], }; } @@ -561,7 +593,6 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor }); } - const target = input.cwd; if (input.reveal === true) { return yield* resolveFileManagerRevealLaunch(target, platform, env, command); } diff --git a/apps/web/src/editorPreferences.test.ts b/apps/web/src/editorPreferences.test.ts index 8a525628db5a..c55fd71a385b 100644 --- a/apps/web/src/editorPreferences.test.ts +++ b/apps/web/src/editorPreferences.test.ts @@ -88,3 +88,25 @@ it.each(["read", "write"] as const)( }); }, ); + +it.each([ + ["file:///work/read%20me.md", "/work/read me.md", {}], + [ + "file://foreign/share/read%20me.md:12#L5", + String.raw`\\foreign\share\read me.md:12`, + { line: 5 }, + ], + ["file:///work/report.txt:12", "/work/report.txt:12", {}], + ["file:///work/report.txt:12#L5C3", "/work/report.txt:12", { line: 5, column: 3 }], +])( + "sends a plain exact path for %s to compatible and older servers", + async (uri, cwd, position) => { + state.allowed.add(secondary); + const open = useOpenInPreferredEditor(secondary, ["vscode"]); + await open(uri); + expect(state.run).toHaveBeenCalledExactlyOnceWith({ + environmentId: secondary, + input: { cwd, position, editor: "vscode" }, + }); + }, +); diff --git a/apps/web/src/editorPreferences.ts b/apps/web/src/editorPreferences.ts index 712d7affc2e0..6b3e99c1bda6 100644 --- a/apps/web/src/editorPreferences.ts +++ b/apps/web/src/editorPreferences.ts @@ -10,6 +10,8 @@ import { type AtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; +import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks"; +import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; import { AsyncResult } from "effect/reactivity"; @@ -127,10 +129,13 @@ export function useOpenInPreferredEditor( ), ); } + const uri = /^file:\/\//iu.test(targetPath) ? parseFileUrlHref(targetPath) : null; + const { line, column } = uri ? splitFilePathPosition("", uri.hash) : {}; const result = await openInEditor({ environmentId, input: { - cwd: targetPath, + cwd: uri ? safeDecodeURIComponent(uri.path) : targetPath, + ...(uri ? { position: { line, column } } : {}), editor, ...(projectRoot ? { projectRoot } : {}), }, diff --git a/apps/web/src/hooks/useFileMetadata.ts b/apps/web/src/hooks/useFileMetadata.ts index 398df04a88de..5b8f1a0cfc79 100644 --- a/apps/web/src/hooks/useFileMetadata.ts +++ b/apps/web/src/hooks/useFileMetadata.ts @@ -3,12 +3,17 @@ import { type EnvironmentId, type ScopedThreadRef, } from "@t3tools/contracts"; -import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks"; +import { + parseFileUrlHref, + resolvePathLinkTarget, + splitFilePathPosition, +} from "@t3tools/shared/fileLinks"; import { isAbsolutePath, isNetworkPath, normalizeProjectPathForComparison, } from "@t3tools/shared/path"; +import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks"; import { useContext } from "react"; import { useEnvironmentScope } from "../state/session"; @@ -22,9 +27,14 @@ export function getFileMetadataQueryAtom( cwd?: string, threadRef?: ScopedThreadRef | null, ) { + const uri = /^file:\/\//iu.test(path) ? parseFileUrlHref(path) : null; const hostPath = splitFilePathPosition(path).path; const targetPath = normalizeProjectPathForComparison( - hostPath.startsWith("~/") || !cwd ? hostPath : resolvePathLinkTarget(hostPath, cwd), + uri + ? safeDecodeURIComponent(uri.path) + : hostPath.startsWith("~/") || !cwd + ? hostPath + : resolvePathLinkTarget(hostPath, cwd), ); const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/"); return ( diff --git a/apps/web/src/terminal-links.test.ts b/apps/web/src/terminal-links.test.ts index 105fc9719b48..2bf8714e700e 100644 --- a/apps/web/src/terminal-links.test.ts +++ b/apps/web/src/terminal-links.test.ts @@ -351,11 +351,32 @@ describe("resolvePathLinkTarget", () => { // regression: #36005 OSC 8 file URIs were joined onto the cwd as relative paths it("does not resolve an OSC 8 file URI target against the cwd", () => { expect(resolveTerminalLinkTarget("file:///var/tmp/report.txt", "/workspace/project")).toBe( - "/var/tmp/report.txt", + "file:///var/tmp/report.txt", ); expect( resolveTerminalLinkTarget("file://remote.invalid/var/tmp/report.txt", "/workspace/project"), ).not.toMatch(/^\/workspace\/project\//); + expect( + resolveTerminalLinkTarget( + "file://myhost/var/tmp/report.txt:12#L5", + "/workspace/project", + "myhost", + ), + ).toBe("file:///var/tmp/report.txt:12#L5"); + expect( + resolveTerminalLinkTarget( + "file://foreign/var/tmp/report.txt:12#L5", + "/workspace/project", + "myhost", + ), + ).toBe("file://foreign/var/tmp/report.txt:12#L5"); + for (const name of ["report.txt:12-64", "report.txt:0", "report.txt:12"]) { + const uri = `file:///var/tmp/${encodeURIComponent(name)}`; + expect(resolveTerminalLinkTarget(uri, "/workspace/project")).toBe(uri); + } + expect( + resolveTerminalLinkTarget("file:///var/tmp/report.txt:12#L5", "/workspace/project"), + ).toBe("file:///var/tmp/report.txt:12#L5"); expect(resolvePathLinkTarget("file:notes.md", "/workspace/project")).toBe( "/workspace/project/file:notes.md", ); diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.ts index f953f6dfee29..621ff0fc7247 100644 --- a/apps/web/src/terminal-links.ts +++ b/apps/web/src/terminal-links.ts @@ -1,11 +1,4 @@ -import { - formatFilePathPosition, - parseFileUrlHref, - resolvePathLinkTarget, - splitFilePathPosition, -} from "@t3tools/shared/fileLinks"; -import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks"; -import { stripSlashPrefixedWindowsDrive } from "@t3tools/shared/path"; +import { parseFileUrlHref, resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { isMacPlatform } from "./lib/utils"; export type TerminalLinkKind = "url" | "path"; @@ -165,16 +158,15 @@ export function isTerminalUrl(value: string): boolean { /** * Explicit OSC 8 targets may be `file://` URIs; everything else is a path relative to `cwd`. * `hostname` is the terminal's environment's, which producers such as GNU `ls` put in the URI. + * A URI's path is the exact filename, so only its `#L12C3` hash is a position. */ export function resolveTerminalLinkTarget(text: string, cwd: string, hostname?: string): string { const fileUrl = /^file:\/\//iu.test(text) ? parseFileUrlHref(text, hostname) : null; if (!fileUrl) return resolvePathLinkTarget(text, cwd); - return formatFilePathPosition( - splitFilePathPosition( - stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(fileUrl.path)), - fileUrl.hash, - ), - ); + // Keep URI identity until consumers decode the filename, separately from its position. + const uri = new URL(text); + if (!fileUrl.path.startsWith("\\")) uri.hostname = ""; + return uri.href; } export function collectWrappedTerminalLinkLine( diff --git a/packages/contracts/src/editor.ts b/packages/contracts/src/editor.ts index 28fd10d6e7b2..146007499d44 100644 --- a/packages/contracts/src/editor.ts +++ b/packages/contracts/src/editor.ts @@ -1,5 +1,5 @@ import * as Schema from "effect/Schema"; -import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; export const EditorLaunchStyle = Schema.Literals(["direct-path", "goto", "line-column"]); export type EditorLaunchStyle = typeof EditorLaunchStyle.Type; @@ -157,6 +157,13 @@ export type FileManagerRevealKind = typeof FileManagerRevealKind.Type; export const LaunchEditorInput = Schema.Struct({ cwd: TrimmedNonEmptyString, editor: EditorId, + /** When present, cwd is an exact path; {} opens it without a position. Omit for diagnostic suffix parsing. */ + position: Schema.optional( + Schema.Struct({ + line: Schema.optional(PositiveInt), + column: Schema.optional(PositiveInt), + }), + ), /** Workspace the target belongs to; JetBrains IDEs open positioned files in this project. */ projectRoot: Schema.optional(TrimmedNonEmptyString), /** Only for file-manager; requires the server's shellRevealInFileManager capability. */ diff --git a/scripts/scenarios/terminal-file-uri-opens-its-exact-file.e2e.ts b/scripts/scenarios/terminal-file-uri-opens-its-exact-file.e2e.ts new file mode 100644 index 000000000000..8c4265b50a79 --- /dev/null +++ b/scripts/scenarios/terminal-file-uri-opens-its-exact-file.e2e.ts @@ -0,0 +1,98 @@ +/// +// The DOM lib types the function this scenario runs in the page. +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; + +import { T3_HOME } from "../e2e.config.ts"; +import { runPromise, test, WEB } from "./t3.ts"; + +const EDITOR_ARGS = `${T3_HOME}/editor-args.txt`; + +/** The file's lines, or none while it does not exist. */ +const readLines = (file: string) => + runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + if (!(yield* fs.exists(file))) return []; + return (yield* fs.readFileString(file)).trim().split("\n"); + }), + ); + +const removeEditorArgs = () => + runPromise( + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.remove(EDITOR_ARGS, { force: true })), + ); + +// GNU ls, made hostless, for filenames that end like a position. +const listed = (name: string) => + `command ls -d --hyperlink=always --color=never -1 --quoting-style=literal -- '${name}' | sed -E 's@file://[^/]+/@file:///@'`; +// An opaque label, so only the URI can name the file. +const hashed = (uriPath: string) => + `printf '\\033]8;;file://%s\\033\\\\CLICKME\\033]8;;\\033\\\\\\n' "$PWD/${uriPath}"`; + +const LINKS = [ + { print: listed("report.txt:12-64"), opens: ["report.txt:12-64"] }, + { print: listed("zero.txt:0"), opens: ["zero.txt:0"] }, + { print: hashed("numeric.txt%3A12#L5"), opens: ["numeric.txt:12"] }, + { print: hashed("position.txt#L5C3"), opens: ["--goto", "position.txt:5:3"] }, + { print: listed("build:2026"), opens: ["--new-window", "build:2026"] }, +]; + +test( + "Ctrl+click on a terminal file URI opens the exact file it names, even one ending like a position", + WEB, + async ({ t3, app, browser, screen }) => { + await removeEditorArgs(); + const files: Record = { + "build:2026/keep.txt": "keep\n", + "numeric.txt:12:1:1/keep.txt": "decoy\n", + }; + for (const name of ["report.txt:12-64", "zero.txt:0", "numeric.txt:12", "position.txt"]) { + files[name] = `${name}\n`; + } + // Enough rows to scroll, so every row is the link. Scripts keep the typed commands short. + for (const [index, link] of LINKS.entries()) { + files[`print-${index}.sh`] = + `for i in $(seq 1 100); do ${link.print}; done; touch printed-${index}\n`; + } + const project = await t3.project("demo", files); + const thread = await t3.thread({ project, title: "List", messages: ["List it"] }); + await t3.open(thread); + + await screen.getByRole("button", "Toggle terminal drawer").tap(); + const input = screen.getByRole("textbox", "Terminal input"); + // The input mounts before fonts and WASM finish loading and its handlers are installed. + await expect(input).toHaveAttribute("data-workspace-focus-default", ""); + + for (const [index, { opens }] of LINKS.entries()) { + await removeEditorArgs(); + await input.focus(); + await browser.keyboard.type(`bash print-${index}.sh\n`); + await expect + .poll(() => readLines(`${project}/printed-${index}`), { timeout: 30_000 }) + .toEqual([""]); + await app.screenshot(`printed-${index}`); + + // The terminal draws on a canvas, so point at the first cells of a row near its middle. + const canvas = await browser.evaluate(() => { + const box = document + .querySelector('[aria-label="Terminal input"]') + ?.parentElement?.querySelector("canvas") + ?.getBoundingClientRect(); + return box ? { x: box.x, y: box.y, width: box.width, height: box.height } : null; + }); + if (!canvas) throw new Error("The terminal canvas is not on the page."); + // Alternate rows, or a quick second click on the same spot counts as a double-click. + await browser.mouse.move(canvas.x + 16, canvas.y + canvas.height / 2 - (index % 2) * 40); + await browser.keyboard.down("Control"); + await browser.mouse.down(); + await browser.mouse.up(); + await browser.keyboard.up("Control"); + + await expect + .poll(() => readLines(EDITOR_ARGS), { timeout: 15_000 }) + .toEqual(["--classic", ...opens.slice(0, -1), `${project}/${opens.at(-1)}`]); + } + }, +); From 507093152148c0d31c09bcd40e3ce4b5214a8557 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:12:34 +0100 Subject: [PATCH 011/112] fix(mobile): cutting text in the iOS composer can be undone (#37158) Co-authored-by: Julius Marminge --- .../ios/T3ComposerEditorView.swift | 40 +++++++++++-------- .../t3-composer-editor/tests/ios/main.swift | 25 ++++++++++++ 2 files changed, 49 insertions(+), 16 deletions(-) diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index 7bc50b694df5..6b2e18389293 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -47,12 +47,12 @@ private enum ComposerEnterBehavior: String { } private final class ComposerTextAttachment: NSTextAttachment { - let source: String - let label: String + let token: ComposerTokenPayload + var source: String { token.source } + var label: String { token.label } - init(source: String, label: String, image: UIImage, size: CGSize, baselineOffset: CGFloat) { - self.source = source - self.label = label + init(token: ComposerTokenPayload, image: UIImage, size: CGSize, baselineOffset: CGFloat) { + self.token = token super.init(data: nil, ofType: nil) self.image = image bounds = CGRect(x: 0, y: baselineOffset, width: size.width, height: size.height) @@ -89,7 +89,6 @@ private final class ComposerTextView: UITextView { var onPasteContext: (([String: String]) -> Void)? var onPasteText: ((String, NSRange) -> Void)? var clipboardFragment = "" - var onAttributedMutation: (() -> Void)? var onSubmit: ((Bool) -> Void)? var isReadOnly = false var textPasteThresholdBytes = 0 @@ -363,9 +362,7 @@ private final class ComposerTextView: UITextView { return super.cut(sender) } copy(sender) - textStorage.replaceCharacters(in: selectedRange, with: "") - selectedRange = NSRange(location: selectedRange.location, length: 0) - onAttributedMutation?() + replaceDisplayRange(selectedRange) } func serializedText() -> String { @@ -564,9 +561,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro "selection": ["start": selection.start, "end": selection.end], ]) } - textView.onAttributedMutation = { [weak self] in - self?.emitTextChange() - } textView.onSubmit = { [weak self] alternate in self?.onComposerSubmit(["alternate": alternate]) } @@ -737,8 +731,10 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro if tokensJson != document.tokensJson { tokensJson = document.tokensJson let nextTokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? [] - // Typing before a chip only moves its offsets; rebuilding then makes iOS autocorrect behind the caret. - tokensNeedRebuild = tokensNeedRebuild || !nextTokens.elementsEqual(tokens, by: { $0.rendersLike($1) }) + // Rebuild only when a chip on screen would look different: typing before a chip moves its + // offsets, and Undo restores the chip it removed. A rebuild there makes iOS autocorrect + // behind the caret, and replacing the text drops UIKit's Redo. + tokensNeedRebuild = tokensNeedRebuild || !nextTokens.elementsEqual(renderedChipTokens(), by: { $0.rendersLike($1) }) tokens = nextTokens } let previousSelection = sourceSelection() @@ -1052,8 +1048,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro font: chipFont ) let attachment = ComposerTextAttachment( - source: token.source, - label: token.label, + token: token, image: image, size: image.size, baselineOffset: chipFont.ascender - image.size.height @@ -1353,6 +1348,19 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro } } + private func renderedChipTokens() -> [ComposerTokenPayload] { + var rendered: [ComposerTokenPayload] = [] + textView.textStorage.enumerateAttribute( + .attachment, + in: NSRange(location: 0, length: textView.textStorage.length) + ) { value, _, _ in + if let attachment = value as? ComposerTextAttachment { + rendered.append(attachment.token) + } + } + return rendered + } + private func documentMatchesExpectedTokens() -> Bool { let source = value as NSString let expectedChips = tokens.compactMap { token -> (Int, String)? in diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift index e9751eec843a..6009daacb404 100644 --- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift +++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift @@ -146,6 +146,31 @@ do { check(view.editor.accessibilityLabel == "Ask anything", "VoiceOver label: \(String(describing: view.editor.accessibilityLabel))") } +// Cutting a chip is undoable: Undo restores the chip and tells the parent, Redo removes it again. +// The parent echoes each edit with its re-derived chips; those echoes must not rebuild the text. +do { + let view = makeEditor("hi @README.md ok", tokensJson: mention("README.md", at: 3)) + func echo() { + let revision = view.onComposerChange.payloads.last?["eventCount"] as? Int ?? 0 + let chips = view.text.contains("@README.md") ? mention("README.md", at: 3) : "[]" + view.setControlledDocumentJson(document(view.text, revision: revision, isNativeEcho: true, tokensJson: chips)) + } + view.editor.selectedRange = NSRange(location: 3, length: 2) + view.editor.cut(nil) + check(view.text == "hi ok", "Cut left the selection behind: \(view.text)") + check(view.onComposerChange.payloads.last?["value"] as? String == "hi ok", "Cut did not emit the new value") + echo() + view.editor.undoManager?.undo() + check(view.text == "hi @README.md ok", "Undo did not restore the cut text: \(view.text)") + let restored = view.chip(at: 3) + check(restored is ComposerTextAttachment, "Undo did not restore the cut chip") + check(view.onComposerChange.payloads.last?["value"] as? String == "hi @README.md ok", "Undo did not emit the restored value") + echo() + check(view.chip(at: 3) === restored, "The parent's echo of the restored chip rebuilt the text and dropped Redo") + view.editor.undoManager?.redo() + check(view.text == "hi ok", "Redo did not cut again: \(view.text)") +} + print("composer editor tests passed") private let dropEditor = ComposerTextView() From 449deb635ec0fc7735b42671afcdb7ee73eebf45 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Nov 2026 05:22:34 -0800 Subject: [PATCH 012/112] fix(web): modified F3 reaches ncurses terminal bindings (#37211) --- apps/web/src/terminal/ghostty/core.test.ts | 28 ++++++++++++++++++++++ apps/web/src/terminal/ghostty/core.ts | 15 +++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index 7958475ea54e..c3f0f3aa0706 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -165,6 +165,34 @@ describe("GhosttyTerminalCore snapshots", () => { }, ); + // smkx is what ncurses keypad(True) sends; a raw-mode parser such as Crossterm never does. + it.each([ + { mode: "", ctrlKey: true, expected: "\x1b[13;5~" }, + { mode: "\x1b[?1h\x1b=", ctrlKey: true, expected: "\x1b[1;5R" }, + { mode: "\x1b[?1h\x1b=", shiftKey: true, expected: "\x1b[1;2R" }, + { mode: "\x1b[?1h\x1b=\x1b[?1l\x1b>", ctrlKey: true, expected: "\x1b[13;5~" }, + { mode: "\x1b[?1h\x1b=\x1b[>1u", ctrlKey: true, expected: "\x1b[13;5~" }, + ])( + "encodes modified F3 as $expected after $mode", + async ({ mode, ctrlKey = false, shiftKey = false, expected }) => { + const core = await createCore(); + core.write(mode); + const event = { + code: "F3", + key: "F3", + repeat: false, + shiftKey, + ctrlKey, + altKey: false, + metaKey: false, + isComposing: false, + getModifierState: () => false, + } as unknown as KeyboardEvent; + + expect(core.encodeKey(event)).toBe(expected); + }, + ); + it.each(["", "\x1b[>1u"])("encodes macOS Option text with keyboard mode %j", async (mode) => { using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); const core = await createCore(); diff --git a/apps/web/src/terminal/ghostty/core.ts b/apps/web/src/terminal/ghostty/core.ts index 119156cc5655..4bd4fd960951 100644 --- a/apps/web/src/terminal/ghostty/core.ts +++ b/apps/web/src/terminal/ghostty/core.ts @@ -162,6 +162,11 @@ export interface GhosttyMouseInput { readonly anyButtonPressed: boolean; } +// Ghostty sends modified F3 as CSI 13;m ~ to stay clear of cursor position reports, but the PTY +// advertises xterm-256color, whose kf15/kf27/... are CSI 1;m R. Terminfo keys only apply in +// keypad-transmit mode (smkx), so that mode marks a terminfo reader; raw parsers never set it. +const MODIFIED_F3 = /^\x1b\[13;(\d+)~$/; + const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); const encoder = new TextEncoder(); @@ -602,7 +607,9 @@ export class GhosttyTerminalCore { ); this.runtime.call("ghostty_wasm_free_usize", written); if (textPointer !== 0) this.runtime.free(textPointer, textBytes.length); - return encoded; + return MODIFIED_F3.test(encoded) && this.modeEnabled(66) && this.kittyKeyboardFlags() === 0 + ? encoded.replace(MODIFIED_F3, "\x1b[1;$1R") + : encoded; } encodePaste(data: string): string { @@ -1040,6 +1047,12 @@ export class GhosttyTerminalCore { } } + private kittyKeyboardFlags(): number { + this.runtime.bytes(this.scratch, 1)[0] = 0; + this.runtime.call("ghostty_terminal_get", this.terminal, 8, this.scratch); + return this.runtime.bytes(this.scratch, 1)[0]!; + } + /** Reads a DEC private mode; an unknown mode reads as off. */ private modeEnabled(mode: number): boolean { this.runtime.bytes(this.scratch, 1)[0] = 0; From d21d8d8b5df7ce2f07d27df05a410f9fcaf37f37 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Nov 2026 05:30:00 -0800 Subject: [PATCH 013/112] fix(mobile): iOS video previews keep their contain fit instead of sometimes cropping (#37186) --- apps/mobile/src/components/VideoThumbnailImage.tsx | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/components/VideoThumbnailImage.tsx b/apps/mobile/src/components/VideoThumbnailImage.tsx index f4ddb25a276f..2a031b54b44f 100644 --- a/apps/mobile/src/components/VideoThumbnailImage.tsx +++ b/apps/mobile/src/components/VideoThumbnailImage.tsx @@ -4,6 +4,7 @@ import { Atom, AsyncResult } from "effect/reactivity"; import { Image } from "expo-image"; import { useIsFocused } from "@react-navigation/native"; import type { VideoThumbnail } from "expo-video"; +import { useState } from "react"; import { StyleSheet } from "react-native"; import type { DraftComposerFileAttachment } from "../lib/composerImages"; @@ -49,13 +50,17 @@ export function VideoThumbnailImage(props: { const thumbnail = (loaded._tag === "Success" ? loaded.value : null) ?? cachedVideoThumbnail(cacheKey); - return thumbnail ? ( + // iOS draws a frame object the moment its prop is set, with the contentFit the view has then, + // and a later contentFit never refits it. Send the frame after mount so contentFit is set first. + const [laidOut, setLaidOut] = useState(false); + return ( setLaidOut(true)} + source={laidOut ? thumbnail : null} style={StyleSheet.absoluteFill} contentFit={props.contentFit ?? "cover"} recyclingKey={cacheKey} accessible={false} /> - ) : null; + ); } From 9c1dfbb5aaf3aab1a64a6bb4a98e06ad87fbdb81 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 15 Nov 2026 05:42:13 -0800 Subject: [PATCH 014/112] fix(server): delegate_task names the CLI version that hides a model (#37214) --- .../src/mcp/OrchestratorMcpService.test.ts | 9 ++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 28 +++++++++++++------ 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 40b5584e95ac..1be59bc41184 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -2512,6 +2512,10 @@ describe("OrchestratorMcpService provider resolution", () => { { slug: "claude-opus-4-1", isLegacy: true }, ...Array.from({ length: 9 }, (_, index) => ({ slug: `claude-opus-5-${index + 1}` })), ].map((model) => ({ ...model, name: model.slug, isCustom: false, capabilities: null })), + version: "2.1.302", + updateRequiredModels: [ + { slug: "claude-fable-5-2", name: "Claude Fable 5.2", minVersion: "2.1.321" }, + ], }, ]), adapterRegistryLayer([codexInstanceId]), @@ -2549,6 +2553,11 @@ describe("OrchestratorMcpService provider resolution", () => { "claude-opus-5-6, claude-opus-5-7, claude-opus-5-8 and 2 more; " + "orchestrator_capabilities with search finds them.", ); + + const updateRequired = yield* refuse("claude-fable-5-2"); + assert.equal(updateRequired.code, "model_unavailable"); + assert.include(updateRequired.message, "v2.1.302"); + assert.include(updateRequired.message, "2.1.321"); }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); }), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index cf5efb0ab333..19a413213633 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -395,16 +395,26 @@ const advertisedModel = (provider: ServerProvider, model: string) => candidate.aliases?.some((alias) => alias.toLowerCase() === model.toLowerCase()), ); +const withV = (version: string) => (version.startsWith("v") ? version : `v${version}`); + /** A provider that lists no models accepts any slug. */ -export const requireAdvertisedModel = (provider: ServerProvider, model: string) => - provider.models.length > 0 && advertisedModel(provider, model) === undefined - ? Effect.fail( - failure( - "model_unavailable", - `Model ${model} is not advertised by provider ${provider.instanceId}. ${advertisedModelsHint(provider.models, model)}`, - ), - ) - : Effect.void; +export const requireAdvertisedModel = (provider: ServerProvider, model: string) => { + if (provider.models.length === 0 || advertisedModel(provider, model) !== undefined) { + return Effect.void; + } + const updateRequired = provider.updateRequiredModels?.find( + (candidate) => candidate.slug === model, + ); + const detectedVersion = provider.installedVersion ?? provider.version; + return Effect.fail( + failure( + "model_unavailable", + updateRequired === undefined + ? `Model ${model} is not advertised by provider ${provider.instanceId}. ${advertisedModelsHint(provider.models, model)}` + : `Model ${model} needs provider ${provider.instanceId} at ${withV(updateRequired.minVersion)} or newer, but the detected CLI is ${detectedVersion === null ? "an unknown version" : withV(detectedVersion)}. Ask the user to update it or point the provider's binary path at a newer install.`, + ), + ); +}; function providerConstraints( provider: ServerProvider | undefined, From 0b489dada1f00db39c99074239c09c006f223aee Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:47:56 +0100 Subject: [PATCH 015/112] =?UTF-8?q?fix(web):=20switching=20a=20draft?= =?UTF-8?q?=E2=80=99s=20machine=20keeps=20its=20selected=20models=20(#3720?= =?UTF-8?q?8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Grok 4.7 Co-authored-by: Julius Marminge --- ...seDraftEnvironmentRouting.browser.test.tsx | 105 ++++++++++++++++-- .../chat/useDraftEnvironmentRouting.ts | 31 ++++-- ...achine-switch-keeps-selected-models.e2e.ts | 86 ++++++++++++++ ...moved-environment-closes-its-toasts.e2e.ts | 67 +---------- scripts/scenarios/second-server.ts | 68 ++++++++++++ 5 files changed, 275 insertions(+), 82 deletions(-) create mode 100644 scripts/scenarios/machine-switch-keeps-selected-models.e2e.ts create mode 100644 scripts/scenarios/second-server.ts diff --git a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx index 0dafee816711..3b23abfcb7c9 100644 --- a/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx +++ b/apps/web/src/components/chat/useDraftEnvironmentRouting.browser.test.tsx @@ -1,3 +1,5 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection"; import * as Option from "effect/Option"; import type { EnvironmentPresentation } from "../../state/environments"; @@ -20,26 +22,30 @@ import { expect, it, vi } from "vite-plus/test"; import { act, render } from "../../../test/render"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting"; -import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { appAtomRegistry, AppAtomRegistryProvider } from "../../rpc/atomRegistry"; import { draftFanoutSelectionsAtom } from "./chatViewSend"; const resources = vi.hoisted(() => ({ + projects: [] as EnvironmentProject[], + pickedEnvironmentId: null as EnvironmentId | null, refreshSelection: vi.fn<(ids: readonly EnvironmentId[]) => Promise>(), })); vi.mock("../../hooks/useLoadBalancedEnvironment", () => ({ useLoadBalancedEnvironment: () => ({ pending: false, failed: false, - environmentId: null, + environmentId: resources.pickedEnvironmentId, refresh: () => {}, refreshSelection: resources.refreshSelection, }), })); -vi.mock("../../state/entities", () => ({ useProjects: () => [] })); +vi.mock("../../state/entities", () => ({ useProjects: () => resources.projects })); vi.mock("../../hooks/useScratchProject", () => ({ useScratchProject: () => ({}) })); function setup() { resources.refreshSelection.mockReset(); + resources.projects = []; + resources.pickedEnvironmentId = null; const a = EnvironmentId.make("machine-a"); const b = EnvironmentId.make("machine-b"); const draftId = DraftId.make("fresh-routing-draft"); @@ -115,17 +121,40 @@ function setup() { return { a, b, draftId, input, store }; } -function Harness({ - input, - onPrepared, -}: { +interface HarnessProps { input: Parameters[0]; onPrepared?: (ready: boolean | null) => void; -}) { +} + +function Harness(props: HarnessProps) { + return ( + + + + ); +} + +function RoutingProbe({ input, onPrepared }: HarnessProps) { const routing = useDraftEnvironmentRouting(input); const draft = useComposerDraftStore((state) => state.getDraftSession(input.draftId!)); + const selections = useAtomValue( + draftFanoutSelectionsAtom( + scopedThreadKey(scopeThreadRef(draft!.environmentId, draft!.threadId)), + ), + ); return ( <> + + {selections?.map((selection) => selection.model).join(", ") ?? "single model"} + + {input.logicalProjectEnvironments.map(({ environmentId }) => ( + + ))} {draft?.environmentId}