From 159cdd9c05773723751c1db61833c87ce39e0c7b Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 13:11:23 +0900 Subject: [PATCH 001/208] fix(workbench): center the welcome screen again when there is no workspace The panel area is a one-cell grid. Since the agent view is kept mounted (85483699, v0.16.0) it holds that cell even while hidden, so the welcome screen, which had no placement of its own, was auto-placed into an implicit row below: an empty 1fr row on top, the welcome text squeezed to its own height at the bottom. Put it in the shared cell, as the workspace panels and the agent view are. Co-Authored-By: Claude Opus 5.5 --- src/renderer/app.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/renderer/app.tsx b/src/renderer/app.tsx index af3242b47..0dd5cb05d 100644 --- a/src/renderer/app.tsx +++ b/src/renderer/app.tsx @@ -311,8 +311,10 @@ export function App() { className="relative grid grid-cols-1 grid-rows-1 flex-1 min-w-0 overflow-hidden" {...{ [LOOK_AREA_ATTR]: "" }} > + {/* In the one cell, as the panels are: the agent view, kept + mounted there, would push it into a row of its own below. */} {workspaces.length === 0 && !agentView && ( -
+
)} From 8456889a5de55b6a2bebadfdace759422d66c575 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 13:30:45 +0900 Subject: [PATCH 002/208] fix(notes): number a recording's first voice 1, not 3 With voice prints, a line's key is only provisional until the model has heard it, and a new voice's key was picked past every key shown so far. At the start of a recording no voice is known yet, so lines that came in while the first was still being heard (the first one often long, the model loading) each took a new provisional key ("2", "3"), and the first voice was then numbered past them. A meeting came out as voices 3 and 4. The tracker now knows which lines are still being heard, and new keys are picked among the voices known: the first voice is 1, and the lines after it show 1 while they wait. Co-Authored-By: Claude Opus 5.5 --- src/renderer/services/notes/recorder.ts | 15 +++++++---- src/renderer/services/notes/voice-print.ts | 25 ++++++++++++++++--- .../services/notes/voice-print.test.ts | 19 +++++++++----- 3 files changed, 44 insertions(+), 15 deletions(-) diff --git a/src/renderer/services/notes/recorder.ts b/src/renderer/services/notes/recorder.ts index 77a3a6fcb..62101baf9 100644 --- a/src/renderer/services/notes/recorder.ts +++ b/src/renderer/services/notes/recorder.ts @@ -151,11 +151,15 @@ function recordingOf(a: Active): TranscriptRecording | undefined { .byNote[transcriptKey(a.workspaceId, a.noteId)]?.recordings.find((r) => r.id === a.recordingId); } -/** The voice keys a recording has, in its lines (but the one starting at `except`) and its names. */ -function keysOf(a: Active, except?: number): string[] { +/** + * The voice keys a recording has, in its lines and its names; not the keys of + * lines whose voice print is still being heard, which are only shown for now. + */ +function keysOf(a: Active): string[] { const r = recordingOf(a); if (!r) return []; - const lines = r.lines.filter((l) => l.startMs !== except); + const voices = a.voices; + const lines = voices ? r.lines.filter((l) => !voices.undecided(l.startMs)) : r.lines; return [...lines.map((l) => l.speaker), ...Object.keys(r.speakers)]; } @@ -208,8 +212,9 @@ function onEvent({ id, event }: VoiceEvent): void { void voices .lineHeard( { at: line.startMs, endAt: line.endMs, startMs, endMs, label }, - // Not its own key as shown so far, which it may keep as a new voice's. - () => keysOf(a, line.startMs), + // Not its own key as shown so far (nor those of the lines after it, + // still being heard), which it may keep as a new voice's. + () => keysOf(a), () => recordingOf(a)?.speakers ?? {}, ) .then(({ key, regrouped: keys }) => { diff --git a/src/renderer/services/notes/voice-print.ts b/src/renderer/services/notes/voice-print.ts index 3030c43fa..5f6c4cfa5 100644 --- a/src/renderer/services/notes/voice-print.ts +++ b/src/renderer/services/notes/voice-print.ts @@ -5,7 +5,10 @@ * voice it is nearest (or a new one). Every so often all the lines are * grouped again, which may move earlier lines to the voice they belong to. * Until its voice print is known, a line goes with the voice its server - * label had last. + * label had last. That key is only shown for now: a new voice's key is + * picked among the lines' voices that are known, so lines coming in while + * the first is still heard don't move the numbering on ("3" for the first + * voice, after two keys shown for a moment). */ import { liveVoice, @@ -59,6 +62,8 @@ export class VoiceTracker { private last: string | null = null; private lastRegroup = Number.NEGATIVE_INFINITY; private queue: Promise = Promise.resolve(); + /** The lines (by `at`) whose voice is still being worked out. */ + private readonly pending = new Set(); /** A new take: its audio starts over, and so do the server's labels. */ startTake(): void { @@ -80,11 +85,19 @@ export class VoiceTracker { this.heard += samples.length; } - /** The voice for words under `label` before their voice print is known. */ + /** + * The voice for words under `label` before their voice print is known. + * `taken` is the keys known: not those of the lines still `undecided`. + */ provisional(label: string, taken: Iterable): string { return this.byLabel.get(label) ?? this.last ?? nextVoiceKey(taken); } + /** Whether the line at `at` is still being heard: its key is only the one shown for now. */ + undecided(at: number): boolean { + return this.pending.has(at); + } + /** The take's audio from `startMs` to `endMs` (its first 10 s), or null when it is gone. */ private audioOf(startMs: number, endMs: number): Float32Array | null { const size = this.ring.length; @@ -103,7 +116,7 @@ export class VoiceTracker { /** * A line whose words are final: the voice it goes with, and, when all the * lines were grouped again, every line's voice by `at`. Lines are heard - * in the order they come. + * in the order they come; `taken` is the keys known, as `provisional`'s. */ lineHeard( line: HeardLine, @@ -113,6 +126,7 @@ export class VoiceTracker { // Its audio now, before the ring moves on. const audio = this.audioOf(line.startMs, line.endMs); const ms = line.endAt - line.at; + this.pending.add(line.at); const next = this.queue.then(async () => { const vector = audio ? await notesApi.voicePrint(audio).catch(() => null) : null; const key = liveVoice( @@ -121,6 +135,7 @@ export class VoiceTracker { taken(), this.byLabel.get(line.label) ?? this.last, ); + this.pending.delete(line.at); this.byLabel.set(line.label, key); this.last = key; if (vector) this.samples.push({ at: line.at, ms, vector, key }); @@ -131,7 +146,9 @@ export class VoiceTracker { } return { key: regrouped?.get(line.at) ?? key, regrouped }; }); - this.queue = next.catch(() => {}); + this.queue = next.catch(() => { + this.pending.delete(line.at); + }); return next; } diff --git a/tests/unit/renderer/services/notes/voice-print.test.ts b/tests/unit/renderer/services/notes/voice-print.test.ts index d9167062a..59a3889f2 100644 --- a/tests/unit/renderer/services/notes/voice-print.test.ts +++ b/tests/unit/renderer/services/notes/voice-print.test.ts @@ -43,6 +43,9 @@ describe("VoiceTracker", () => { heardMs = 0; }); + /** The keys known, as the recorder gives them: not those of lines still being heard. */ + const known = () => [...lines].filter(([at]) => !tracker.undecided(at)).map(([, k]) => k); + /** `who` says a line of `seconds` under the server's `label`: the voice it ends up with. */ async function say(who: number, seconds: number, label = "1"): Promise { const startMs = heardMs; @@ -55,12 +58,8 @@ describe("VoiceTracker", () => { endMs: heardMs, label, }; - lines.set(line.at, tracker.provisional(label, lines.values())); - const { key, regrouped } = await tracker.lineHeard( - line, - () => [...lines].filter(([at]) => at !== line.at).map(([, k]) => k), - () => ({}), - ); + lines.set(line.at, tracker.provisional(label, known())); + const { key, regrouped } = await tracker.lineHeard(line, known, () => ({})); for (const [at, k] of regrouped ?? []) if (lines.has(at)) lines.set(at, k); lines.set(line.at, key); return key; @@ -75,6 +74,14 @@ describe("VoiceTracker", () => { expect(tracker.provisional("1", lines.values())).toBe("3"); }); + test("numbers the first voice 1 when more lines come while it is still heard", async () => { + // A long first line, and two more right after it, before the model has heard the first. + const heard = [say(1, 22), say(1, 0.1), say(1, 9)]; + expect([...lines.values()]).toEqual(["1", "1", "1"]); + expect(await Promise.all(heard)).toEqual(["1", "1", "1"]); + expect(await say(2, 4)).toBe("2"); + }); + test("asks the model for at most 10 seconds of a line, and none for a short one", async () => { await say(1, 12); expect(asked).toEqual([VOICE_PRINT_RATE * 10]); From 198b53df898d4c81a725864811183f38342de3e6 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 13:32:32 +0900 Subject: [PATCH 003/208] fix(notes): keep the way back to everyone in sight while one person is shown A person's chip shows only their lines, and clicking it again shows everyone. But the chips are in the recording's heading, a row of the transcript that scrolls away as the lines are read, and Escape is not something to find, so getting the whole transcript back meant closing the panel and opening it again. The person picked is now shown in the transcript's header too, a chip that stays as the lines scroll; clicking it shows everyone again. Co-Authored-By: Claude Opus 5.5 --- .../components/notes/transcript-panel.tsx | 40 +++++++++++++++++-- .../components/notes/transcript-recording.tsx | 40 ++++++++++++++++++- .../notes/transcript-recording.test.tsx | 26 ++++++++++++ 3 files changed, 101 insertions(+), 5 deletions(-) create mode 100644 tests/unit/renderer/components/notes/transcript-recording.test.tsx diff --git a/src/renderer/components/notes/transcript-panel.tsx b/src/renderer/components/notes/transcript-panel.tsx index ca9952c08..1c64eef09 100644 --- a/src/renderer/components/notes/transcript-panel.tsx +++ b/src/renderer/components/notes/transcript-panel.tsx @@ -1,8 +1,9 @@ /** * A note's transcript, beside its text: each recording with its people and * what they said, a time to a line. While this note records, the words - * come in as they are said. A person's chip shows only what they said, and - * its pencil names them (the name goes to each of their voices); a search + * come in as they are said. A person's chip shows only what they said + * (shown above the lines too, which takes it back to everyone), and its + * pencil names them (the name goes to each of their voices); a search * shows the lines with its words; a line's time, while either holds, shows * that line in the whole conversation. A line is moved to another voice by * clicking its speaker, and goes into the note as a quote; a recording of @@ -44,10 +45,11 @@ import { import { useUIStore } from "../../state/stores/ui"; import type { DropdownMenuPoint } from "../ui/dropdown-menu"; import { LineMoveMenu, LineRow, type LineTarget, PartialRow } from "./transcript-line"; -import { RecordingHeading } from "./transcript-recording"; +import { PickedSpeaker, RecordingHeading } from "./transcript-recording"; import { type Cast, castOf, + isNamed, isNarrowed, isPicked, personOf, @@ -148,6 +150,23 @@ export const TranscriptPanel = memo(function TranscriptPanel({ searchToggleRef.current?.focus(); }, []); + // The person picked, as their chip names them: shown above the lines, which + // the recording's chips scroll away from. + const alone = useMemo(() => { + if (!speaker) return null; + const recording = recordings.find((r) => r.id === speaker.recordingId); + const p = casts.get(speaker.recordingId)?.people.find((x) => x.person === speaker.person); + if (recording && p) { + return { + name: speakerName(recording, p.keys[0] as string, unnamed), + color: speakerColor(p.color), + }; + } + // Gone from its recording (its voices grouped again): still the way back. + const { person } = speaker; + return { name: isNamed(person) ? person : unnamed(person.slice(1)), color: null }; + }, [speaker, recordings, casts, unnamed]); + const pick = useCallback((recordingId: string, person: string) => { setSpeaker((now) => (isPicked(now, recordingId, person) ? null : { recordingId, person })); }, []); @@ -337,9 +356,22 @@ export const TranscriptPanel = memo(function TranscriptPanel({
- + {t("transcript.title")} +
+ {alone && ( + { + setSpeaker(null); + // The chip goes; the keyboard stays in the transcript. + scroller.current?.focus({ preventScroll: true }); + }} + /> + )} +
{recordings.length > 0 && ( + ); +} diff --git a/tests/unit/renderer/components/notes/transcript-recording.test.tsx b/tests/unit/renderer/components/notes/transcript-recording.test.tsx new file mode 100644 index 000000000..b9b4a83c2 --- /dev/null +++ b/tests/unit/renderer/components/notes/transcript-recording.test.tsx @@ -0,0 +1,26 @@ +/** The person the transcript shows alone, above its lines. */ +import { describe, expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; + +const { PickedSpeaker } = await import( + "../../../../../src/renderer/components/notes/transcript-recording" +); + +describe("the picked person above the transcript", () => { + test("names them, and is the way back to everyone", () => { + const html = renderToStaticMarkup( + {}} />, + ); + expect(html).toContain("Speaker 3"); + expect(html).toContain('title="Everyone again"'); + expect(html).toContain("background:#4f8cff"); + }); + + test("without a color once their voices are grouped again", () => { + const html = renderToStaticMarkup( + {}} />, + ); + expect(html).toContain("Speaker 2"); + expect(html).not.toContain("rounded-full"); + }); +}); From cbb691b91e431e77847d0e6ee849a7051a302785 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 16:00:56 +0900 Subject: [PATCH 004/208] feat(cli): pull files from remote workspaces --- docs/CLI.md | 13 + src/main/features/cli/args.ts | 10 +- .../features/cli/commands/agent-context.ts | 1 + src/main/features/cli/commands/file.ts | 60 +++ src/main/features/cli/commands/index.ts | 2 + src/main/features/cli/commands/note.ts | 11 +- src/main/features/cli/context.ts | 1 + src/main/features/cli/file-pull.ts | 402 +++++++++++++++++ src/main/features/cli/index.ts | 4 +- src/main/features/cli/paths.ts | 6 + src/main/features/cli/registry.ts | 3 +- src/main/features/cli/remote.ts | 12 +- src/main/features/remote/index.ts | 4 +- src/main/features/remote/peer-file-reads.ts | 10 +- tests/unit/main/cli/control.test.ts | 7 +- tests/unit/main/cli/fake-services.ts | 11 +- tests/unit/main/cli/file-pull.test.ts | 406 ++++++++++++++++++ 17 files changed, 934 insertions(+), 29 deletions(-) create mode 100644 src/main/features/cli/commands/file.ts create mode 100644 src/main/features/cli/file-pull.ts create mode 100644 tests/unit/main/cli/file-pull.test.ts diff --git a/docs/CLI.md b/docs/CLI.md index 7d192d64a..128526101 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -193,6 +193,19 @@ nexus chat send 1a2b --device "Mac mini" --wait - # 그 컴퓨터의 탭에 - `workspace list --device` 는 그 컴퓨터의 워크스페이스 목록입니다. `--workspace` 에 쓸 이름을 여기서 봅니다. - 서브에이전트(`agent`), 브라우저, 화면 배치 · 에이전트 뷰, `worktree new`, 포트, `problems`, 워크스페이스 추가 · 이름 · 고정 · 순서는 이 컴퓨터에서만 됩니다. 다른 컴퓨터에 워크스페이스를 추가하는 일은 사용자만 합니다(원격 프로토콜이 에이전트의 요청을 받지 않습니다). +### 다른 컴퓨터에서 파일 가져오기 + +```bash +nexus file pull --device "Mac mini" --workspace site dist/report.pdf +nexus file pull --device "Windows PC" --workspace site -r 'C:/work/site/dist' ./snapshot --json +``` + +`file pull` 에는 기기와 원격 워크스페이스를 모두 지정합니다. 원격 상대 경로는 지정한 워크스페이스를 기준으로 해석합니다. 절대 경로에는 원격 기기의 기존 파일 공유 규칙이 적용됩니다. 워크스페이스 조회에는 `workspace list --device` 와 같은 권한이 필요합니다. + +앱이 실행 중인 컴퓨터의 로컬 워크스페이스에서 실행합니다. 로컬 대상은 CLI 의 작업 디렉터리를 기준으로 해석합니다. 대상을 생략하거나 기존 폴더를 지정하면 원래 이름으로 저장합니다. 각 파일은 전송을 마친 뒤 대상에 배치되며 기존 파일을 덮어씁니다. + +출력에는 저장 경로, 바이트 수, SHA-256 이 들어갑니다. `--json` 으로 기기와 원격 경로도 받을 수 있습니다. `-r` 의 JSON 결과는 파일과 건너뛴 링크의 배열이며 링크에는 `"skipped": "symlink"` 가 붙습니다. 원격 폴더 목록이 잘렸으면 복사를 시작하기 전에 실패합니다. + ## 세션의 에이전트 따라가기 Claude Code 세션 안의 서브에이전트와, 그 세션이 Bash 로 실행한 `claude -p` · `codex exec` 를 봅니다. 세션이 `claude -p` 나 `codex exec` 를 서브에이전트처럼 쓸 때 유용합니다. Codex 탭이 명령으로 실행한 `claude -p` · `codex exec` 도 그 탭의 실행으로 보입니다. diff --git a/src/main/features/cli/args.ts b/src/main/features/cli/args.ts index d7462bced..c9721b974 100644 --- a/src/main/features/cli/args.ts +++ b/src/main/features/cli/args.ts @@ -13,6 +13,8 @@ export interface FlagSpec { readonly description: string; /** A short name for the value in help, such as "N" or "URL". */ readonly value?: string; + /** A single-letter alias, spelled with one dash. */ + readonly short?: string; /** A string flag that may be given again: its values, in order, as a list. */ readonly repeat?: boolean; } @@ -57,12 +59,16 @@ export function parseArgs(argv: readonly string[], specs: Record specs[name]?.short === arg[1]) + : undefined; + if (!arg.startsWith("--") && short === undefined) { positionals.push(arg); continue; } const eq = arg.indexOf("="); - const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq); + const name = short ?? (eq === -1 ? arg.slice(2) : arg.slice(2, eq)); const spec = all[name]; if (!spec) throw new CliUsageError(`unknown flag --${name}`); let raw: string | undefined = eq === -1 ? undefined : arg.slice(eq + 1); diff --git a/src/main/features/cli/commands/agent-context.ts b/src/main/features/cli/commands/agent-context.ts index be745b9ba..f0fb4f45e 100644 --- a/src/main/features/cli/commands/agent-context.ts +++ b/src/main/features/cli/commands/agent-context.ts @@ -51,6 +51,7 @@ export function chatAgentContext( const remoteInstructions = [ "The user's other computers in the remote (nexus device list) are reached the same way:", "session list --device all, then chat or terminal read/send/wait ... --device NAME.", + "Copy remote files with nexus file pull --device DEVICE --workspace WS REMOTE [LOCAL] (add -r for a folder).", ]; function locationOf( diff --git a/src/main/features/cli/commands/file.ts b/src/main/features/cli/commands/file.ts new file mode 100644 index 000000000..9fbc20714 --- /dev/null +++ b/src/main/features/cli/commands/file.ts @@ -0,0 +1,60 @@ +import { CliError } from "../context"; +import { pull } from "../file-pull"; +import { type CliCommand, output } from "../registry"; +import { deviceFlag } from "../remote"; +import { WORKSPACE_FLAG } from "./flags"; + +const filePull: CliCommand = { + path: ["file", "pull"], + args: " [local-path]", + summary: "Copy a file from another NexusCode computer", + details: + "Give both --device and --workspace. Remote relative paths start at that workspace. Local relative paths start at this shell's cwd.", + flags: { + device: { + type: "string", + value: "DEVICE", + description: "The remote computer (id, id prefix or name)", + }, + workspace: { ...WORKSPACE_FLAG, description: "The remote workspace (id, id prefix or name)" }, + recursive: { type: "boolean", short: "r", description: "Copy a directory and its contents" }, + }, + async run(ctx, { positionals: [remotePath, localPath, ...extra], flags }) { + const device = deviceFlag(flags); + if (!device) throw new CliError("give --device to choose a remote computer", 2); + if (!remotePath || extra.length > 0 || localPath === "") { + throw new CliError("give [local-path]", 2); + } + const workspace = typeof flags.workspace === "string" ? flags.workspace : undefined; + const recursive = flags.recursive === true; + try { + const result = await pull(ctx, { + device, + remotePath, + recursive, + ...(workspace !== undefined ? { workspace } : {}), + ...(localPath !== undefined ? { localPath } : {}), + }); + const records = result.entries.map((entry) => ({ device: result.device, ...entry })); + const lines = result.entries.map((entry) => + "skipped" in entry + ? `Skipped symlink ${JSON.stringify(entry.remotePath)}` + : `${JSON.stringify(entry.path)} ${entry.size} bytes sha256 ${entry.sha256}`, + ); + return output( + lines.join("\n") || `Copied directory to ${JSON.stringify(result.destination)}`, + recursive ? records : records[0], + ); + } catch (error) { + if (ctx.signal?.aborted) throw new CliError("file pull cancelled", 3); + if (!(error instanceof Error)) throw error; + const message = error.message.replace(/[\r\n]+/g, " "); + if (message === error.message) throw error; + throw error instanceof CliError + ? new CliError(message, error.exitCode, error.json) + : new CliError(message); + } + }, +}; + +export const fileCommands: CliCommand[] = [filePull]; diff --git a/src/main/features/cli/commands/index.ts b/src/main/features/cli/commands/index.ts index c0d9df7a3..4e923d5c4 100644 --- a/src/main/features/cli/commands/index.ts +++ b/src/main/features/cli/commands/index.ts @@ -10,6 +10,7 @@ import { chatControlCommands } from "./chat-control"; import { deviceCommands } from "./device"; import { editorCommands } from "./editor"; import { eventCommands } from "./events"; +import { fileCommands } from "./file"; import { layoutCommands, tabArrangeCommands } from "./layout"; import { noteCommands } from "./note"; import { notifyCommands } from "./notify"; @@ -27,6 +28,7 @@ export const CLI_COMMANDS: readonly CliCommand[] = [ ...chatControlCommands, ...eventCommands, ...deviceCommands, + ...fileCommands, ...tabArrangeCommands, ...layoutCommands, ...viewCommands, diff --git a/src/main/features/cli/commands/note.ts b/src/main/features/cli/commands/note.ts index 66a77d80b..01d616465 100644 --- a/src/main/features/cli/commands/note.ts +++ b/src/main/features/cli/commands/note.ts @@ -11,7 +11,7 @@ import { noteMarkdown } from "../../notes/store"; import { CliUsageError, exactArgs, type ParsedArgs } from "../args"; import { type CliContext, CliError, mayChange, pick, resolveWorkspace } from "../context"; import { ago, oneLine, table } from "../format"; -import { callerPath } from "../paths"; +import { callerPath, onAppMachine } from "../paths"; import { type CliCommand, output } from "../registry"; import { WORKSPACE_FLAG } from "./flags"; @@ -22,15 +22,6 @@ function when(at: number, now: number): string { return new Date(at).toISOString().slice(0, 10); } -/** - * Whether the command runs in a terminal on the machine the app runs on (a - * local workspace's), where the notes' folders are. - */ -function onAppMachine(ctx: CliContext): boolean { - const own = ctx.services.listWorkspaces().find((w) => w.id === ctx.caller.workspaceId); - return own?.location.kind === "local"; -} - const NOTE_ARG_HELP = "A note is named by its id, an id prefix, or its title (as nexus note list shows them)."; diff --git a/src/main/features/cli/context.ts b/src/main/features/cli/context.ts index f0a90572e..81509d40a 100644 --- a/src/main/features/cli/context.ts +++ b/src/main/features/cli/context.ts @@ -67,6 +67,7 @@ export interface CliRemote { method: M, params: RpcParams, timeoutMs?: number, + signal?: AbortSignal, ): Promise>; } diff --git a/src/main/features/cli/file-pull.ts b/src/main/features/cli/file-pull.ts new file mode 100644 index 000000000..701a5a8bb --- /dev/null +++ b/src/main/features/cli/file-pull.ts @@ -0,0 +1,402 @@ +import { createHash, randomUUID } from "node:crypto"; +import { type FileHandle, lstat, mkdir, open, rename, stat, unlink } from "node:fs/promises"; +import path from "node:path"; +import { performance } from "node:perf_hooks"; +import { setTimeout as delay } from "node:timers/promises"; +import { + MAX_BYTES_CHUNK, + type RemoteWorkspace, + RpcErrorCode, + type RpcParams, + type RpcResult, +} from "../../../../packages/remote-protocol/src"; +import { bytesOf, supportsFileVersions } from "../remote/peer-file-reads"; +import { RpcFailure } from "../remote/room"; +import { type CliContext, type CliDevice, CliError } from "./context"; +import { callerPath, onAppMachine } from "./paths"; +import { + askDevice, + deviceRef, + offline, + peerSessions, + pickPeerWorkspace, + resolveDevice, +} from "./remote"; + +type FileMethod = "files.list" | "files.read"; +type FilePeer = ( + method: M, + params: Omit, "workspaceId">, + signal: AbortSignal, +) => Promise>; +type Bytes = Extract, { kind: "bytes" }>; +type Source = + | { kind: "file"; remotePath: string } + | { kind: "link"; remotePath: string } + | { kind: "dir"; remotePath: string; children: { name: string; source: Source }[] }; +type Copy = { path: string; source: Source }; + +interface SavedFile { + path: string; + remotePath: string; + size: number; + sha256: string; +} + +type PullEntry = SavedFile | { remotePath: string; skipped: "symlink" }; + +const PARALLEL_CHUNKS = 4; +// All pulls share the relay socket with chat and terminal traffic. Allow bursts +// of chunks, with room left in the relay's 50-frame-per-second budget. +const REQUESTS_PER_SECOND = 24; +const sent: number[] = []; +// Leave time to unwind before the hook server (35m) and client (36m) deadlines. +const PULL_TIMEOUT_MS = 34 * 60_000; + +async function waitForFileRequest(signal: AbortSignal): Promise { + for (;;) { + signal.throwIfAborted(); + const now = performance.now(); + while (sent.length > 0 && now - (sent[0] as number) >= 1000) sent.shift(); + if (sent.length < REQUESTS_PER_SECOND) { + sent.push(now); + return; + } + await delay(Math.ceil(1000 - (now - (sent[0] as number))), undefined, { signal }); + } +} + +function rpcMessage(error: unknown, code: number): string | undefined { + if (error instanceof CliError && error.cause instanceof RpcFailure && error.cause.code === code) { + return error.cause.message; + } +} + +function isFolder(error: unknown): boolean { + return ( + rpcMessage(error, RpcErrorCode.InvalidParams)?.endsWith("is a folder: files.list lists it") ?? + false + ); +} + +function changed(remotePath: string): CliError { + return new CliError(`${JSON.stringify(remotePath)} changed while copying`); +} + +async function readBytes( + peer: FilePeer, + remotePath: string, + offset: number, + length: number, + signal: AbortSignal, + generation?: Bytes, +): Promise { + const version = generation?.version; + let result: RpcResult<"files.read">; + try { + result = await peer( + "files.read", + { + path: remotePath, + as: "bytes", + offset, + length, + ...(version !== undefined + ? { requireVersion: version } + : length === 0 + ? { versioned: true } + : {}), + }, + signal, + ); + } catch (error) { + if ( + rpcMessage(error, RpcErrorCode.InvalidParams) === "file version changed" || + rpcMessage(error, RpcErrorCode.Unavailable) === "the file changed while it was being read" || + (generation && (isFolder(error) || rpcMessage(error, RpcErrorCode.NotFound) !== undefined)) + ) + throw changed(remotePath); + throw error; + } + if (result.kind !== "bytes") { + throw new CliError('the remote NexusCode does not support files.read as "bytes"', 3); + } + if ( + !Number.isSafeInteger(result.size) || + (generation && + (result.size !== generation.size || (version !== undefined && result.version !== version))) + ) + throw changed(remotePath); + try { + return bytesOf(result, offset, length); + } catch { + throw changed(remotePath); + } +} + +function validName(name: string, rules: path.PlatformPath): boolean { + if ( + !name || + name === "." || + name === ".." || + name.includes("\0") || + rules.basename(name) !== name + ) { + return false; + } + if (rules !== path.win32) return true; + return ( + !/[<>:"|?*]|[. ]$/.test(name) && + !Array.from(name).some((c) => c.charCodeAt(0) < 32) && + !/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]|conin\$|conout\$)(?:\.|$)/i.test(name) + ); +} + +async function listTree( + peer: FilePeer, + remotePath: string, + rules: path.PlatformPath, + signal: AbortSignal, +): Promise { + // Discover truncation anywhere in the tree before creating local entries. + const listing = await peer("files.list", { path: remotePath }, signal); + if (listing.truncated) { + throw new CliError(`directory listing for ${JSON.stringify(listing.path)} is truncated`); + } + const children: Extract["children"] = []; + for (const entry of listing.entries) { + if (!validName(entry.name, rules)) { + throw new CliError(`invalid entry name from the remote: ${JSON.stringify(entry.name)}`); + } + const child = rules.join(listing.path, entry.name); + const source = + entry.kind === "dir" + ? await listTree(peer, child, rules, signal) + : { kind: entry.kind, remotePath: child }; + children.push({ name: entry.name, source }); + } + return { kind: "dir", remotePath: listing.path, children }; +} + +async function localIO(destination: string, act: () => Promise): Promise { + try { + return await act(); + } catch (error) { + throw new CliError(`cannot write ${JSON.stringify(destination)}: ${(error as Error).message}`); + } +} + +function localChild(parent: string, name: string): string { + if (!validName(name, path)) { + throw new CliError(`cannot save the remote name ${JSON.stringify(name)} on this computer`); + } + return path.join(parent, name); +} + +async function destinationOf( + ctx: CliContext, + given: string | undefined, + sourceName: string, +): Promise { + if (given === undefined) return localChild(ctx.invocation.cwd, sourceName); + const destination = callerPath(ctx, given); + const existing = await localIO(destination, async () => { + try { + return await stat(destination); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + }); + return existing?.isDirectory() ? localChild(destination, sourceName) : destination; +} + +function planCopies(source: Source, destination: string, copies: Copy[]): void { + copies.push({ path: destination, source }); + if (source.kind !== "dir") return; + for (const { name, source: child } of source.children) { + planCopies(child, child.kind === "link" ? destination : localChild(destination, name), copies); + } +} + +async function makeDirectory(destination: string): Promise { + try { + await mkdir(destination); + } catch (error) { + if ( + (error as NodeJS.ErrnoException).code !== "EEXIST" || + !(await lstat(destination)).isDirectory() + ) { + throw error; + } + } +} + +async function writeChunk(file: FileHandle, bytes: Buffer, offset: number): Promise { + let written = 0; + while (written < bytes.length) { + const { bytesWritten } = await file.write( + bytes, + written, + bytes.length - written, + offset + written, + ); + if (bytesWritten === 0) throw new Error("the write made no progress"); + written += bytesWritten; + } +} + +async function copyFile( + peer: FilePeer, + remotePath: string, + destination: string, + first: Bytes, + signal: AbortSignal, +): Promise { + signal.throwIfAborted(); + const temporary = path.join(path.dirname(destination), `.nexus-pull-${randomUUID()}.tmp`); + const file = await localIO(destination, () => open(temporary, "wx", 0o600)); + const hash = createHash("sha256"); + const stopBatch = new AbortController(); + const pieceSignal = AbortSignal.any([signal, stopBatch.signal]); + let saved = false; + try { + try { + for (let offset = 0; offset < first.size; ) { + signal.throwIfAborted(); + const batch: Promise[] = []; + for (let i = 0; i < PARALLEL_CHUNKS && offset < first.size; i++) { + const at = offset; + const length = Math.min(MAX_BYTES_CHUNK, first.size - at); + batch.push( + (async () => { + const piece = await readBytes(peer, remotePath, at, length, pieceSignal, first); + const bytes = Buffer.from(piece.data, "base64"); + if (bytes.length !== length) throw changed(remotePath); + pieceSignal.throwIfAborted(); + await localIO(destination, () => writeChunk(file, bytes, at)); + return bytes; + })(), + ); + offset += length; + } + try { + for (const bytes of await Promise.all(batch)) hash.update(bytes); + } catch (error) { + stopBatch.abort(); + // No positioned write may outlive the file handle or cleanup. + await Promise.allSettled(batch); + throw error; + } + } + await readBytes(peer, remotePath, 0, first.version === undefined ? 1 : 0, signal, first); + } finally { + await localIO(destination, () => file.close()); + } + signal.throwIfAborted(); + await localIO(destination, () => rename(temporary, destination)); + saved = true; + return { + path: destination, + remotePath: first.path, + size: first.size, + sha256: hash.digest("hex"), + }; + } finally { + if (!saved) await localIO(destination, () => unlink(temporary)); + } +} + +function filePeer(ctx: CliContext, device: CliDevice, workspace: RemoteWorkspace): FilePeer { + return async ( + method: M, + params: Omit, "workspaceId">, + signal: AbortSignal, + ) => { + await waitForFileRequest(signal); + return askDevice( + ctx, + device, + method, + { ...params, workspaceId: workspace.id } as RpcParams, + signal, + ); + }; +} + +export async function pull( + ctx: CliContext, + options: { + device: string; + workspace?: string; + remotePath: string; + localPath?: string; + recursive: boolean; + }, +): Promise<{ device: ReturnType; destination: string; entries: PullEntry[] }> { + if (!onAppMachine(ctx)) { + throw new CliError("run file pull in a local workspace on the app's computer"); + } + const deadline = new AbortController(); + const timer = setTimeout( + () => deadline.abort(new CliError("file pull timed out", 3)), + PULL_TIMEOUT_MS, + ); + const signal = ctx.signal ? AbortSignal.any([ctx.signal, deadline.signal]) : deadline.signal; + try { + signal.throwIfAborted(); + const device = await resolveDevice(ctx, options.device); + if (!device) throw new CliError("give --device to choose a remote computer", 2); + if (!device.online) throw offline(device, ctx.services.clock.now()); + if (!device.serves.includes("files")) { + throw new CliError(`"${device.name}" does not share files (Settings › Remote)`); + } + const { workspaces } = await peerSessions(ctx, device, signal); + const workspace = pickPeerWorkspace(device, workspaces, options.workspace); + const peer = filePeer(ctx, device, workspace); + // The serving device also accepts UNC paths with forward slashes. + const rules = /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/])/.test(workspace.path) + ? path.win32 + : path.posix; + const metadataLength = supportsFileVersions(device.schema) ? 0 : 1; + let first: Bytes | undefined; + let source: Source; + try { + first = await readBytes(peer, options.remotePath, 0, metadataLength, signal); + source = { kind: "file", remotePath: options.remotePath }; + } catch (error) { + if (!isFolder(error)) throw error; + if (!options.recursive) { + throw new CliError( + `${JSON.stringify(options.remotePath)} is a directory (use -r to copy it)`, + ); + } + source = await listTree(peer, options.remotePath, rules, signal); + } + const destination = await destinationOf( + ctx, + options.localPath, + rules.basename(first?.path ?? source.remotePath), + ); + const copies: Copy[] = []; + planCopies(source, destination, copies); + const entries: PullEntry[] = []; + for (const { source: item, path: target } of copies) { + signal.throwIfAborted(); + if (item.kind === "dir") await localIO(target, () => makeDirectory(target)); + else if (item.kind === "link") + entries.push({ remotePath: item.remotePath, skipped: "symlink" }); + else { + const metadata = + first ?? (await readBytes(peer, item.remotePath, 0, metadataLength, signal)); + entries.push(await copyFile(peer, item.remotePath, target, metadata, signal)); + } + } + signal.throwIfAborted(); + return { device: deviceRef(device), destination, entries }; + } catch (error) { + signal.throwIfAborted(); + throw error; + } finally { + clearTimeout(timer); + } +} diff --git a/src/main/features/cli/index.ts b/src/main/features/cli/index.ts index e99d5e9e7..25496ef80 100644 --- a/src/main/features/cli/index.ts +++ b/src/main/features/cli/index.ts @@ -258,12 +258,12 @@ export function setupCliFeature(options: SetupCliFeatureOptions): CliFeature { remote: { inRoom: () => options.remote?.()?.inRoom() ?? false, devices: async () => (await options.remote?.()?.devices()) ?? [], - request: (deviceId, method, params, timeoutMs) => { + request: (deviceId, method, params, timeoutMs, signal) => { const remote = options.remote?.(); if (!remote) { throw new CliError("this computer is not in the remote room (Settings › Remote)", 3); } - return remote.request(deviceId, method, params, timeoutMs); + return remote.request(deviceId, method, params, timeoutMs, signal); }, }, consents, diff --git a/src/main/features/cli/paths.ts b/src/main/features/cli/paths.ts index 7bae99e84..eaae72e56 100644 --- a/src/main/features/cli/paths.ts +++ b/src/main/features/cli/paths.ts @@ -10,6 +10,12 @@ import { toSlashPath } from "../../../shared/fs/drive-path"; import type { WorkspaceMeta } from "../../../shared/types/workspace"; import { type CliContext, CliError } from "./context"; +/** Whether the caller's shell paths refer to the app's own filesystem. */ +export function onAppMachine(ctx: CliContext): boolean { + const own = ctx.services.listWorkspaces().find((w) => w.id === ctx.caller.workspaceId); + return own?.location.kind === "local"; +} + /** The path rules of the host `absolute` is a path on. */ function rulesOf(absolute: string): path.PlatformPath { return /^(?:[A-Za-z]:[\\/]|\\\\)/.test(absolute) ? path.win32 : path.posix; diff --git a/src/main/features/cli/registry.ts b/src/main/features/cli/registry.ts index e5858c1b7..a33ee2936 100644 --- a/src/main/features/cli/registry.ts +++ b/src/main/features/cli/registry.ts @@ -56,7 +56,8 @@ function usageLine(command: CliCommand): string { function flagLines(flags: Record): string[] { const rows = Object.entries(flags).map(([name, spec]) => { const value = spec.type === "boolean" ? "" : ` ${spec.value ?? spec.type.toUpperCase()}`; - return [`--${name}${value}`, spec.description] as const; + const short = spec.short ? `-${spec.short}, ` : ""; + return [`${short}--${name}${value}`, spec.description] as const; }); const width = Math.max(0, ...rows.map(([left]) => left.length)); return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`); diff --git a/src/main/features/cli/remote.ts b/src/main/features/cli/remote.ts index c6f990c57..9224f086e 100644 --- a/src/main/features/cli/remote.ts +++ b/src/main/features/cli/remote.ts @@ -197,7 +197,9 @@ export async function askDevice( device: CliDevice, method: M, given: RpcParams, + signal?: AbortSignal, ): Promise> { + signal?.throwIfAborted(); const now = ctx.services.clock.now(); if (!device.online) throw offline(device, now); // A read says who reads: a device whose user turned agents down is read by people alone. @@ -225,9 +227,12 @@ export async function askDevice( ? AGENT_REQUEST_MS : undefined; try { - return await ctx.services.remote.request(device.id, method, params, timeoutMs); + return await ctx.services.remote.request(device.id, method, params, timeoutMs, signal); } catch (error) { - throw failureOf(device, method, error, ctx.services.clock.now()); + signal?.throwIfAborted(); + const failure = failureOf(device, method, error, ctx.services.clock.now()); + if (failure !== error) failure.cause = error; + throw failure; } } @@ -235,8 +240,9 @@ export async function askDevice( export async function peerSessions( ctx: CliContext, device: CliDevice, + signal?: AbortSignal, ): Promise<{ workspaces: RemoteWorkspace[]; sessions: RemoteSession[] }> { - return askDevice(ctx, device, "sessions.list", {}); + return askDevice(ctx, device, "sessions.list", {}, signal); } /** The workspace a --workspace flag names on `device`; "." is no workspace there. */ diff --git a/src/main/features/remote/index.ts b/src/main/features/remote/index.ts index 9a98e6a70..9085644ab 100644 --- a/src/main/features/remote/index.ts +++ b/src/main/features/remote/index.ts @@ -963,8 +963,8 @@ export async function registerRemoteChannel(options: { }; }); }, - request: (deviceId, method, params, timeoutMs) => - inRoom().request(deviceId, method, params, timeoutMs), + request: (deviceId, method, params, timeoutMs, signal) => + inRoom().request(deviceId, method, params, timeoutMs, signal), }, dispose: () => { account.cancelSignIn(); diff --git a/src/main/features/remote/peer-file-reads.ts b/src/main/features/remote/peer-file-reads.ts index d82a5f74b..4c4c1c4dd 100644 --- a/src/main/features/remote/peer-file-reads.ts +++ b/src/main/features/remote/peer-file-reads.ts @@ -29,7 +29,9 @@ const MAX_FILE_BYTES = 8 * 1024 * 1024; const MAX_PENDING = 64; const MAX_WHOLE_READS = 4; const MAX_SPAN_READS = 32; -const FILE_VERSIONS = "0.13.4"; +export function supportsFileVersions(schema: string | undefined): boolean { + return speaks(schema, "0.13.4"); +} interface Entry { file: string; @@ -52,7 +54,7 @@ function changed(): RpcFailure { return new RpcFailure(RpcErrorCode.InvalidParams, "file version changed"); } -function bytesOf(result: Content, offset: number, length: number): Bytes { +export function bytesOf(result: Result, offset: number, length: number): Bytes { if ( result.kind !== "bytes" || result.offset !== offset || @@ -107,7 +109,7 @@ export class PeerFileReads { if ( !peer || scope.rejoins !== (peer.rejoins ?? 0) || - scope.versioned !== speaks(peer.schema, FILE_VERSIONS) || + scope.versioned !== supportsFileVersions(peer.schema) || scope.files !== peer.serves?.includes("files") ) { this.invalidateDevice(id); @@ -118,7 +120,7 @@ export class PeerFileReads { this.peers.set(id, { controller: new AbortController(), rejoins: peer.rejoins ?? 0, - versioned: speaks(peer.schema, FILE_VERSIONS), + versioned: supportsFileVersions(peer.schema), files: peer.serves?.includes("files"), }); } diff --git a/tests/unit/main/cli/control.test.ts b/tests/unit/main/cli/control.test.ts index 2977f6505..d37f13512 100644 --- a/tests/unit/main/cli/control.test.ts +++ b/tests/unit/main/cli/control.test.ts @@ -132,7 +132,7 @@ describe("changing another workspace", () => { expect(app.asked).toHaveLength(0); }); - // Every command that takes --workspace, as run on a busy "api" with the user + // Every command that takes a local --workspace, as run on a busy "api" with the user // saying no: one that changes it asks first and changes nothing, one that // reads it runs through without asking. A new command fails until it is here. const CHANGES = ` @@ -176,7 +176,10 @@ describe("changing another workspace", () => { .split(/[|\n]/) .map((line) => line.trim()) .filter(Boolean); - const paths = CLI_COMMANDS.filter((c) => c.flags?.workspace).map((c) => c.path.join(" ")); + // file pull.test.ts covers the remote-only --workspace on file pull. + const paths = CLI_COMMANDS.filter((c) => c.flags?.workspace) + .map((c) => c.path.join(" ")) + .filter((p) => p !== "file pull"); const commandOf = (line: string) => paths.filter((p) => `${line} `.startsWith(`${p} `)).sort((a, b) => b.length - a.length)[0]; const runs = [ diff --git a/tests/unit/main/cli/fake-services.ts b/tests/unit/main/cli/fake-services.ts index 98a5208b7..c12919f04 100644 --- a/tests/unit/main/cli/fake-services.ts +++ b/tests/unit/main/cli/fake-services.ts @@ -190,7 +190,12 @@ export interface FakeApp { inRoom: boolean; devices: CliDevice[]; requests: Array<{ deviceId: string; method: string; params: unknown; timeoutMs?: number }>; - answer: (deviceId: string, method: string, params: unknown) => Promise; + answer: ( + deviceId: string, + method: string, + params: unknown, + signal?: AbortSignal, + ) => Promise; }; /** Each terminal's screen as terminal.read gives it, by tab id; a test may change one. */ screens: Map; @@ -509,14 +514,14 @@ export function fakeApp(now = Date.now()): FakeApp { const remote: CliRemote = { inRoom: () => peers.inRoom, devices: async () => peers.devices, - request: async (deviceId, method, params, timeoutMs) => { + request: async (deviceId, method, params, timeoutMs, signal) => { peers.requests.push({ deviceId, method, params, ...(timeoutMs !== undefined ? { timeoutMs } : {}), }); - return (await peers.answer(deviceId, method, params)) as never; + return (await peers.answer(deviceId, method, params, signal)) as never; }, }; const noteAssets: FakeApp["noteAssets"] = []; diff --git a/tests/unit/main/cli/file-pull.test.ts b/tests/unit/main/cli/file-pull.test.ts new file mode 100644 index 000000000..b09d1004c --- /dev/null +++ b/tests/unit/main/cli/file-pull.test.ts @@ -0,0 +1,406 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { + MAX_BYTES_CHUNK, + RpcErrorCode, + type RpcParams, + type RpcResult, +} from "../../../../packages/remote-protocol/src"; +import { CLI_COMMANDS } from "../../../../src/main/features/cli/commands"; +import type { CliDevice } from "../../../../src/main/features/cli/context"; +import { runCli } from "../../../../src/main/features/cli/registry"; +import { RpcFailure } from "../../../../src/main/features/remote/room"; +import { API, contextFor, type FakeApp, fakeApp, SHELL_TAB } from "./fake-services"; + +const DEVICE: CliDevice = { + id: "face0001", + name: "Peer PC", + platform: "windows", + online: true, + self: false, + serves: ["files", "sessions", "agents"], + schema: "0.13.4", +}; +const WS = { id: "befa0001", name: "project", path: "C:/work/project" }; +const REMOTE = "C:\\work\\project\\out\\source.bin"; +const DATA = Buffer.from([1, 0, 255, 2, 3]); +const VERSION = "0123456789abcdef"; + +type Read = RpcParams<"files.read">; +type Listing = RpcResult<"files.list">; +type Reader = (read: Read, signal?: AbortSignal) => unknown; + +function piece(read: Read, data = DATA, remotePath = REMOTE, version: string | null = VERSION) { + const offset = read.offset ?? 0; + const length = read.length ?? MAX_BYTES_CHUNK; + return { + kind: "bytes", + path: remotePath, + size: data.length, + offset, + data: data.subarray(offset, offset + length).toString("base64"), + ...(version !== null ? { version } : {}), + }; +} + +function peer(reader: Reader = (read) => piece(read), listings: Record = {}) { + const app = fakeApp(); + app.peers.devices = [DEVICE]; + app.peers.answer = async (_id, method, params, signal) => { + if (method === "sessions.list") return { workspaces: [WS], sessions: [] }; + if (method === "files.read") return reader(params as Read, signal); + if (method === "files.list") { + const asked = (params as RpcParams<"files.list">).path; + if (listings[asked]) return listings[asked]; + throw new Error(`unexpected listing of ${asked}`); + } + throw new Error(`unexpected request ${method}`); + }; + return app; +} + +function fail(code: number, message: string): never { + throw new RpcFailure(code, message); +} + +function directory(asked: string): never { + return fail(RpcErrorCode.InvalidParams, `${asked} is a folder: files.list lists it`); +} + +function reads(app: FakeApp): Read[] { + return app.peers.requests.filter((r) => r.method === "files.read").map((r) => r.params as Read); +} + +let cwd: string; +beforeEach(async () => { + cwd = await mkdtemp(path.join(tmpdir(), "nexus-file-pull-")); +}); +afterEach(async () => { + await rm(cwd, { recursive: true, force: true }); +}); + +function run(app: FakeApp, args: string[], signal?: AbortSignal) { + const ctx = contextFor(app, ["file", "pull", ...args], undefined, { cwd }); + return runCli(CLI_COMMANDS, signal ? { ...ctx, signal } : ctx); +} + +function pull(app: FakeApp, ...args: string[]) { + return run(app, ["--device", "face", "--workspace", "befa", ...args]); +} + +function hash(data: Buffer): string { + return createHash("sha256").update(data).digest("hex"); +} + +test.each([ + "out/source.bin", + REMOTE, + "C:/work/project/out/source.bin", +])("passes %s to the Windows workspace and saves its basename", async (source) => { + const app = peer(); + const result = await pull(app, source, "--json"); + const target = path.join(cwd, "source.bin"); + expect(result.stderr).toBe(""); + expect(result.exitCode).toBe(0); + expect(result.files).toBeUndefined(); + expect(JSON.parse(result.stdout)).toEqual({ + device: { id: DEVICE.id, name: DEVICE.name }, + path: target, + remotePath: REMOTE, + size: DATA.length, + sha256: hash(DATA), + }); + expect(await readFile(target)).toEqual(DATA); + expect(reads(app).every((r) => r.path === source && r.workspaceId === WS.id)).toBe(true); +}); + +test("uses an existing directory or an explicit file name relative to the CLI cwd", async () => { + const folder = path.join(cwd, "downloads"); + await mkdir(folder); + const result = await pull(peer(), "source.bin", "downloads"); + expect(result.stderr).toBe(""); + expect(result.stdout).toContain(hash(DATA)); + expect(await readFile(path.join(folder, "source.bin"))).toEqual(DATA); + + const file = path.join(cwd, "renamed.bin"); + await writeFile(file, "old contents"); + expect((await pull(peer(), "source.bin", "renamed.bin")).stderr).toBe(""); + expect(await readFile(file)).toEqual(DATA); + expect((await readdir(cwd)).sort()).toEqual(["downloads", "renamed.bin"]); +}); + +test.skipIf(process.platform !== "win32")( + "uses the Git Bash temp path as a local directory", + async () => { + const app = peer(); + const ctx = contextFor( + app, + ["file", "pull", "--device", "Peer PC", "--workspace", "project", "source.bin", "/tmp"], + undefined, + { cwd, msysRoot: "C:\\Git", tempDir: cwd }, + ); + expect((await runCli(CLI_COMMANDS, ctx)).stderr).toBe(""); + expect(await readFile(path.join(cwd, "source.bin"))).toEqual(DATA); + }, +); + +test("starts four positioned chunk reads and assembles out-of-order answers", async () => { + const data = Buffer.concat( + [1, 2, 3, 4, 5, 6].map((part) => Buffer.alloc(part < 6 ? MAX_BYTES_CHUNK : 13, part)), + ); + let active = 0; + let peak = 0; + const completed: number[] = []; + const app = peer(async (request) => { + if (request.length === 0) return piece(request, data); + const offset = request.offset ?? 0; + peak = Math.max(++active, peak); + try { + await delay(offset === 0 ? 40 : 5); + completed.push(offset); + return piece(request, data); + } finally { + active--; + } + }); + const result = await pull(app, "source.bin", "--json"); + expect(result.stderr).toBe(""); + expect(peak).toBe(4); + expect(completed[0]).not.toBe(0); + expect(await readFile(path.join(cwd, "source.bin"))).toEqual(data); + expect(JSON.parse(result.stdout).sha256).toBe(hash(data)); + expect(reads(app)[0]).toMatchObject({ as: "bytes", length: 0, versioned: true }); + expect( + reads(app) + .slice(1) + .every((r) => r.requireVersion === VERSION), + ).toBe(true); + expect(reads(app).at(-1)).toMatchObject({ length: 0, requireVersion: VERSION }); +}); + +test("a changed version lets outstanding reads unwind and keeps the old file", async () => { + const data = Buffer.alloc(MAX_BYTES_CHUNK + 1, 42); + const saved = path.join(cwd, "source.bin"); + await writeFile(saved, "previous"); + let otherAborted = false; + const app = peer(async (request, signal) => { + if (!request.length) return piece(request, data); + if (!request.offset) { + await delay(5); + return fail(RpcErrorCode.InvalidParams, "file version changed"); + } + try { + await delay(2000, undefined, { signal }); + } finally { + otherAborted = signal?.aborted ?? false; + } + }); + const result = await pull(app, "source.bin"); + expect(result.stderr).toContain("changed while copying"); + expect(result.exitCode).not.toBe(0); + expect(otherAborted).toBe(true); + expect(await readFile(saved, "utf8")).toBe("previous"); + expect(await readdir(cwd)).toEqual(["source.bin"]); +}); + +test("a change after the data reads also prevents replacement", async () => { + const app = peer((request) => + piece( + request, + DATA, + REMOTE, + request.length === 0 && request.requireVersion ? "version-b" : VERSION, + ), + ); + expect((await pull(app, "source.bin")).stderr).toContain("changed while copying"); + expect(await readdir(cwd)).toEqual([]); +}); + +test("cancellation unwinds reads and removes the temporary file", async () => { + const controller = new AbortController(); + const app = peer(async (request, signal) => { + if (!request.length) return piece(request); + expect((await readdir(cwd))[0]).toMatch(/^\.nexus-pull-/); + controller.abort(); + signal?.throwIfAborted(); + throw new Error("cancellation did not reach remote.request"); + }); + const result = await run( + app, + ["--device", DEVICE.id, "--workspace", WS.id, "source.bin"], + controller.signal, + ); + expect(result.stderr).toContain("file pull cancelled"); + expect(result.exitCode).not.toBe(0); + expect(await readdir(cwd)).toEqual([]); +}); + +test("a failed rename leaves no temporary file", async () => { + await mkdir(path.join(cwd, "source.bin")); + const result = await pull(peer(), "source.bin"); + expect(result.stderr).toContain("cannot write"); + expect(result.exitCode).not.toBe(0); + expect(await readdir(cwd)).toEqual(["source.bin"]); +}); + +describe("recursive pull", () => { + const root = "C:\\work\\project"; + const nested = path.win32.join(root, "nested"); + const empty = path.win32.join(root, "empty"); + + function tree(truncated = false) { + return peer( + (read) => (read.path === "." ? directory(read.path) : piece(read, DATA, read.path)), + { + ".": { + path: root, + entries: [ + { kind: "file", name: "root.txt" }, + { kind: "dir", name: "nested" }, + { kind: "link", name: "shortcut" }, + { kind: "dir", name: "empty" }, + ], + }, + [nested]: { path: nested, entries: [{ kind: "file", name: "leaf.txt" }], truncated }, + [empty]: { path: empty, entries: [] }, + }, + ); + } + + test("keeps nested and empty directories and names skipped links", async () => { + const app = tree(); + const result = await pull(app, "-r", ".", "snapshot", "--json"); + expect(result.stderr).toBe(""); + const dest = path.join(cwd, "snapshot"); + expect((await stat(path.join(dest, "empty"))).isDirectory()).toBe(true); + expect(await readFile(path.join(dest, "root.txt"))).toEqual(DATA); + expect(await readFile(path.join(dest, "nested", "leaf.txt"))).toEqual(DATA); + expect((await readdir(dest)).sort()).toEqual(["empty", "nested", "root.txt"]); + expect(JSON.parse(result.stdout)).toEqual([ + expect.objectContaining({ + remotePath: path.win32.join(root, "root.txt"), + sha256: hash(DATA), + }), + expect.objectContaining({ + remotePath: path.win32.join(nested, "leaf.txt"), + sha256: hash(DATA), + }), + { + device: { id: DEVICE.id, name: DEVICE.name }, + remotePath: path.win32.join(root, "shortcut"), + skipped: "symlink", + }, + ]); + expect(reads(app).every((r) => !r.path.endsWith("shortcut"))).toBe(true); + }); + + test("refuses to copy any of a tree with a truncated nested listing", async () => { + const result = await pull(tree(true), "-r", "."); + expect(result.stderr).toContain("is truncated"); + expect(result.exitCode).not.toBe(0); + expect(await readdir(cwd)).toEqual([]); + }); + + test("requires -r for a directory", async () => { + const result = await pull(tree(), "."); + expect(result.stderr).toContain("is a directory (use -r to copy it)"); + expect(result.exitCode).not.toBe(0); + }); + + test("rejects a listing with an entry outside the destination", async () => { + const app = peer((read) => directory(read.path), { + ".": { path: root, entries: [{ kind: "file", name: "..\\outside.txt" }] }, + }); + expect((await pull(app, "-r", ".")).stderr).toContain("invalid entry name"); + expect(await readdir(cwd)).toEqual([]); + }); +}); + +describe("older hosts", () => { + test.each(["0.13.3", "0.13.4"])("copies from a versionless %s host", async (schema) => { + const app = peer((read) => piece(read, DATA, REMOTE, null)); + app.peers.devices = [{ ...DEVICE, schema }]; + const result = await pull(app, "source.bin"); + expect(result.stderr).toBe(""); + expect(await readFile(path.join(cwd, "source.bin"))).toEqual(DATA); + expect(reads(app)[0]?.length).toBe(schema === "0.13.4" ? 0 : 1); + expect( + reads(app) + .slice(1) + .every((r) => !r.versioned && !r.requireVersion), + ).toBe(true); + }); + + test("detects a size change without a version", async () => { + const app = peer((read) => + piece(read, read.length === 1 ? DATA : Buffer.concat([DATA, DATA]), REMOTE, null), + ); + app.peers.devices = [{ ...DEVICE, schema: "0.13.3" }]; + expect((await pull(app, "source.bin")).stderr).toContain("changed while copying"); + expect(await readdir(cwd)).toEqual([]); + }); + + test("reports an older host that ignores the bytes option", async () => { + const app = peer(() => ({ kind: "binary", path: REMOTE, size: DATA.length })); + expect((await pull(app, "source.bin")).stderr).toContain( + 'does not support files.read as "bytes"', + ); + expect(await readdir(cwd)).toEqual([]); + }); +}); + +test("requires a device and a workspace, as other remote creation commands do", async () => { + expect((await run(peer(), ["source.bin"])).stderr).toContain("give --device"); + expect((await run(peer(), ["source.bin", "--device", "Peer PC"])).stderr).toContain( + "give --workspace", + ); + expect((await run(peer(), ["--help"])).stdout).toContain("-r, --recursive"); +}); + +test("a shell on an SSH workspace cannot write to the app's host", async () => { + const app = peer(); + const at = app.workspaces.findIndex((workspace) => workspace.id === API); + const existing = app.workspaces[at]; + if (!existing) throw new Error("missing API workspace in fixture"); + app.workspaces[at] = { + ...existing, + location: { kind: "ssh", host: "box", remotePath: "/w/api" }, + }; + const ctx = contextFor( + app, + ["file", "pull", "--device", DEVICE.id, "--workspace", WS.id, "source.bin"], + { workspaceId: API, tabId: SHELL_TAB }, + { cwd }, + ); + expect((await runCli(CLI_COMMANDS, ctx)).stderr).toContain("run file pull in a local workspace"); + expect(app.peers.requests).toEqual([]); + expect(await readdir(cwd)).toEqual([]); +}); + +test("reports an offline device and a device with no files capability", async () => { + const app = peer(); + app.peers.devices = [{ ...DEVICE, online: false }]; + expect((await pull(app, "source.bin")).stderr).toContain('"Peer PC" is offline'); + app.peers.devices = [{ ...DEVICE, serves: ["sessions", "agents"] }]; + expect((await pull(app, "source.bin")).stderr).toContain('"Peer PC" does not share files'); + expect(app.peers.requests).toEqual([]); +}); + +test.each([ + [RpcErrorCode.Forbidden, "is outside the workspace's folders"], + [RpcErrorCode.NotFound, "does not exist"], + [RpcErrorCode.Unavailable, "files.read: no answer in time"], +])("explains a peer failure (%s) in one line", async (code, message) => { + const app = peer((read) => fail(code, `${read.path} ${message}`)); + const result = await pull(app, "parent/\nsource.bin"); + expect(result.stderr).toContain( + code === RpcErrorCode.Unavailable ? "did not answer in time" : message, + ); + expect(result.stderr.trimEnd().split("\n")).toHaveLength(1); + expect(result.exitCode).not.toBe(0); + expect(await readdir(cwd)).toEqual([]); +}); From e70d225c465287811822055a3ded59529d68618c Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 16:06:01 +0900 Subject: [PATCH 005/208] fix(cli): streamline remote file pulls --- src/main/features/cli/file-pull.ts | 106 +++++++++++++------- tests/unit/main/cli/file-pull.test.ts | 135 ++++++++++++++++++++------ 2 files changed, 176 insertions(+), 65 deletions(-) diff --git a/src/main/features/cli/file-pull.ts b/src/main/features/cli/file-pull.ts index 701a5a8bb..036bb92a2 100644 --- a/src/main/features/cli/file-pull.ts +++ b/src/main/features/cli/file-pull.ts @@ -29,7 +29,7 @@ type FilePeer = ( params: Omit, "workspaceId">, signal: AbortSignal, ) => Promise>; -type Bytes = Extract, { kind: "bytes" }>; +type Bytes = Omit, { kind: "bytes" }>, "data"> & { data: Buffer }; type Source = | { kind: "file"; remotePath: string } | { kind: "link"; remotePath: string } @@ -46,6 +46,8 @@ interface SavedFile { type PullEntry = SavedFile | { remotePath: string; skipped: "symlink" }; const PARALLEL_CHUNKS = 4; +const BUSY_RETRIES = 5; +const BUSY_RETRY_BASE_MS = 250; // All pulls share the relay socket with chat and terminal traffic. Allow bursts // of chunks, with room left in the relay's 50-frame-per-second budget. const REQUESTS_PER_SECOND = 24; @@ -85,27 +87,20 @@ function changed(remotePath: string): CliError { async function readBytes( peer: FilePeer, - remotePath: string, - offset: number, - length: number, + request: { path: string; offset: number; length: number; versioned?: true }, signal: AbortSignal, generation?: Bytes, ): Promise { + const { path: remotePath, offset, length } = request; const version = generation?.version; let result: RpcResult<"files.read">; try { result = await peer( "files.read", { - path: remotePath, + ...request, as: "bytes", - offset, - length, - ...(version !== undefined - ? { requireVersion: version } - : length === 0 - ? { versioned: true } - : {}), + ...(version !== undefined ? { requireVersion: version } : {}), }, signal, ); @@ -128,10 +123,15 @@ async function readBytes( ) throw changed(remotePath); try { - return bytesOf(result, offset, length); + bytesOf(result, offset, length); } catch { throw changed(remotePath); } + const data = Buffer.from(result.data, "base64"); + if (data.length !== Math.max(0, Math.min(length, result.size - offset))) { + throw changed(remotePath); + } + return { ...result, data }; } function validName(name: string, rules: path.PlatformPath): boolean { @@ -245,6 +245,17 @@ async function writeChunk(file: FileHandle, bytes: Buffer, offset: number): Prom } } +/** Use the current destination's mode when replacing a regular file. */ +async function destinationMode(destination: string): Promise { + try { + const existing = await lstat(destination); + if (existing.isFile()) return existing.mode & 0o7777; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + return 0o666 & ~process.umask(); +} + async function copyFile( peer: FilePeer, remotePath: string, @@ -261,7 +272,9 @@ async function copyFile( let saved = false; try { try { - for (let offset = 0; offset < first.size; ) { + await localIO(destination, () => writeChunk(file, first.data, 0)); + hash.update(first.data); + for (let offset = first.data.length; offset < first.size; ) { signal.throwIfAborted(); const batch: Promise[] = []; for (let i = 0; i < PARALLEL_CHUNKS && offset < first.size; i++) { @@ -269,12 +282,15 @@ async function copyFile( const length = Math.min(MAX_BYTES_CHUNK, first.size - at); batch.push( (async () => { - const piece = await readBytes(peer, remotePath, at, length, pieceSignal, first); - const bytes = Buffer.from(piece.data, "base64"); - if (bytes.length !== length) throw changed(remotePath); + const { data } = await readBytes( + peer, + { path: remotePath, offset: at, length }, + pieceSignal, + first, + ); pieceSignal.throwIfAborted(); - await localIO(destination, () => writeChunk(file, bytes, at)); - return bytes; + await localIO(destination, () => writeChunk(file, data, at)); + return data; })(), ); offset += length; @@ -288,7 +304,13 @@ async function copyFile( throw error; } } - await readBytes(peer, remotePath, 0, first.version === undefined ? 1 : 0, signal, first); + if (first.version === undefined) { + await readBytes(peer, { path: remotePath, offset: 0, length: 1 }, signal, first); + } + signal.throwIfAborted(); + if (process.platform !== "win32") { + await localIO(destination, async () => file.chmod(await destinationMode(destination))); + } } finally { await localIO(destination, () => file.close()); } @@ -312,14 +334,22 @@ function filePeer(ctx: CliContext, device: CliDevice, workspace: RemoteWorkspace params: Omit, "workspaceId">, signal: AbortSignal, ) => { - await waitForFileRequest(signal); - return askDevice( - ctx, - device, - method, - { ...params, workspaceId: workspace.id } as RpcParams, - signal, - ); + const request = { ...params, workspaceId: workspace.id } as RpcParams; + for (let retry = 0; ; retry++) { + await waitForFileRequest(signal); + try { + return await askDevice(ctx, device, method, request, signal); + } catch (error) { + if ( + method !== "files.read" || + retry >= BUSY_RETRIES || + rpcMessage(error, RpcErrorCode.Unavailable) !== "the host is busy reading files" + ) { + throw error; + } + } + await delay(BUSY_RETRY_BASE_MS * 2 ** retry, undefined, { signal }); + } }; } @@ -357,11 +387,22 @@ export async function pull( const rules = /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/])/.test(workspace.path) ? path.win32 : path.posix; - const metadataLength = supportsFileVersions(device.schema) ? 0 : 1; + const versioned = supportsFileVersions(device.schema); + const readFirst = (remotePath: string) => + readBytes( + peer, + { + path: remotePath, + offset: 0, + length: MAX_BYTES_CHUNK, + ...(versioned ? { versioned: true } : {}), + }, + signal, + ); let first: Bytes | undefined; let source: Source; try { - first = await readBytes(peer, options.remotePath, 0, metadataLength, signal); + first = await readFirst(options.remotePath); source = { kind: "file", remotePath: options.remotePath }; } catch (error) { if (!isFolder(error)) throw error; @@ -386,9 +427,8 @@ export async function pull( else if (item.kind === "link") entries.push({ remotePath: item.remotePath, skipped: "symlink" }); else { - const metadata = - first ?? (await readBytes(peer, item.remotePath, 0, metadataLength, signal)); - entries.push(await copyFile(peer, item.remotePath, target, metadata, signal)); + const head = first ?? (await readFirst(item.remotePath)); + entries.push(await copyFile(peer, item.remotePath, target, head, signal)); } } signal.throwIfAborted(); diff --git a/tests/unit/main/cli/file-pull.test.ts b/tests/unit/main/cli/file-pull.test.ts index b09d1004c..93c885ca1 100644 --- a/tests/unit/main/cli/file-pull.test.ts +++ b/tests/unit/main/cli/file-pull.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { createHash } from "node:crypto"; -import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { setTimeout as delay } from "node:timers/promises"; @@ -115,7 +115,16 @@ test.each([ sha256: hash(DATA), }); expect(await readFile(target)).toEqual(DATA); - expect(reads(app).every((r) => r.path === source && r.workspaceId === WS.id)).toBe(true); + expect(reads(app)).toEqual([ + { + workspaceId: WS.id, + path: source, + as: "bytes", + offset: 0, + length: MAX_BYTES_CHUNK, + versioned: true, + }, + ]); }); test("uses an existing directory or an explicit file name relative to the CLI cwd", async () => { @@ -133,6 +142,36 @@ test("uses an existing directory or an explicit file name relative to the CLI cw expect((await readdir(cwd)).sort()).toEqual(["downloads", "renamed.bin"]); }); +test("a file exactly one chunk long uses just one read", async () => { + const data = Buffer.alloc(MAX_BYTES_CHUNK, 42); + const app = peer((request) => piece(request, data)); + expect((await pull(app, "source.bin")).stderr).toBe(""); + expect(reads(app)).toHaveLength(1); + expect(await readFile(path.join(cwd, "source.bin"))).toEqual(data); +}); + +test.skipIf(process.platform === "win32")( + "applies umask to new files and preserves an existing file's mode", + async () => { + const target = path.join(cwd, "source.bin"); + expect((await pull(peer(), "source.bin")).stderr).toBe(""); + expect((await stat(target)).mode & 0o7777).toBe(0o666 & ~process.umask()); + + await chmod(target, 0o751); + const replacement = Buffer.from("replacement"); + expect( + ( + await pull( + peer((read) => piece(read, replacement)), + "source.bin", + ) + ).stderr, + ).toBe(""); + expect(await readFile(target)).toEqual(replacement); + expect((await stat(target)).mode & 0o7777).toBe(0o751); + }, +); + test.skipIf(process.platform !== "win32")( "uses the Git Bash temp path as a local directory", async () => { @@ -156,11 +195,11 @@ test("starts four positioned chunk reads and assembles out-of-order answers", as let peak = 0; const completed: number[] = []; const app = peer(async (request) => { - if (request.length === 0) return piece(request, data); + if (request.offset === 0) return piece(request, data); const offset = request.offset ?? 0; peak = Math.max(++active, peak); try { - await delay(offset === 0 ? 40 : 5); + await delay(offset === MAX_BYTES_CHUNK ? 40 : 5); completed.push(offset); return piece(request, data); } finally { @@ -170,26 +209,26 @@ test("starts four positioned chunk reads and assembles out-of-order answers", as const result = await pull(app, "source.bin", "--json"); expect(result.stderr).toBe(""); expect(peak).toBe(4); - expect(completed[0]).not.toBe(0); + expect(completed[0]).not.toBe(MAX_BYTES_CHUNK); expect(await readFile(path.join(cwd, "source.bin"))).toEqual(data); expect(JSON.parse(result.stdout).sha256).toBe(hash(data)); - expect(reads(app)[0]).toMatchObject({ as: "bytes", length: 0, versioned: true }); + expect(reads(app)).toHaveLength(6); + expect(reads(app)[0]).toMatchObject({ as: "bytes", length: MAX_BYTES_CHUNK, versioned: true }); expect( reads(app) .slice(1) .every((r) => r.requireVersion === VERSION), ).toBe(true); - expect(reads(app).at(-1)).toMatchObject({ length: 0, requireVersion: VERSION }); }); test("a changed version lets outstanding reads unwind and keeps the old file", async () => { - const data = Buffer.alloc(MAX_BYTES_CHUNK + 1, 42); + const data = Buffer.alloc(MAX_BYTES_CHUNK * 2 + 1, 42); const saved = path.join(cwd, "source.bin"); await writeFile(saved, "previous"); let otherAborted = false; const app = peer(async (request, signal) => { - if (!request.length) return piece(request, data); - if (!request.offset) { + if (request.offset === 0) return piece(request, data); + if (request.offset === MAX_BYTES_CHUNK) { await delay(5); return fail(RpcErrorCode.InvalidParams, "file version changed"); } @@ -207,27 +246,27 @@ test("a changed version lets outstanding reads unwind and keeps the old file", a expect(await readdir(cwd)).toEqual(["source.bin"]); }); -test("a change after the data reads also prevents replacement", async () => { +test("a chunk with a different version prevents replacement", async () => { + const data = Buffer.alloc(MAX_BYTES_CHUNK + 1, 42); const app = peer((request) => - piece( - request, - DATA, - REMOTE, - request.length === 0 && request.requireVersion ? "version-b" : VERSION, - ), + piece(request, data, REMOTE, request.offset ? "version-b" : VERSION), ); expect((await pull(app, "source.bin")).stderr).toContain("changed while copying"); expect(await readdir(cwd)).toEqual([]); }); -test("cancellation unwinds reads and removes the temporary file", async () => { +test("cancellation during busy backoff removes the temporary file", async () => { const controller = new AbortController(); - const app = peer(async (request, signal) => { - if (!request.length) return piece(request); - expect((await readdir(cwd))[0]).toMatch(/^\.nexus-pull-/); - controller.abort(); - signal?.throwIfAborted(); - throw new Error("cancellation did not reach remote.request"); + const data = Buffer.alloc(MAX_BYTES_CHUNK + 1, 42); + const app = peer(async (request) => { + if (request.offset === 0) return piece(request, data); + const [temporary] = await readdir(cwd); + expect(temporary).toMatch(/^\.nexus-pull-/); + if (process.platform !== "win32" && temporary) { + expect((await stat(path.join(cwd, temporary))).mode & 0o777).toBe(0o600 & ~process.umask()); + } + setImmediate(() => controller.abort()); + return fail(RpcErrorCode.Unavailable, "the host is busy reading files"); }); const result = await run( app, @@ -236,9 +275,36 @@ test("cancellation unwinds reads and removes the temporary file", async () => { ); expect(result.stderr).toContain("file pull cancelled"); expect(result.exitCode).not.toBe(0); + expect(reads(app)).toHaveLength(2); expect(await readdir(cwd)).toEqual([]); }); +test("retries a busy host and saves the complete file", async () => { + const data = Buffer.alloc(MAX_BYTES_CHUNK + 1, 42); + let attempts = 0; + const app = peer((request) => { + if (request.offset && ++attempts <= 2) { + return fail(RpcErrorCode.Unavailable, "the host is busy reading files"); + } + return piece(request, data); + }); + expect((await pull(app, "source.bin")).stderr).toBe(""); + expect(await readFile(path.join(cwd, "source.bin"))).toEqual(data); + expect(reads(app)).toHaveLength(4); + expect(reads(app).slice(1)).toEqual( + Array(3).fill(expect.objectContaining({ offset: MAX_BYTES_CHUNK, requireVersion: VERSION })), + ); +}); + +test("reports the busy error after five retries", async () => { + const app = peer(() => fail(RpcErrorCode.Unavailable, "the host is busy reading files")); + const result = await pull(app, "source.bin"); + expect(result.stderr).toContain("the host is busy reading files"); + expect(result.exitCode).not.toBe(0); + expect(reads(app)).toHaveLength(6); + expect(await readdir(cwd)).toEqual([]); +}, 12000); + test("a failed rename leaves no temporary file", async () => { await mkdir(path.join(cwd, "source.bin")); const result = await pull(peer(), "source.bin"); @@ -295,7 +361,11 @@ describe("recursive pull", () => { skipped: "symlink", }, ]); - expect(reads(app).every((r) => !r.path.endsWith("shortcut"))).toBe(true); + expect(reads(app).map((r) => r.path)).toEqual([ + ".", + path.win32.join(root, "root.txt"), + path.win32.join(nested, "leaf.txt"), + ]); }); test("refuses to copy any of a tree with a truncated nested listing", async () => { @@ -327,17 +397,17 @@ describe("older hosts", () => { const result = await pull(app, "source.bin"); expect(result.stderr).toBe(""); expect(await readFile(path.join(cwd, "source.bin"))).toEqual(DATA); - expect(reads(app)[0]?.length).toBe(schema === "0.13.4" ? 0 : 1); - expect( - reads(app) - .slice(1) - .every((r) => !r.versioned && !r.requireVersion), - ).toBe(true); + expect(reads(app)).toHaveLength(2); + expect(reads(app)[0]).toMatchObject({ offset: 0, length: MAX_BYTES_CHUNK }); + expect(reads(app)[0]?.versioned).toBe(schema === "0.13.4" ? true : undefined); + expect(reads(app)[1]).toMatchObject({ offset: 0, length: 1 }); + expect(reads(app)[1]?.versioned).toBeUndefined(); + expect(reads(app)[1]?.requireVersion).toBeUndefined(); }); test("detects a size change without a version", async () => { const app = peer((read) => - piece(read, read.length === 1 ? DATA : Buffer.concat([DATA, DATA]), REMOTE, null), + piece(read, read.length === 1 ? Buffer.concat([DATA, DATA]) : DATA, REMOTE, null), ); app.peers.devices = [{ ...DEVICE, schema: "0.13.3" }]; expect((await pull(app, "source.bin")).stderr).toContain("changed while copying"); @@ -402,5 +472,6 @@ test.each([ ); expect(result.stderr.trimEnd().split("\n")).toHaveLength(1); expect(result.exitCode).not.toBe(0); + expect(reads(app)).toHaveLength(1); expect(await readdir(cwd)).toEqual([]); }); From 42e33435c102c701bc4c0ed82455cdb9af4a7c5a Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 16:10:58 +0900 Subject: [PATCH 006/208] chore(scripts): sync Claude Code command checks --- scripts/check-agent-commands.ts | 92 +++++++++++++------ .../unit/scripts/check-agent-commands.test.ts | 30 ++++++ 2 files changed, 95 insertions(+), 27 deletions(-) diff --git a/scripts/check-agent-commands.ts b/scripts/check-agent-commands.ts index 5e6cfe463..3a0e30ebf 100644 --- a/scripts/check-agent-commands.ts +++ b/scripts/check-agent-commands.ts @@ -20,7 +20,11 @@ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "nod import { tmpdir } from "node:os"; import path from "node:path"; import { APP_COMMANDS, type AppCommand } from "../src/renderer/services/chat/app-commands"; -import { CONFIG_KEYS, parseConfigUsage } from "../src/renderer/services/chat/claude-config"; +import { + CONFIG_KEYS, + type ListedKey, + parseConfigUsage, +} from "../src/renderer/services/chat/claude-config"; import { CODEX_COMMANDS } from "../src/renderer/services/chat/codex-commands"; /** A command its definition turns off; the check says when it is on again. */ @@ -59,14 +63,30 @@ const CLAUDE_LEFT_OUT: Record = { "terminal-setup": TERMINAL, theme: TERMINAL, tui: TERMINAL, - // https://code.claude.com/docs/en/ultrareview - ultrareview: "an account-gated cloud review alias omitted by the headless slash catalog", "use-case": "an account-gated picker (Life Sciences)", version: OFF, voice: "dictation in the terminal", wellbeing: OFF, }; +/** Commands the tab gets from the CLI when its account and feature flags expose them. */ +const CLAUDE_LEFT_OUT_WHEN_UNAVAILABLE: Record = { + advisor: "chooses a second model for advice when the advisor tool is enabled", + "extra-usage": "the former name of /usage-credits, gated by the same billing options", + import: "imports another agent's configuration when the import feature is enabled", + "skill-doctor": "reports skill usage and context cost when feature-flag fetching is enabled", + ultrareview: "runs a cloud code review on eligible accounts", + "usage-credits": "manages usage credits or requests them from an admin on eligible accounts", +}; + +/** Keys a bare /config can omit when Claude Code is signed out. */ +const CLAUDE_SIGN_IN_CONFIG_KEYS = new Set([ + "remoteControl", + "agentPushNotifEnabled", + "inputNeededNotifEnabled", + "promptSuggestionEnabled", +]); + /** Claude Code's commands the tab could run and does not yet. */ const CLAUDE_LATER: Record = { restart: @@ -150,14 +170,14 @@ interface Report { notes: string[]; } -function run(command: string, args: string[]): string { +function run(command: string, args: string[], exitCodes: readonly number[] = [0]): string { const result = spawnSync(command, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: 120_000, }); if (result.error) throw result.error; - if (result.status !== 0) { + if (result.status === null || !exitCodes.includes(result.status)) { throw new Error( `${command} ${args.join(" ")} exited ${result.status}: ${result.stderr.trim()}`, ); @@ -308,7 +328,8 @@ function claudeHeadless(program: string): { commands: string[]; configUsage: str "-p", "--no-session-persistence", "--settings", - '{"disableAllHooks":true}', + // /config lists teammateMode only with agent teams enabled. + '{"disableAllHooks":true,"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"}}', "--output-format", "stream-json", "--verbose", @@ -334,40 +355,57 @@ function claudeHeadless(program: string): { commands: string[]; configUsage: str return { commands, configUsage }; } +function claudeSignedOut(program: string): boolean { + // auth status exits 1 when signed out. Require the JSON to confirm that state. + const status = JSON.parse(run(program, ["auth", "status", "--json"], [0, 1])) as { + loggedIn?: boolean; + }; + if (typeof status?.loggedIn !== "boolean") throw new Error("no loggedIn in claude auth status"); + return !status.loggedIn; +} + +/** Compare the keys the dialog gets from a bare /config with the table of value sources. */ +export function claudeConfigProblems(listed: readonly ListedKey[], signedOut: boolean): string[] { + if (listed.length === 0) return ["/config: no keys in a bare /config's answer"]; + const problems: string[] = []; + const listedKeys = new Set(listed.map((k) => k.key)); + const tableKeys = new Set(CONFIG_KEYS.map((k) => k.key)); + for (const key of listedKeys) { + if (!tableKeys.has(key)) { + problems.push( + `/config ${key}: new; the settings dialog shows it under Other, its value read from nowhere (CONFIG_KEYS)`, + ); + } + } + for (const key of tableKeys) { + if (listedKeys.has(key) || (signedOut && CLAUDE_SIGN_IN_CONFIG_KEYS.has(key))) continue; + problems.push(`/config ${key}: Claude Code no longer lists it (CONFIG_KEYS)`); + } + return problems; +} + function checkClaude(): Report { const program = findProgram("claude"); const version = run(program, ["--version"]).trim().split(/\s+/)[0]; const cli = claudeCommandsIn(readFileSync(program).toString("latin1")); const headless = claudeHeadless(program); + const fromCli = new Set(headless.commands); const { problems, notes } = accountFor("Claude Code", cli, { - fromCli: new Set(headless.commands), + fromCli, app: APP_COMMANDS, appTable: "APP_COMMANDS", - leftOut: CLAUDE_LEFT_OUT, + leftOut: { + ...CLAUDE_LEFT_OUT, + ...Object.fromEntries( + Object.entries(CLAUDE_LEFT_OUT_WHEN_UNAVAILABLE).filter(([name]) => !fromCli.has(name)), + ), + }, later: CLAUDE_LATER, appOnly: CLAUDE_APP_ONLY, }); - // The settings dialog shows every key a bare /config lists; the table - // says where each one's value is read. const listed = parseConfigUsage(headless.configUsage); - if (listed.length === 0) { - problems.push("/config: no keys in a bare /config's answer"); - } else { - const listedKeys = new Set(listed.map((k) => k.key)); - const tableKeys = new Set(CONFIG_KEYS.map((k) => k.key)); - for (const key of listedKeys) { - if (!tableKeys.has(key)) { - problems.push( - `/config ${key}: new; the settings dialog shows it under Other, its value read from nowhere (CONFIG_KEYS)`, - ); - } - } - for (const key of tableKeys) { - if (!listedKeys.has(key)) - problems.push(`/config ${key}: Claude Code no longer lists it (CONFIG_KEYS)`); - } - } + problems.push(...claudeConfigProblems(listed, claudeSignedOut(program))); notes.push(`/config: ${listed.length} keys, the table ${CONFIG_KEYS.length}`); return { title: `Claude Code ${version} (${program})`, problems, notes }; } diff --git a/tests/unit/scripts/check-agent-commands.test.ts b/tests/unit/scripts/check-agent-commands.test.ts index 4a57f8a2f..02929142a 100644 --- a/tests/unit/scripts/check-agent-commands.test.ts +++ b/tests/unit/scripts/check-agent-commands.test.ts @@ -1,10 +1,12 @@ import { describe, expect, test } from "bun:test"; import { claudeCommandsIn, + claudeConfigProblems, codexCommandsIn, codexMethodsIn, codexServiceTierCommandsIn, } from "../../../scripts/check-agent-commands"; +import { CONFIG_KEYS } from "../../../src/renderer/services/chat/claude-config"; describe("Claude Code's commands, as its bundle defines them", () => { test("the type before the name, with aliases; one turned off is told", () => { @@ -25,6 +27,34 @@ describe("Claude Code's commands, as its bundle defines them", () => { }); }); +describe("Claude Code's /config keys", () => { + const keysThatRequireSignIn = [ + "remoteControl", + "agentPushNotifEnabled", + "inputNeededNotifEnabled", + "promptSuggestionEnabled", + ]; + const signedOutKeys = CONFIG_KEYS.filter(({ key }) => !keysThatRequireSignIn.includes(key)); + + test("allows the sign-in keys to be missing only when signed out", () => { + expect(claudeConfigProblems(signedOutKeys, true)).toEqual([]); + expect(claudeConfigProblems(signedOutKeys, false)).toEqual( + keysThatRequireSignIn.map( + (key) => `/config ${key}: Claude Code no longer lists it (CONFIG_KEYS)`, + ), + ); + }); + + test("still flags missing ordinary keys and new keys when signed out", () => { + const listed = signedOutKeys.filter(({ key }) => key !== "theme"); + expect(claudeConfigProblems([...listed, { key: "newKey", kind: "boolean" }], true)).toEqual([ + "/config newKey: new; the settings dialog shows it under Other, its value read from nowhere (CONFIG_KEYS)", + "/config theme: Claude Code no longer lists it (CONFIG_KEYS)", + ]); + expect(claudeConfigProblems([], true)).toEqual(["/config: no keys in a bare /config's answer"]); + }); +}); + describe("Codex's commands, from its SlashCommand enum", () => { test("kebab-cased variants, unless strum names them", () => { const source = ` From de21f7ce10bd534d6fe56460d98126a6b0882d25 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 16:22:34 +0900 Subject: [PATCH 007/208] chore(lint): clear existing Biome warnings --- src/main/features/cli/commands/terminal.ts | 1 - src/renderer/services/chat/controller.ts | 2 +- src/renderer/services/chat/store.ts | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/features/cli/commands/terminal.ts b/src/main/features/cli/commands/terminal.ts index 19452570f..53e47c7aa 100644 --- a/src/main/features/cli/commands/terminal.ts +++ b/src/main/features/cli/commands/terminal.ts @@ -26,7 +26,6 @@ import { pickPeerWorkspace, resolveDevice, } from "../remote"; -import { senderOf } from "../sender"; import { DEFAULT_QUIET_MS, DEFAULT_WAIT_MS, diff --git a/src/renderer/services/chat/controller.ts b/src/renderer/services/chat/controller.ts index 6c0757a20..573badb84 100644 --- a/src/renderer/services/chat/controller.ts +++ b/src/renderer/services/chat/controller.ts @@ -1057,7 +1057,7 @@ export class ChatController { from?: RelaySender, id?: string, queued = false, - ): Promise { + ): Promise { if (!(await this.ensureRunning())) { if (id) throw new Error("Claude is not running"); return; diff --git a/src/renderer/services/chat/store.ts b/src/renderer/services/chat/store.ts index ee363594e..3f594a4bd 100644 --- a/src/renderer/services/chat/store.ts +++ b/src/renderer/services/chat/store.ts @@ -40,7 +40,7 @@ export interface QueuedMessage { export function dispatchQueuedMessage( queue: readonly QueuedMessage[], update: (change: (prev: ChatTabState) => ChatTabState) => void, - send: (item: QueuedMessage) => Promise, + send: (item: QueuedMessage) => Promise, rejected: (error: unknown) => boolean, observed: (id: string) => boolean, settled: () => void, From c51a39d588eb37bfeb8c1853e9afc71bb75bceb3 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 16:22:49 +0900 Subject: [PATCH 008/208] fix(browser): restore visibility after tab reattachment --- src/main/features/browser/ipc.ts | 18 +- src/main/features/browser/registry.ts | 135 +++++-------- src/shared/ipc/contract.ts | 14 +- .../main/features/browser/registry.test.ts | 188 ++++++++++++++++++ 4 files changed, 249 insertions(+), 106 deletions(-) create mode 100644 tests/unit/main/features/browser/registry.test.ts diff --git a/src/main/features/browser/ipc.ts b/src/main/features/browser/ipc.ts index 303c4f9b9..f75b80a34 100644 --- a/src/main/features/browser/ipc.ts +++ b/src/main/features/browser/ipc.ts @@ -256,29 +256,17 @@ export function registerBrowserChannel( suspendAll: async (args: unknown) => { const { captureSnapshot } = validateArgs(c.suspendAll.args, args); - // The registry's suspendAll captures BEFORE hiding (VSCode pattern) so - // the renderer can overlay each snapshot on top of the still-visible - // placeholder before the native view goes dark — no flash, no blank. + // Capture before hiding so the renderer can show the last frame under the overlay. const snapshots = await registry.suspendAll({ captureSnapshot }); for (const { tabId, dataUrl } of snapshots) { - // Only broadcast when capture succeeded and produced a usable - // payload; tiny/empty captures arrive as null and the renderer - // keeps the prior placeholder without harm. - if (dataUrl !== null) { - broadcast("browser", "snapshot", { kind: "set", tabId, dataUrl }); - } + broadcast("browser", "snapshot", { kind: "set", tabId, dataUrl }); } return ipcOk(undefined); }, resumeAll: (args: unknown) => { validateArgs(c.resumeAll.args, args); - const resumed = registry.resumeAll(); - for (const tabId of resumed) { - // Drop the cached snapshot in the renderer so the live view shows - // through again. Sent even when no snapshot was previously - // broadcast for this tab (e.g. drag-mode suspend with - // captureSnapshot=false) — harmless on the renderer side. + for (const tabId of registry.resumeAll()) { broadcast("browser", "snapshot", { kind: "cleared", tabId }); } return ipcOk(undefined); diff --git a/src/main/features/browser/registry.ts b/src/main/features/browser/registry.ts index 8db631cb1..570d87f59 100644 --- a/src/main/features/browser/registry.ts +++ b/src/main/features/browser/registry.ts @@ -4,8 +4,7 @@ * * LIFECYCLE * --------- - * create() — allocates a WebContentsView, applies security policy, and - * attaches it to the main window's contentView. + * create() — allocates a detached WebContentsView and applies security policy. * destroy() — closes the WebContents, detaches the view, removes the entry. * setActive() — attach (active=true) or detach (active=false) the view. * setBounds() — resize/reposition. Renderer sends CSS-layout pixels; we @@ -15,7 +14,7 @@ * needs no conversion. * suspendAll() — capture (optional) + hide every active view so DOM * overlays (modals/menus/drag indicators) can render above. - * resumeAll() — show every previously-active view. + * resumeAll() — show every currently active view and clear snapshots. * * SUSPEND VS SETACTIVE * -------------------- @@ -79,16 +78,11 @@ interface TabEntry { /** * Whether this tab is the active tab in its group. * - * The view is actually attached to the window iff `active && !registry.suspended`. - * Decoupling these two flags lets the global suspendAll/resumeAll cycle - * detach every active view temporarily without losing the per-tab activation - * state we restore on resume. + * Active views stay attached while an overlay temporarily hides them. */ active: boolean; /** - * Last bounds applied via setBounds(). Cached so resumeAll() can re-apply - * them after re-attaching — Electron does NOT preserve bounds across - * remove/addChildView pairs. + * Last CSS bounds applied via setBounds(), restored on reattach. */ lastBounds: CssBounds | null; /** @@ -102,7 +96,7 @@ interface TabEntry { /** * Last bounds applied via `setDevToolsBounds`. Same role as `lastBounds` * — re-applied whenever the devtools view is re-attached after a - * suspend/resume or setActive(true) cycle. + * setActive(true) or DevTools toggle. */ devtoolsBounds: CssBounds | null; /** @@ -143,10 +137,10 @@ export interface BrowserAddressResolver { resolve(workspaceId: string, url: string): Promise; } -/** One snapshot result for `suspendAll` — `dataUrl` is null when capture failed. */ -export interface SuspendSnapshot { +/** A usable page snapshot captured by `suspendAll`. */ +interface SuspendSnapshot { tabId: string; - dataUrl: string | null; + dataUrl: string; } export class BrowserTabRegistry { @@ -174,6 +168,8 @@ export class BrowserTabRegistry { * be visible. */ private suspendGeneration = 0; + /** Tabs whose overlay snapshot needs clearing on resume, even after detaching. */ + private readonly snapshotTabs = new Set(); /** Told of each tab's WebContents as it is created, before its first page loads. */ private readonly createListeners = new Set<(tabId: string, contents: WebContents) => void>(); private addressResolver: BrowserAddressResolver | null = null; @@ -190,8 +186,7 @@ export class BrowserTabRegistry { // ------------------------------------------------------------------------- /** - * Creates a new WebContentsView for `tabId`, navigates it to `url`, and - * adds it (hidden initially) to the main window's contentView hierarchy. + * Creates a detached WebContentsView for `tabId` and navigates it to `url`. * * If a view for `tabId` already exists it is destroyed before the new one * is created — see class doc for the rationale. @@ -374,6 +369,7 @@ export class BrowserTabRegistry { } this.tabs.delete(tabId); + this.snapshotTabs.delete(tabId); logger.debug(`[destroy] tab ${tabId} destroyed`); } @@ -420,10 +416,7 @@ export class BrowserTabRegistry { return; } - // Cache so resumeAll() can re-apply after a suspend/resume cycle — - // Electron does not preserve bounds across removeChildView/addChildView. - // Cached in CSS px (verbatim from the renderer) so a later re-apply picks - // up the *current* zoom factor, not the one in effect when this arrived. + // Keep CSS pixels so reattachment uses the current shell zoom factor. entry.lastBounds = { x, y, width, height }; this.applyCssBounds(entry.view, entry.lastBounds); @@ -470,16 +463,10 @@ export class BrowserTabRegistry { /** * Activates or deactivates the view for `tabId`. * - * Active → view is added to the main window's contentView (unless the - * registry is currently suspended), background throttling is - * disabled so animations stay smooth. + * Active → view is added to the main window's contentView and follows + * the current suspend state. Background throttling is disabled. * Inactive → view is removed from the main window's contentView, background * throttling is enabled to conserve CPU/GPU resources. - * - * The actual attachment depends on `active && !this.suspended` — during a - * global suspend window (open dropdown / modal / drag) every active view is - * detached on the registry side without disturbing the per-tab `active` - * flag, so `resumeAll` can restore exactly the same set. */ setActive(args: { tabId: string; active: boolean }): void { const { tabId, active } = args; @@ -502,16 +489,6 @@ export class BrowserTabRegistry { if (entry.devtoolsOpen && entry.devtoolsView !== null) { this.attachAndRestoreDevtoolsBounds(entry); } - // If the registry is currently suspended (an overlay is in progress), - // immediately hide the freshly-attached view so it doesn't paint above - // the modal. resumeAll() will call setVisible(true) once the overlay - // closes. - if (this.suspended && !entry.view.webContents.isDestroyed()) { - entry.view.setVisible(false); - if (entry.devtoolsView !== null && !entry.devtoolsView.webContents.isDestroyed()) { - entry.devtoolsView.setVisible(false); - } - } entry.view.webContents.setBackgroundThrottling(false); } else { this.safeRemoveChildView(entry); @@ -531,6 +508,8 @@ export class BrowserTabRegistry { * the view would reappear at (0, 0) sized 0×0. */ private attachAndRestoreBounds(entry: TabEntry): void { + // An overlay may have ended while the view was detached. + entry.view.setVisible(!this.suspended); this.win.contentView.addChildView(entry.view); const b = entry.lastBounds; if (b) { @@ -558,6 +537,7 @@ export class BrowserTabRegistry { private attachAndRestoreDevtoolsBounds(entry: TabEntry): void { const dt = entry.devtoolsView; if (dt === null) return; + dt.setVisible(!this.suspended); this.win.contentView.addChildView(dt); const b = entry.devtoolsBounds; if (b !== null) { @@ -614,25 +594,22 @@ export class BrowserTabRegistry { this.suspended = true; const gen = ++this.suspendGeneration; - const activeEntries: Array<[string, TabEntry]> = []; + const activeEntries = new Map(); for (const [tabId, entry] of this.tabs) { if (entry.active && !entry.view.webContents.isDestroyed()) { - activeEntries.push([tabId, entry]); + activeEntries.set(tabId, entry); } } - let snapshots: SuspendSnapshot[] = []; - if (opts.captureSnapshot) { - snapshots = await this.captureActiveSnapshots(activeEntries); - } + const snapshots = opts.captureSnapshot ? await this.captureActiveSnapshots(activeEntries) : []; // Bail if resumeAll ran while we were capturing — the view is supposed // to be visible now, hiding here would re-introduce the blank area the // user just dismissed. if (gen !== this.suspendGeneration) return []; - for (const [, entry] of activeEntries) { - if (entry.view.webContents.isDestroyed()) continue; + for (const entry of activeEntries.values()) { + if (!entry.active || entry.view.webContents.isDestroyed()) continue; entry.view.setVisible(false); // Mirror the hide onto the DevTools host view so its OS-level overlay // doesn't paint above a DOM modal either. @@ -645,16 +622,16 @@ export class BrowserTabRegistry { } } - return snapshots; + return snapshots.filter(({ tabId }) => { + if (this.tabs.get(tabId) !== activeEntries.get(tabId)) return false; + this.snapshotTabs.add(tabId); + return true; + }); } /** - * Re-show every WebContentsView that was active when the matching - * `suspendAll` ran. - * - * Returns the list of tabIds that were re-shown — the caller broadcasts a - * `snapshot {cleared: true}` event for each so the renderer drops its - * cached image and exposes the live view again. + * Re-show currently attached views and return the IDs of all tabs with + * snapshots to clear, including tabs that detached during the overlay. */ resumeAll(): string[] { if (!this.suspended) return []; @@ -662,8 +639,7 @@ export class BrowserTabRegistry { // Bump generation so any in-flight suspendAll capture skips its hide step. this.suspendGeneration++; - const resumed: string[] = []; - for (const [tabId, entry] of this.tabs) { + for (const entry of this.tabs.values()) { if (entry.active && !entry.view.webContents.isDestroyed()) { entry.view.setVisible(true); if ( @@ -673,10 +649,11 @@ export class BrowserTabRegistry { ) { entry.devtoolsView.setVisible(true); } - resumed.push(tabId); } } - return resumed; + const snapshotTabs = [...this.snapshotTabs]; + this.snapshotTabs.clear(); + return snapshotTabs; } /** @@ -686,33 +663,32 @@ export class BrowserTabRegistry { * returns from `nativeImage.toDataURL()`, which matters because the result * crosses the IPC boundary as a broadcast payload to the renderer. * - * `dataUrl` is set to `null` when capture failed, returned an empty image - * (page not yet rendered), or produced a payload too small to be a real - * page snapshot — the renderer treats `null` as "no overlay available" - * and keeps the existing placeholder. + * Failed, empty, and very small captures leave the existing placeholder visible. */ private async captureActiveSnapshots( - activeEntries: Array<[string, TabEntry]>, + activeEntries: ReadonlyMap, ): Promise { const TINY_DATA_URL_THRESHOLD = 2_000; // ~150x150 solid-colour JPEG floor - const captures = activeEntries.map(async ([tabId, entry]): Promise => { - try { - const img = await entry.view.webContents.capturePage(); - if (img.isEmpty()) return { tabId, dataUrl: null }; - const buf = img.toJPEG(75); - const dataUrl = `data:image/jpeg;base64,${buf.toString("base64")}`; - if (dataUrl.length < TINY_DATA_URL_THRESHOLD) { - return { tabId, dataUrl: null }; + const captures = [...activeEntries].map( + async ([tabId, entry]): Promise => { + try { + const img = await entry.view.webContents.capturePage(); + if (img.isEmpty()) return null; + const buf = img.toJPEG(75); + const dataUrl = `data:image/jpeg;base64,${buf.toString("base64")}`; + if (dataUrl.length < TINY_DATA_URL_THRESHOLD) { + return null; + } + return { tabId, dataUrl }; + } catch (err) { + logger.warn(`[suspendAll] capturePage failed for ${tabId}: ${(err as Error).message}`); + return null; } - return { tabId, dataUrl }; - } catch (err) { - logger.warn(`[suspendAll] capturePage failed for ${tabId}: ${(err as Error).message}`); - return { tabId, dataUrl: null }; - } - }); + }, + ); - return Promise.all(captures); + return (await Promise.all(captures)).filter((snapshot) => snapshot !== null); } // ------------------------------------------------------------------------- @@ -818,11 +794,6 @@ export class BrowserTabRegistry { // bounds yet — that's fine, attach lazily on the next setActive(true). if (entry.active) { this.attachAndRestoreDevtoolsBounds(entry); - // Mirror the suspend state — a global suspendAll may be in progress - // when the user opens DevTools (unlikely but harmless to handle). - if (this.suspended && !entry.devtoolsView.webContents.isDestroyed()) { - entry.devtoolsView.setVisible(false); - } } entry.view.webContents.setDevToolsWebContents(entry.devtoolsView.webContents); diff --git a/src/shared/ipc/contract.ts b/src/shared/ipc/contract.ts index cbac660ca..e7ec38116 100644 --- a/src/shared/ipc/contract.ts +++ b/src/shared/ipc/contract.ts @@ -1873,11 +1873,9 @@ export const ipcContract = { * * Mechanism follows the VSCode pattern: when `captureSnapshot` is true * the main process first calls `webContents.capturePage()` on every - * active view, broadcasts the resulting JPEG dataURL via - * `browser.snapshot`, and only then hides the view via - * `setVisible(false)`. The renderer overlays the snapshot in DOM, so - * the area underneath the modal still shows the page content rather - * than going blank. + * active view and hides the view via `setVisible(false)`. The resulting + * JPEG data URL is broadcast via `browser.snapshot`. The renderer shows + * the snapshot beneath the overlay. * * `captureSnapshot: false` skips the capture entirely and hides * immediately — used by drag operations where any delay would break @@ -1891,10 +1889,8 @@ export const ipcContract = { */ suspendAll: call(z.object({ captureSnapshot: z.boolean() }), z.void()), /** - * Re-show every WebContentsView that was active when the matching - * `suspendAll` ran via `setVisible(true)`. Broadcasts a `snapshot` - * event with `cleared: true` for every tab so the renderer drops its - * cached snapshot image and exposes the live view again. + * Re-show currently active views and clear cached snapshots, including + * snapshots of tabs that deactivated during the overlay. */ resumeAll: call(z.object({}), z.void()), }, diff --git a/tests/unit/main/features/browser/registry.test.ts b/tests/unit/main/features/browser/registry.test.ts new file mode 100644 index 000000000..078415ea9 --- /dev/null +++ b/tests/unit/main/features/browser/registry.test.ts @@ -0,0 +1,188 @@ +import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; +import { EventEmitter } from "node:events"; +import type { BrowserWindow } from "electron"; +import { + createIpcPair, + mockGetAllWebContents, + mockIpcMain, + resetInMemoryIpc, + setupInMemoryRouter, +} from "../../../../helpers/ipc-pair"; + +let nextContentsId = 1000; +const image = { isEmpty: () => false, toJPEG: () => Buffer.alloc(2000) }; + +class FakeWebContents extends EventEmitter { + readonly id = nextContentsId++; + readonly session = Object.assign(new EventEmitter(), { + setPermissionRequestHandler: () => {}, + webRequest: { onBeforeRequest: () => {} }, + }); + readonly capturePage = mock(async () => image); + readonly loadURL = mock(async (_url: string) => {}); + private destroyed = false; + + setWindowOpenHandler(): void {} + setBackgroundThrottling(): void {} + setDevToolsWebContents(): void {} + openDevTools(): void {} + closeDevTools(): void {} + isLoading(): boolean { + return true; + } + isDestroyed(): boolean { + return this.destroyed; + } + close(): void { + this.destroyed = true; + this.emit("destroyed"); + } +} + +class FakeWebContentsView { + readonly webContents = new FakeWebContents(); + visible = true; + setVisible(visible: boolean): void { + this.visible = visible; + } +} + +const electron = await import("electron"); +mock.module("electron", () => ({ + ...electron, + ipcMain: mockIpcMain, + webContents: { getAllWebContents: mockGetAllWebContents }, + WebContentsView: FakeWebContentsView, +})); + +const { BrowserTabRegistry } = await import("../../../../../src/main/features/browser/registry"); +const { registerBrowserChannel } = await import("../../../../../src/main/features/browser/ipc"); + +const tabId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; +const createArgs = { + tabId, + workspaceId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + partition: "persist:test", + url: "https://example.com", +}; + +describe("browser visibility IPC", () => { + let registry: InstanceType; + let pair: ReturnType; + let attached: Set; + let page: FakeWebContentsView; + + function call(method: string, args: unknown) { + return pair.window.ipc.call("browser", method, args); + } + + function setActive(active: boolean) { + return call("setActive", { tabId, active }); + } + + function snapshots() { + return pair.sender.sent + .filter(({ channel, args }) => channel === "ipc:event" && args[1] === "snapshot") + .map(({ args }) => args[2]); + } + + beforeEach(async () => { + resetInMemoryIpc(); + await setupInMemoryRouter(); + attached = new Set(); + registry = new BrowserTabRegistry({ + contentView: { + addChildView: (view: FakeWebContentsView) => attached.add(view), + removeChildView: (view: FakeWebContentsView) => attached.delete(view), + }, + } as unknown as BrowserWindow); + registerBrowserChannel(registry); + pair = createIpcPair(); + // Keep the app renderer's ID distinct from other tests' excluded page IDs. + Object.defineProperty(pair.sender, "id", { value: nextContentsId++ }); + await call("create", createArgs); + page = registry.get(tabId)!.view as unknown as FakeWebContentsView; + await setActive(true); + }); + + afterEach(() => { + registry.disposeAll(); + resetInMemoryIpc(); + }); + + test("restores a detached page and DevTools when they attach after resume", async () => { + await call("openDevTools", { tabId }); + const devTools = registry.get(tabId)!.devtoolsView as unknown as FakeWebContentsView; + await call("suspendAll", { captureSnapshot: true }); + expect(page.visible).toBe(false); + expect(devTools.visible).toBe(false); + expect(snapshots()).toEqual([{ kind: "set", tabId, dataUrl: expect.any(String) }]); + + await setActive(false); + await call("resumeAll", {}); + expect(attached.size).toBe(0); + + await setActive(true); + expect(attached).toEqual(new Set([page, devTools])); + expect(page.visible).toBe(true); + expect(devTools.visible).toBe(true); + expect(snapshots().at(-1)).toEqual({ kind: "cleared", tabId }); + }); + + test("restores DevTools reopened after it was closed while suspended", async () => { + await call("openDevTools", { tabId }); + const devTools = registry.get(tabId)!.devtoolsView as unknown as FakeWebContentsView; + await call("suspendAll", { captureSnapshot: false }); + await call("openDevTools", { tabId }); + await call("resumeAll", {}); + await call("openDevTools", { tabId }); + expect(attached.has(devTools)).toBe(true); + expect(devTools.visible).toBe(true); + }); + + test("resumes before a pending capture completes without hiding or publishing a snapshot", async () => { + const capture = Promise.withResolvers(); + page.webContents.capturePage.mockReturnValueOnce(capture.promise); + const suspended = call("suspendAll", { captureSnapshot: true }); + expect(page.webContents.capturePage).toHaveBeenCalledTimes(1); + await call("resumeAll", {}); + capture.resolve(image); + await suspended; + + expect(page.visible).toBe(true); + expect(snapshots()).not.toContainEqual(expect.objectContaining({ kind: "set" })); + }); + + test("uses the current overlay state when a tab attaches before the first capture completes", async () => { + const capture = Promise.withResolvers(); + page.webContents.capturePage.mockReturnValueOnce(capture.promise); + const suspended = call("suspendAll", { captureSnapshot: true }); + await setActive(false); + await setActive(true); + expect(page.visible).toBe(false); + + await call("resumeAll", {}); + await call("suspendAll", { captureSnapshot: false }); + capture.resolve(image); + await suspended; + expect(page.visible).toBe(false); + expect(snapshots()).not.toContainEqual(expect.objectContaining({ kind: "set" })); + + await call("resumeAll", {}); + expect(page.visible).toBe(true); + }); + + test("discards a pending snapshot when the tab is recreated under the same ID", async () => { + const capture = Promise.withResolvers(); + page.webContents.capturePage.mockReturnValueOnce(capture.promise); + const suspended = call("suspendAll", { captureSnapshot: true }); + await call("destroy", { tabId }); + await call("create", createArgs); + await setActive(true); + capture.resolve(image); + await suspended; + await call("resumeAll", {}); + + expect(snapshots()).not.toContainEqual(expect.objectContaining({ kind: "set" })); + }); +}); From 390837f2b377cf16e1b4fb6b40920c6ecf0115dc Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 16:27:27 +0900 Subject: [PATCH 009/208] test(renderer): isolate preview defaults across test files --- tests/unit/renderer/services/cli/editor-open.test.ts | 7 ++++++- tests/unit/renderer/services/cli/settings.test.ts | 6 +++++- tests/unit/renderer/state/stores/preview-defaults.test.ts | 6 +++++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/tests/unit/renderer/services/cli/editor-open.test.ts b/tests/unit/renderer/services/cli/editor-open.test.ts index b5fb4e871..87ab731c1 100644 --- a/tests/unit/renderer/services/cli/editor-open.test.ts +++ b/tests/unit/renderer/services/cli/editor-open.test.ts @@ -1,5 +1,5 @@ /** nexus open --source and --preview: the tab shows that view, as its switch does, this once. */ -import { afterAll, afterEach, expect, test } from "bun:test"; +import { afterAll, afterEach, beforeEach, expect, test } from "bun:test"; const globals = globalThis as { window?: unknown; document?: unknown }; const originalWindow = globals.window; @@ -39,7 +39,12 @@ const viewOf = (tabId: string) => { return tab?.type === "editor" ? tab.viewMode : null; }; +beforeEach(() => { + usePreviewDefaultsStore.getState().hydrate({}); +}); + afterEach(() => { + usePreviewDefaultsStore.getState().hydrate({}); useTabsStore.setState({ byWorkspace: {} }); useLayoutStore.setState({ byWorkspace: {} }); }); diff --git a/tests/unit/renderer/services/cli/settings.test.ts b/tests/unit/renderer/services/cli/settings.test.ts index bd66a932c..b24292c9e 100644 --- a/tests/unit/renderer/services/cli/settings.test.ts +++ b/tests/unit/renderer/services/cli/settings.test.ts @@ -3,7 +3,7 @@ * the store the Settings dialog uses, and saved as the dialog saves it. */ -import { afterAll, beforeEach, describe, expect, it, mock } from "bun:test"; +import { afterAll, afterEach, beforeEach, describe, expect, it, mock } from "bun:test"; const writes: unknown[] = []; @@ -78,6 +78,10 @@ beforeEach(() => { writes.length = 0; }); +afterEach(() => { + usePreviewDefaultsStore.getState().hydrate({}); +}); + describe("settings.set", () => { it('takes "" as the system\'s font', async () => { await set("editor.fontFamily", "JetBrains Mono"); diff --git a/tests/unit/renderer/state/stores/preview-defaults.test.ts b/tests/unit/renderer/state/stores/preview-defaults.test.ts index 3969f853b..78933d1a5 100644 --- a/tests/unit/renderer/state/stores/preview-defaults.test.ts +++ b/tests/unit/renderer/state/stores/preview-defaults.test.ts @@ -3,10 +3,14 @@ * not know is dropped on load. */ -import { describe, expect, it } from "bun:test"; +import { afterEach, describe, expect, it } from "bun:test"; import { usePreviewDefaultsStore } from "../../../../../src/renderer/state/stores/preview-defaults"; describe("usePreviewDefaultsStore", () => { + afterEach(() => { + usePreviewDefaultsStore.getState().hydrate({}); + }); + it("drops a format it does not know on load", () => { usePreviewDefaultsStore.getState().hydrate({ json: "preview", future: "raw" }); expect(usePreviewDefaultsStore.getState().byFormat).toEqual({ json: "preview" }); From 4c5ed8aff42d3719c91669beb87acd9900fc86b0 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 16:35:21 +0900 Subject: [PATCH 010/208] fix(browser): show main-frame load failures in tabs and CLI --- src/main/features/browser/ipc.ts | 23 ++---- src/main/features/browser/registry.ts | 73 ++++++++++++++--- src/main/features/cli/browser/driver.ts | 15 +++- src/main/features/cli/index.ts | 9 ++- .../workspace/content/browser-view.tsx | 26 ++++-- src/renderer/state/operations/browser.ts | 10 ++- src/renderer/state/stores/browser-runtime.ts | 2 + src/shared/i18n/locales/en/common.json | 1 + src/shared/i18n/locales/ko/common.json | 1 + src/shared/ipc/contract.ts | 12 +-- tests/setup.ts | 4 + .../main/features/browser/registry.test.ts | 81 +++++++++++++++++++ 12 files changed, 212 insertions(+), 45 deletions(-) diff --git a/src/main/features/browser/ipc.ts b/src/main/features/browser/ipc.ts index f75b80a34..d910a45dc 100644 --- a/src/main/features/browser/ipc.ts +++ b/src/main/features/browser/ipc.ts @@ -4,7 +4,7 @@ * * BROADCASTS * ---------- - * Every browser.* event (navigated, loadingChanged, error, titleUpdated) is + * Every browser.* event (navigated, loadingChanged, loadFailureChanged, titleUpdated) is * sent via the shared `broadcast` helper so all open renderer windows receive * it. The renderer is responsible for filtering by tabId. * @@ -99,6 +99,9 @@ export function registerBrowserChannel( registry: BrowserTabRegistry, channelDeps?: BrowserChannelDeps, ): void { + registry.onLoadFailure((tabId, failure) => { + broadcast("browser", "loadFailureChanged", { tabId, failure }); + }); registry.onRefused((tabId, url, error) => { const { kind, reason } = error as { kind?: unknown; reason?: unknown }; broadcast("browser", "refused", { @@ -131,7 +134,8 @@ export function registerBrowserChannel( }); }); - wc.on("did-navigate-in-page", (_event, navUrl) => { + wc.on("did-navigate-in-page", (_event, navUrl, isMainFrame) => { + if (!isMainFrame) return; broadcast("browser", "navigated", { tabId, url: navUrl, @@ -148,19 +152,6 @@ export function registerBrowserChannel( broadcast("browser", "loadingChanged", { tabId, isLoading: false }); }); - wc.on("did-fail-load", (_event, errorCode, errorDescription, validatedURL) => { - broadcast("browser", "error", { - tabId, - code: errorCode, - description: errorDescription, - url: validatedURL, - }); - // Loading has ended (failed) — ensure isLoading is toggled off - // even when did-stop-loading fires before the renderer processes - // this event. - broadcast("browser", "loadingChanged", { tabId, isLoading: false }); - }); - wc.on("page-title-updated", (_event, title) => { broadcast("browser", "titleUpdated", { tabId, title }); }); @@ -276,7 +267,7 @@ export function registerBrowserChannel( listen: { navigated: {}, loadingChanged: {}, - error: {}, + loadFailureChanged: {}, refused: {}, titleUpdated: {}, snapshot: {}, diff --git a/src/main/features/browser/registry.ts b/src/main/features/browser/registry.ts index 570d87f59..50af2e8dd 100644 --- a/src/main/features/browser/registry.ts +++ b/src/main/features/browser/registry.ts @@ -75,6 +75,9 @@ interface TabEntry { view: WebContentsView; workspaceId: string; partition: string; + loadFailure: BrowserLoadFailure | null; + navigationRequest: number; + forwardedAddress: { requested: string; target: string } | null; /** * Whether this tab is the active tab in its group. * @@ -137,6 +140,11 @@ export interface BrowserAddressResolver { resolve(workspaceId: string, url: string): Promise; } +export interface BrowserLoadFailure { + url: string; + description: string; +} + /** A usable page snapshot captured by `suspendAll`. */ interface SuspendSnapshot { tabId: string; @@ -175,6 +183,9 @@ export class BrowserTabRegistry { private addressResolver: BrowserAddressResolver | null = null; /** Told of a URL the resolver would not open, and why. */ private readonly refusedListeners = new Set<(tabId: string, url: string, error: Error) => void>(); + private readonly loadFailureListeners = new Set< + (tabId: string, failure: BrowserLoadFailure | null) => void + >(); constructor(win: BrowserWindow, permissionDeps?: PermissionHandlerDeps) { this.win = win; @@ -235,6 +246,9 @@ export class BrowserTabRegistry { view, workspaceId, partition, + loadFailure: null, + navigationRequest: 0, + forwardedAddress: null, active: false, lastBounds: null, devtoolsView: null, @@ -242,13 +256,26 @@ export class BrowserTabRegistry { devtoolsOpen: false, }; this.tabs.set(tabId, entry); + view.webContents.on("did-fail-load", (_event, code, description, url, isMainFrame) => { + if (!isMainFrame || code === -3) return; // ERR_ABORTED + const forward = entry.forwardedAddress; + this.setLoadFailure(tabId, entry, { + url: forward?.target === url ? forward.requested : url, + description, + }); + }); + view.webContents.on("did-navigate", () => this.setLoadFailure(tabId, entry, null)); for (const listener of this.createListeners) listener(tabId, view.webContents); // A page's own move to a local address of an SSH workspace goes to the // address's forward instead. Guards that blocked it already win. view.webContents.on("will-navigate", (event, target) => { if (event.defaultPrevented) return; - if (!this.addressResolver?.rewrites(workspaceId, target)) return; + if (!this.addressResolver?.rewrites(workspaceId, target)) { + entry.navigationRequest++; + entry.forwardedAddress = null; + return; + } event.preventDefault(); this.load(tabId, entry, target, "will-navigate"); }); @@ -279,12 +306,24 @@ export class BrowserTabRegistry { return () => this.refusedListeners.delete(listener); } + onLoadFailure(listener: (tabId: string, failure: BrowserLoadFailure | null) => void): void { + this.loadFailureListeners.add(listener); + } + + private setLoadFailure(tabId: string, entry: TabEntry, failure: BrowserLoadFailure | null): void { + if (this.tabs.get(tabId) !== entry || (failure === null && entry.loadFailure === null)) return; + entry.loadFailure = failure; + if (entry.active) entry.view.setVisible(!this.suspended && failure === null); + for (const listener of this.loadFailureListeners) listener(tabId, failure); + } + /** Loads `url` in the tab, through the address resolver when it has a say. */ private load(tabId: string, entry: TabEntry, url: string, label: string): void { + const request = ++entry.navigationRequest; + entry.forwardedAddress = null; if (!isTabLoadAllowed(url)) { - const error = new Error("a browser tab opens only http, https and file addresses"); - logger.warn(`[${label}] ${url} not opened in ${tabId}: ${error.message}`); - for (const listener of this.refusedListeners) listener(tabId, url, error); + logger.warn(`[${label}] disallowed address in ${tabId}: ${url}`); + this.setLoadFailure(tabId, entry, { url, description: "ERR_DISALLOWED_URL_SCHEME" }); return; } const loadNow = (target: string) => { @@ -297,15 +336,23 @@ export class BrowserTabRegistry { loadNow(url); return; } + const isCurrent = () => + this.tabs.get(tabId) === entry && + entry.navigationRequest === request && + !entry.view.webContents.isDestroyed(); resolver.resolve(entry.workspaceId, url).then( (resolved) => { - // The tab may have closed while the forward was set up. - if (this.tabs.get(tabId) !== entry || entry.view.webContents.isDestroyed()) return; + if (!isCurrent()) return; + entry.forwardedAddress = { requested: url, target: resolved }; loadNow(resolved); }, (error: Error) => { - if (this.tabs.get(tabId) !== entry) return; + if (!isCurrent()) return; logger.warn(`[${label}] ${url} not opened in ${tabId}: ${error.message}`); + const { kind } = error as { kind?: unknown }; + const description = + kind === "not-connected" ? "ERR_SSH_NOT_CONNECTED" : "ERR_PORT_FORWARD_FAILED"; + this.setLoadFailure(tabId, entry, { url, description }); for (const listener of this.refusedListeners) listener(tabId, url, error); }, ); @@ -509,7 +556,7 @@ export class BrowserTabRegistry { */ private attachAndRestoreBounds(entry: TabEntry): void { // An overlay may have ended while the view was detached. - entry.view.setVisible(!this.suspended); + entry.view.setVisible(!this.suspended && entry.loadFailure === null); this.win.contentView.addChildView(entry.view); const b = entry.lastBounds; if (b) { @@ -641,7 +688,7 @@ export class BrowserTabRegistry { for (const entry of this.tabs.values()) { if (entry.active && !entry.view.webContents.isDestroyed()) { - entry.view.setVisible(true); + entry.view.setVisible(entry.loadFailure === null); if ( entry.devtoolsOpen && entry.devtoolsView !== null && @@ -673,6 +720,7 @@ export class BrowserTabRegistry { const captures = [...activeEntries].map( async ([tabId, entry]): Promise => { try { + if (entry.loadFailure) return null; const img = await entry.view.webContents.capturePage(); if (img.isEmpty()) return null; const buf = img.toJPEG(75); @@ -716,6 +764,7 @@ export class BrowserTabRegistry { return; } if (entry.view.webContents.navigationHistory.canGoBack()) { + entry.navigationRequest++; entry.view.webContents.navigationHistory.goBack(); } } @@ -727,6 +776,7 @@ export class BrowserTabRegistry { return; } if (entry.view.webContents.navigationHistory.canGoForward()) { + entry.navigationRequest++; entry.view.webContents.navigationHistory.goForward(); } } @@ -738,6 +788,11 @@ export class BrowserTabRegistry { logger.warn(`[reload] unknown tabId: ${tabId}`); return; } + if (entry.loadFailure) { + this.load(tabId, entry, entry.loadFailure.url, "retry"); + return; + } + entry.navigationRequest++; if (ignoreCache) { entry.view.webContents.reloadIgnoringCache(); } else { diff --git a/src/main/features/cli/browser/driver.ts b/src/main/features/cli/browser/driver.ts index faf85952b..4bf7b6204 100644 --- a/src/main/features/cli/browser/driver.ts +++ b/src/main/features/cli/browser/driver.ts @@ -109,6 +109,7 @@ export interface BrowserPage { readonly view: View; /** Whether the view is in the window; a tab not shown is not. */ readonly active: boolean; + readonly loadFailure?: { url: string; description: string } | null; } export interface BrowserDriver { @@ -939,6 +940,11 @@ export class CdpBrowserDriver implements BrowserDriver { if (contents.isLoading()) await once(contents, "did-stop-loading", LOAD_MS); } + private checkLoadFailure(tabId: string): void { + const failure = this.pageOf(tabId)?.loadFailure; + if (failure) throw new CliError(`Could not load ${failure.url}: ${failure.description}`); + } + async settle(tabId: string): Promise { const deadline = Date.now() + PAGE_START_MS; let page = this.pageOf(tabId); @@ -951,11 +957,13 @@ export class CdpBrowserDriver implements BrowserDriver { const done = this.driven.begin(contents); try { await this.settleOn(contents); + this.checkLoadFailure(tabId); await this.awaitDownload(contents); } finally { done(); } if (contents.isDestroyed()) return null; + this.checkLoadFailure(tabId); const download = this.downloads.get(contents); return { url: contents.getURL(), @@ -964,9 +972,14 @@ export class CdpBrowserDriver implements BrowserDriver { }; } - snapshot(tabId: string, options: { maxLines: number; within?: string }): Promise { + async snapshot( + tabId: string, + options: { maxLines: number; within?: string }, + ): Promise { + this.checkLoadFailure(tabId); return this.with(tabId, async (contents, state) => { if (contents.isLoading()) await once(contents, "did-stop-loading", LOAD_MS); + this.checkLoadFailure(tabId); const within = options.within === undefined ? undefined diff --git a/src/main/features/cli/index.ts b/src/main/features/cli/index.ts index e99d5e9e7..987153565 100644 --- a/src/main/features/cli/index.ts +++ b/src/main/features/cli/index.ts @@ -167,7 +167,14 @@ export function setupCliFeature(options: SetupCliFeatureOptions): CliFeature { }); const browser = new CdpBrowserDriver((tabId) => { const entry = getBrowserRegistry()?.get(tabId); - return entry && { contents: entry.view.webContents, view: entry.view, active: entry.active }; + return ( + entry && { + contents: entry.view.webContents, + view: entry.view, + active: entry.active, + loadFailure: entry.loadFailure, + } + ); }); const stopWatchingBrowsers = onBrowserTabCreated((tabId, contents) => browser.watch(tabId, contents), diff --git a/src/renderer/components/workspace/content/browser-view.tsx b/src/renderer/components/workspace/content/browser-view.tsx index bb608f349..c5d3af513 100644 --- a/src/renderer/components/workspace/content/browser-view.tsx +++ b/src/renderer/components/workspace/content/browser-view.tsx @@ -56,6 +56,7 @@ import { BrowserEmptyState } from "@/components/editor/browser/empty-state"; import { NavControls } from "@/components/editor/browser/nav-controls"; import { PickButton } from "@/components/editor/browser/pick-button"; import { UrlBar } from "@/components/editor/browser/url-bar"; +import { EmptyState } from "@/components/ui/empty-state"; import { IconButton } from "@/components/ui/icon-button"; import { ipcCallResult } from "@/ipc/client"; import { resolveInitialBrowserUrl } from "@/state/operations/browser"; @@ -141,6 +142,7 @@ export function BrowserTabView({ const canGoBack = runtime?.canGoBack ?? false; const canGoForward = runtime?.canGoForward ?? false; const isLoading = runtime?.isLoading ?? false; + const loadFailure = runtime?.loadFailure ?? null; // Page snapshot painted as an absolute overlay while the native view is // hidden by a suspendAll cycle. When set, it shows the last frame of the // page captured by main right before `setVisible(false)` — letting a @@ -159,7 +161,8 @@ export function BrowserTabView({ // `about:blank` is used as the synthetic initial load and is treated as // "no real content" for display purposes. Once the user navigates to an // http/https URL the empty state disappears. - const showEmptyState = (currentUrl === "" || currentUrl === BLANK_TAB_URL) && lastUrl === ""; + const showEmptyState = + !loadFailure && (currentUrl === "" || currentUrl === BLANK_TAB_URL) && lastUrl === ""; // ------------------------------------------------------------------------- // Mount: browser.create @@ -363,7 +366,7 @@ export function BrowserTabView({
)} + {loadFailure && ( +
+ void ipcCallResult("browser", "reload", { tabId })} + disabled={isLoading} + tone="status" + className="[overflow-wrap:anywhere]" + /> +
+ )} {/* Placeholder: ResizeObserver target. The WebContentsView is overlaid by the main process using the CSS-pixel bounds of this element. */} @@ -50,6 +56,26 @@ export function StatusLine({ model }: { model: ChatModel }) { type Translate = ReturnType["t"]; +/** Time since the latest signal when model generation is the only visible activity. */ +export function generatingElapsed(model: ChatModel, now: number): number | undefined { + const turn = model.turn; + if (!model.running || turn?.lastActivityAt === undefined) return undefined; + const elapsed = now - turn.lastActivityAt; + if ( + elapsed < 3_000 || + model.interrupting || + model.permissions.length > 0 || + turn.retry || + turn.status === "compacting" || + Object.values(model.tools).some( + (tool) => + tool.parentToolUseId === null && (tool.status === "running" || tool.status === "streaming"), + ) + ) + return undefined; + return elapsed; +} + function activityOf(model: ChatModel, t: Translate): string { const turn = model.turn; if (model.interrupting) return t("chat.status.interrupting"); diff --git a/src/renderer/services/chat/agent-tab.ts b/src/renderer/services/chat/agent-tab.ts index bda2f2924..e5bb2d79a 100644 --- a/src/renderer/services/chat/agent-tab.ts +++ b/src/renderer/services/chat/agent-tab.ts @@ -182,19 +182,23 @@ export async function sendToAgentTab( if (heldId) unseenSends.delete(key); return heldId ? { heldId } : {}; } - if (when === "now" && target.agent === "claude") { - await target.controller.sendNow(text, images, from, id); - } else { - const heldId = - target.agent === "codex" && id - ? await target.controller.sendPeer(text, images, id) - : target.agent === "claude" - ? await target.controller.send(text, images, from, id) - : await target.controller.send(text, images, from); + if (target.agent === "codex") { + const heldId = await target.controller.sendWithTiming( + text, + images, + when === "now" ? "now" : "next", + from, + device, + id, + ); if (heldId) { unseenSends.delete(key); return { heldId }; } + } else if (when === "now") { + await target.controller.sendNow(text, images, from, id); + } else { + await target.controller.send(text, images, from, id); } return id && target.agent === "codex" ? { itemKey: `u-peer-${id}` } : {}; } catch (err) { @@ -205,7 +209,7 @@ export async function sendToAgentTab( /** * When a message sent during a turn goes, as the composer's keys have it: - * next (↩), now (⌘↩, Claude's alone), after the turn (⌘⇧↩). + * next (↩), now (⌘↩), after the turn (⌘⇧↩). */ export type SendTiming = "next" | "now" | "after"; diff --git a/src/renderer/services/chat/codex-controller.ts b/src/renderer/services/chat/codex-controller.ts index 66b68c118..956fe1490 100644 --- a/src/renderer/services/chat/codex-controller.ts +++ b/src/renderer/services/chat/codex-controller.ts @@ -220,7 +220,9 @@ export class CodexController { private disposed = false; private titled = false; private rewinding = false; - private startingTurn = false; + private startingTurn?: Promise; + private stoppingTurn?: string; + private deferToolSendsForTurn?: string; private resumingSelection = false; private canonicalCwd: string | undefined; private agentRefresh: ReturnType | undefined; @@ -1197,6 +1199,7 @@ export class CodexController { } if (replay.found) { this.update((prev) => ({ ...prev, phase: replay.running ? "ready" : "ended" })); + if (replay.running) this.sendNextQueued(); if (replay.running && (this.discoverAgents || this.dirtyAgents.size > 0)) { this.armSubagentRefresh(); } @@ -1226,26 +1229,44 @@ export class CodexController { this.flushNow(); } - /** - * Sends a message now: during a turn it steers the turn, which reads it - * next. One another agent sends through the nexus command (`from`) is led - * by a line that tells Codex who sent it. - */ + /** Sends after the next tool completion or starts a turn when idle. */ async send(text: string, images: ImageBlock[] = [], from?: RelaySender): Promise { - await this.sendMessage(text, images, from); + await this.sendMessage(text, images, { from }); } - sendPeer(text: string, images: ImageBlock[], id: string): Promise { - return this.sendMessage(text, images, undefined, id); + async sendNow(text: string, images: ImageBlock[] = []): Promise { + await this.sendMessage(text, images, { now: true }); } - private async sendMessage( + async sendWithTiming( text: string, - images: ImageBlock[] = [], + images: ImageBlock[], + timing: "next" | "now", from?: RelaySender, + device?: string, id?: string, - queued = false, ): Promise { + return (await this.sendMessage(text, images, { now: timing === "now", from, id, device })) + ?.heldId; + } + + private async sendMessage( + text: string, + images: ImageBlock[], + { + from, + id, + device, + now, + queued, + }: { + from?: RelaySender; + id?: string; + device?: string; + now?: boolean; + queued?: QueuedMessage; + }, + ): Promise<{ heldId: string; afterTurn?: true } | undefined> { const collaboration = this.collaborationChange; if (this.rewinding || this.resumingSelection) throw new Error("Codex is changing the conversation"); @@ -1262,10 +1283,28 @@ export class CodexController { // line reaches the model: a message sent at once (a new task's, the // CLI's) would find no thread yet. this.flushNow(); + // An immediate follow-up needs the id assigned to the in-flight start. + if (now && !this.model.turnId && this.startingTurn) { + await this.startingTurn.catch(() => {}); + } if (this.rewinding || this.resumingSelection) throw new Error("Codex is changing the conversation"); if (queued && !this.state.queue.some((entry) => entry.id === id && entry.status === "sending")) throw new Error("The conversation changed while delivering a queued message"); + const { running, turnId } = this.model; + if (queued && !this.canSendQueued(queued)) return { heldId: queued.id }; + if (!queued && ((this.startingTurn && !turnId) || (running && (!now || !turnId)))) { + return { + heldId: this.holdMessage( + text, + images, + from, + device, + id, + now ? undefined : this.model.lastSeq, + ), + }; + } const threadId = this.model.threadId; if (!threadId) throw new Error("Codex has no thread to send to"); const said = from && text ? relayedText(from, text) : text; @@ -1294,7 +1333,6 @@ export class CodexController { const turn = turnIdOf(result) ?? fallback; if (record && turn) this.hooks.onRelayed?.({ ...record, turnId: turn }); }; - const { running, turnId } = this.model; if (running && turnId) { try { const result = await this.request("turn/steer", { @@ -1309,17 +1347,13 @@ export class CodexController { if (id && !(err instanceof CodexReplyError)) throw err; this.flushNow(); log.info(`steer not taken: ${(err as Error).message}`); - // A new turn runs: the message waits for it to end. + // The active turn refused the message. Wait for a turn boundary. if (this.model.running) { - if (id && this.state.queue.some((item) => item.id === id && item.status === "sending")) - return id; - return this.enqueue( - text, - images, - from, - id ? this.state.peerSubmissions?.[id]?.clientDeviceId : undefined, - id, - ); + if (queued) { + this.deferToolSendsForTurn = this.model.turnId; + return { heldId: queued.id, afterTurn: true }; + } + return { heldId: this.holdMessage(text, images, from, device, id) }; } // The turn ended meanwhile: the message starts the next one. } @@ -1330,7 +1364,6 @@ export class CodexController { // until it is sent, so a thread changed since is not overridden. if (model || effort) this.hooks.onChosen?.({}); // Its answer, or its error as a notice, comes in the log. - this.startingTurn = true; const start = this.request("turn/start", { threadId, clientUserMessageId, @@ -1342,8 +1375,10 @@ export class CodexController { .then((result) => told(result)) .finally(() => { this.flushNow(); - this.startingTurn = false; + this.startingTurn = undefined; + this.sendNextQueued(); }); + this.startingTurn = start; if (id) await start; else void start.catch(() => {}); } @@ -1364,18 +1399,30 @@ export class CodexController { device?: string, id?: string, ): string | undefined { + return this.holdMessage(text, images, from, device, id); + } + + private holdMessage( + text: string, + images: ImageBlock[], + from?: RelaySender, + device?: string, + id?: string, + afterTool?: number, + ): string { if (this.rewinding || this.resumingSelection) throw new Error("Codex is changing the conversation"); const item: QueuedMessage = { id: id ?? nextId(), text, images, + ...(afterTool !== undefined ? { afterTool } : {}), ...(from ? { from } : {}), ...(device ? { device } : {}), }; this.update((prev) => ({ ...prev, queue: [...prev.queue, item] })); - if (!this.model.running) this.sendNextQueued(); - return this.state.queue.some((entry) => entry.id === item.id) ? item.id : undefined; + this.sendNextQueued(); + return item.id; } removeQueued(id: string): QueuedMessage | undefined { @@ -1408,12 +1455,34 @@ export class CodexController { dispatchQueuedMessage( this.state.queue, (update) => this.update(update), - (next) => this.sendMessage(next.text, next.images, next.from, next.id, true), + async (next) => { + const held = await this.sendMessage(next.text, next.images, { + from: next.from, + id: next.id, + queued: next, + }); + if (held) return held.afterTurn ? { ...next, afterTool: undefined } : next; + }, (error) => error instanceof CodexReplyError, (id) => this.sawQueuedMessage(id), - () => { - if (!this.model.running) this.sendNextQueued(); - }, + () => this.sendNextQueued(), + (item) => this.canSendQueued(item), + ); + } + + private canSendQueued(item: QueuedMessage): boolean { + if (this.disposed || this.startingTurn || this.state.phase === "held") return false; + const { running, turnId, toolCompletedSeq, permissions, interrupting } = this.model; + if (!running) return true; + return ( + turnId !== undefined && + turnId !== this.deferToolSendsForTurn && + turnId !== this.stoppingTurn && + !interrupting && + permissions.length === 0 && + item.afterTool !== undefined && + toolCompletedSeq !== undefined && + toolCompletedSeq > item.afterTool ); } @@ -1424,7 +1493,14 @@ export class CodexController { async interrupt(): Promise { const { threadId, turnId } = this.model; if (!threadId || !turnId) return undefined; - return this.request("turn/interrupt", { threadId, turnId }); + this.stoppingTurn = turnId; + try { + return await this.request("turn/interrupt", { threadId, turnId }); + } finally { + this.stoppingTurn = undefined; + this.flushNow(); + this.sendNextQueued(); + } } /** Picks a preset for the next turn on, shown at once. */ @@ -1587,7 +1663,7 @@ export class CodexController { await this.write({ id, result }); // What the user said with a decline goes to the turn, which goes on. const message = answer.kind === "deny" ? answer.message : undefined; - if (message) await this.send(message).catch(() => {}); + if (message) await this.sendNow(message).catch(() => {}); } private request( @@ -1871,8 +1947,10 @@ export class CodexController { this.state.queue.some((item) => item.status === "unconfirmed") ) this.update((prev) => clearObservedQueued(prev, (id) => this.sawQueuedMessage(id))); - if (before.running && !model.running) { + if ((before.running && !model.running) || before.toolCompletedSeq !== model.toolCompletedSeq) { this.sendNextQueued(); + } + if (before.running && !model.running) { // Some versions only report child activity through the parent. Recheck // metadata while children are still running, without rereading quiet ones. if ( diff --git a/src/renderer/services/chat/codex-model.ts b/src/renderer/services/chat/codex-model.ts index ebedaf9f0..c894b00d0 100644 --- a/src/renderer/services/chat/codex-model.ts +++ b/src/renderer/services/chat/codex-model.ts @@ -43,6 +43,7 @@ import { emptyModel, type ImageBlock, type ModelInfo, + noteTurnActivity, num, type PermissionRequest, rec, @@ -94,6 +95,8 @@ export interface CodexModel extends ChatModel { nativeTranscripts?: Record; /** The turn that runs, to steer or stop. */ turnId?: string; + /** Log sequence of the current turn's last tool completion. */ + toolCompletedSeq?: number; /** What the program is signed in with (its kind only); null when it is not. */ account?: { type: string } | null; /** The program needs a sign-in before a turn can run. */ @@ -224,6 +227,7 @@ export function applyCodexLine( draft.next.blocks = {}; draft.next.forkSource = undefined; draft.next.turnId = undefined; + draft.next.toolCompletedSeq = undefined; draft.next.mcpServers = undefined; draft.next.mcpLogin = undefined; } @@ -272,6 +276,7 @@ function applyIn(draft: CodexDraft, message: Rec, seq: number, at: number | unde if (!m.running) { m.running = true; m.turn = { startedAt: at, outputTokens: 0, thinkingTokens: 0 }; + noteTurnActivity(m, at); } } return; @@ -287,6 +292,7 @@ function applyIn(draft: CodexDraft, message: Rec, seq: number, at: number | unde const { [key]: request, ...rest } = m.requests; m.requests = rest; m.permissions = m.permissions.filter((p) => p.requestId !== key); + noteTurnActivity(m, at); const decision = rec(message.result)?.decision; const itemId = str(request.params.itemId); if ((decision === "decline" || decision === "cancel") && itemId) { @@ -503,6 +509,8 @@ function applyResponse( if (turnId && m.running) enterTurn(m, turnId); if (sent.request.threadId === m.threadId) rememberCollaborationEffort(m, sent.request.effort); + } else if (m.running && (turnId ?? sent.request.expectedTurnId) === m.turnId) { + noteTurnActivity(m, at); } const clientId = str(sent.request.clientUserMessageId); if (clientId) { @@ -826,6 +834,7 @@ function applyNotification( m.running = true; m.turn = { startedAt: at, outputTokens: 0, thinkingTokens: 0 }; } + noteTurnActivity(m, at); return; } case "turn/completed": @@ -837,14 +846,21 @@ function applyNotification( const turnId = str(params.turnId) ?? m.turnId ?? ""; if (item) { const when = num(item.startedAtMs) ?? at; - applyItem( + const completed = method === "item/completed"; + const toolRan = applyItem( draft, turnId, item, - method === "item/started" ? "started" : "completed", + completed ? "completed" : "started", tag, when, ); + if (m.running && turnId === m.turnId) { + noteTurnActivity(m, at); + if (completed && toolRan && m.permissions.length === 0) { + m.toolCompletedSeq = seq; + } + } } return; } @@ -854,6 +870,7 @@ function applyNotification( const itemId = str(params.itemId); if (!delta || !itemId) return; appendText(draft, itemId, "text", delta, str(params.turnId) ?? m.turnId ?? "", tag, at); + if (!params.turnId || params.turnId === m.turnId) noteTurnActivity(m, at); if (m.turn) { m.turn = { ...m.turn, outputTokens: m.turn.outputTokens + Math.ceil(delta.length / 4) }; } @@ -865,6 +882,7 @@ function applyNotification( const itemId = str(params.itemId); if (!delta || !itemId) return; appendText(draft, itemId, "thinking", delta, str(params.turnId) ?? m.turnId ?? "", tag, at); + if (!params.turnId || params.turnId === m.turnId) noteTurnActivity(m, at); if (m.turn) { const thinkingTokens = m.turn.thinkingTokens + Math.ceil(delta.length / 4); m.turn = { ...m.turn, thinkingTokens }; @@ -874,6 +892,7 @@ function applyNotification( case "item/reasoning/summaryPartAdded": { const itemId = str(params.itemId); if (itemId && m.blocks[itemId]) appendText(draft, itemId, "thinking", "\n\n", "", tag, at); + if (!params.turnId || params.turnId === m.turnId) noteTurnActivity(m, at); return; } case "item/commandExecution/outputDelta": { @@ -1009,6 +1028,7 @@ function applyNotification( if (m.requests[key]) { const { [key]: _resolved, ...rest } = m.requests; m.requests = rest; + noteTurnActivity(m, at); } m.permissions = m.permissions.filter((p) => p.requestId !== key); return; @@ -1025,6 +1045,7 @@ function applyTurnCompleted(draft: CodexDraft, turn: Rec, seq: number, at: numbe m.turn = null; m.streaming = null; m.interrupting = false; + m.toolCompletedSeq = undefined; if (!turnId || turnId === m.turnId) m.turnId = undefined; // The turn's questions end with it. const ended = Object.entries(m.requests).filter(([, r]) => r.params.turnId === turnId); @@ -1075,7 +1096,7 @@ function applyItem( tag: string, at: number | undefined, discoverAgents = true, -): void { +): boolean | undefined { const m = draft.next; const id = str(item.id); if (!id) return; @@ -1144,11 +1165,14 @@ function applyItem( if (discoverAgents) applyNativeAgentItem(m, item); const tools = toolsOf(item, id, phase); if (!tools) return; + const ran = + item.status !== "declined" && !tools.some((tool) => m.tools[tool.id]?.status === "denied"); for (const tool of tools) { const known = m.tools[tool.id]; draft.setTool(tool.id, (prev) => mergeTool(prev, tool)); if (!known) addBlock(draft, turnId, { type: "tool", toolUseId: tool.id }, tag, at); } + return ran; } function applyNativeAgentItem(m: CodexModel, item: Rec): void { @@ -1190,7 +1214,10 @@ function mergeTool(prev: ToolCall | undefined, next: ToolCall): ToolCall { /** Makes a turn the running one; its item ids are only known to be unique within it. */ function enterTurn(m: CodexModel, turnId: string): void { - if (turnId !== m.turnId) m.blocks = {}; + if (turnId !== m.turnId) { + m.blocks = {}; + m.toolCompletedSeq = undefined; + } m.turnId = turnId; } @@ -1590,6 +1617,7 @@ function applyServerRequest(draft: CodexDraft, key: string, method: string, para m.requests = { ...m.requests, [key]: { method, params } }; const permission = permissionOf(m, key, method, params); if (permission) { + m.toolCompletedSeq = undefined; m.permissions = [...m.permissions.filter((p) => p.requestId !== key), permission]; } } diff --git a/src/renderer/services/chat/model.ts b/src/renderer/services/chat/model.ts index 80bf386cc..3f312cb40 100644 --- a/src/renderer/services/chat/model.ts +++ b/src/renderer/services/chat/model.ts @@ -259,6 +259,8 @@ export interface StreamingMessage { export interface TurnState { startedAt?: number; + /** Last progress from the main conversation, in milliseconds. */ + lastActivityAt?: number; outputTokens: number; thinkingTokens: number; /** requesting: waiting on the API; compacting: /compact runs. */ @@ -266,6 +268,13 @@ export interface TurnState { retry?: { attempt: number; maxRetries?: number; delayMs?: number }; } +export function noteTurnActivity(model: ChatModel, at: number | undefined): void { + const turn = model.turn; + if (turn && at !== undefined && at > (turn.lastActivityAt ?? -Infinity)) { + model.turn = { ...turn, lastActivityAt: at }; + } +} + export interface ModelInfo { value: string; resolvedModel?: string; @@ -631,6 +640,7 @@ function applyIn(draft: Draft, message: Rec, seq: number, at: number | undefined if (!m.running) { m.running = true; m.turn = { startedAt: at, outputTokens: 0, thinkingTokens: 0 }; + noteTurnActivity(m, at); } return; } @@ -674,12 +684,15 @@ function applyOut( return; case "stream_event": applyStreamEvent(draft, message); + if (!message.parent_tool_use_id) noteTurnActivity(draft.next, at); return; case "assistant": applyAssistant(draft, message, seq, at); + if (!message.parent_tool_use_id) noteTurnActivity(draft.next, at); return; case "user": applyUserOut(draft, message, seq, at, live); + if (!message.parent_tool_use_id) noteTurnActivity(draft.next, at); return; case "result": applyResult(draft, message, seq, at); diff --git a/src/renderer/services/chat/store.ts b/src/renderer/services/chat/store.ts index 3f594a4bd..78f38ad64 100644 --- a/src/renderer/services/chat/store.ts +++ b/src/renderer/services/chat/store.ts @@ -25,6 +25,8 @@ export interface QueuedMessage { id: string; text: string; images: ImageBlock[]; + /** Codex may steer after a tool completion later than this log sequence. */ + afterTool?: number; status?: "sending" | "failed" | "unconfirmed"; error?: string; /** The agent that sent it through the nexus command, when one did. */ @@ -40,13 +42,14 @@ export interface QueuedMessage { export function dispatchQueuedMessage( queue: readonly QueuedMessage[], update: (change: (prev: ChatTabState) => ChatTabState) => void, - send: (item: QueuedMessage) => Promise, + send: (item: QueuedMessage) => Promise, rejected: (error: unknown) => boolean, observed: (id: string) => boolean, settled: () => void, + eligible: (item: QueuedMessage) => boolean = () => true, ): void { if (queue.some((item) => item.status === "sending")) return; - const next = queue.find((item) => !item.status); + const next = queue.find((item) => !item.status && eligible(item)); if (!next) return; const sending: QueuedMessage = { ...next, status: "sending" }; const replace = (item?: QueuedMessage) => { @@ -66,7 +69,7 @@ export function dispatchQueuedMessage( replace(sending); void send(next).then( (stillHeld) => { - if (replace(stillHeld === next.id ? next : undefined)) settled(); + if (replace(stillHeld)) settled(); }, (error: unknown) => { if (observed(next.id)) { @@ -106,7 +109,7 @@ export interface ChatTabState { model: ChatModel; /** What the tab showed before its program's log: a transcript, an earlier agent's log. */ history: ChatModel | null; - /** Messages the app holds until the turn ends (⌘⇧↩). */ + /** Messages the app holds for a tool completion or the end of the turn. */ queue: QueuedMessage[]; /** Authenticated remote user submissions, keyed by the host-generated message ID. */ peerSubmissions?: Readonly>; diff --git a/src/renderer/services/cli/chat-view.ts b/src/renderer/services/cli/chat-view.ts index 8471ba404..fc5aafb45 100644 --- a/src/renderer/services/cli/chat-view.ts +++ b/src/renderer/services/cli/chat-view.ts @@ -134,7 +134,13 @@ export function chatInfoOf( } const answer = lastAnswer(model); const told = answer ? { message: answer } : {}; - if (unseen || model.running || chat.phase === "starting" || chat.phase === "held") { + if ( + unseen || + model.running || + chat.queue.some((item) => item.status === "sending") || + chat.phase === "starting" || + chat.phase === "held" + ) { return { agent, state: "working", ...told, ...at }; } const error = turnError(model); diff --git a/src/renderer/services/remote/chat-panel.ts b/src/renderer/services/remote/chat-panel.ts index 2a16c96b6..32445d653 100644 --- a/src/renderer/services/remote/chat-panel.ts +++ b/src/renderer/services/remote/chat-panel.ts @@ -246,7 +246,7 @@ export function chatPanelOf(source: ChatSource, now = Date.now()): ChatPanel { }; } -/** A message the tab holds for after its turn, as the panel tells it: its text cut short. */ +/** A held message as the panel tells it, with a bounded text preview. */ function heldOf( item: QueuedMessage, submission?: PeerSubmission, diff --git a/src/renderer/services/remote/chat-watch.ts b/src/renderer/services/remote/chat-watch.ts index db69639f6..606903f27 100644 --- a/src/renderer/services/remote/chat-watch.ts +++ b/src/renderer/services/remote/chat-watch.ts @@ -373,6 +373,7 @@ export function tabSource( codex.items.some((item) => item.kind === "user" && item.rewindable), fork: codexIdle && codex.items.length > 0, background: false, + now: true, moveNow: true, config: true, }, diff --git a/src/renderer/services/remote/peer-composer.ts b/src/renderer/services/remote/peer-composer.ts index 1a496efe5..2b06cbd55 100644 --- a/src/renderer/services/remote/peer-composer.ts +++ b/src/renderer/services/remote/peer-composer.ts @@ -235,22 +235,15 @@ export function peerComposerController(deps: PeerComposerDeps): ComposerControll await answerOf(send(text, images, uploads, when)); }; const timingOf = (how: "send" | "now" | "queue") => - how === "queue" - ? "after" - : how === "now" && agent === "claude" && can()?.now - ? "now" - : undefined; + how === "queue" ? "after" : how === "now" && can()?.now ? "now" : undefined; const tell = (error: Error) => deps.onError?.(error.message); return { key: `remote:${ref.deviceId}:${ref.workspaceId}:${ref.tabId}`, modes: CHAT_MODES[agent], send: (text, images) => sendChecked(text, images), - // A Claude chat's ↩ waits for the tool it runs, ⌘↩ does not (as its - // device lets it); a Codex chat's ↩ goes into the turn already. + sendNow: (text, images) => sendChecked(text, images, [], timingOf("now")), ...(agent === "claude" ? { - sendNow: (text: string, images?: ImageBlock[]) => - sendChecked(text, images, [], can()?.now ? "now" : undefined), readHeldNow: async () => { if (can()?.hurry) await answerOf(call("remote", "peerChatHurry", ref)); }, diff --git a/src/shared/i18n/locales/en/common.json b/src/shared/i18n/locales/en/common.json index a67f5b6bc..f7652abc5 100644 --- a/src/shared/i18n/locales/en/common.json +++ b/src/shared/i18n/locales/en/common.json @@ -1006,6 +1006,7 @@ }, "status": { "working": "Working", + "generating": "Generating · {{elapsed}}", "requesting": "Waiting for the model", "thinking": "Thinking", "writing": "Writing", @@ -1045,6 +1046,7 @@ "aria": "Messages waiting to be read", "label": "Unread", "after_turn": "After the turn", + "after_tool": "After the tool", "sending": "Sending…", "failed": "Delivery failed", "unconfirmed": "Delivery unconfirmed", @@ -1060,7 +1062,7 @@ "hint": "{{send}} send · {{newLine}} new line · / commands · @ files", "hint_codex": "{{send}} send · {{newLine}} new line · @ files", "hint_running": "{{send}} deliver after the current tool · {{nowKey}} deliver now · {{queueKey}} deliver after the turn", - "hint_running_codex": "{{send}} deliver now · {{queueKey}} deliver after the turn", + "hint_running_codex": "{{send}} after tool · {{nowKey}} now (discards current response) · {{queueKey}} after turn", "send": "Send", "steer": "Send into this turn", "queue": "Queue", diff --git a/src/shared/i18n/locales/ko/common.json b/src/shared/i18n/locales/ko/common.json index 2570e2321..82c3e3448 100644 --- a/src/shared/i18n/locales/ko/common.json +++ b/src/shared/i18n/locales/ko/common.json @@ -1007,6 +1007,7 @@ "status": { "working": "작업 중", "requesting": "모델 응답 대기 중", + "generating": "응답 생성 중 · {{elapsed}}", "thinking": "생각 중", "writing": "작성 중", "running_tool": "{{tool}} 실행 중", @@ -1045,6 +1046,7 @@ "aria": "읽히길 기다리는 메시지", "label": "읽기 전", "after_turn": "턴 종료 후", + "after_tool": "도구 실행 후", "sending": "전송 중…", "failed": "전송 실패", "unconfirmed": "전송 여부 미확인", @@ -1060,7 +1062,7 @@ "hint": "{{send}} 보내기 · {{newLine}} 줄바꿈 · / 명령 · @ 파일", "hint_codex": "{{send}} 보내기 · {{newLine}} 줄바꿈 · @ 파일", "hint_running": "{{send}} 도구 실행 후 전달 · {{nowKey}} 즉시 전달 · {{queueKey}} 턴 종료 후 전달", - "hint_running_codex": "{{send}} 즉시 전달 · {{queueKey}} 턴 종료 후 전달", + "hint_running_codex": "{{send}} 도구 실행 후 · {{nowKey}} 즉시 (진행 중 응답 버림) · {{queueKey}} 턴 종료 후", "send": "보내기", "steer": "이번 턴에 보내기", "queue": "대기열에 넣기", diff --git a/tests/unit/main/cli/chat-control.test.ts b/tests/unit/main/cli/chat-control.test.ts index 4b9ea414b..fcd68bef9 100644 --- a/tests/unit/main/cli/chat-control.test.ts +++ b/tests/unit/main/cli/chat-control.test.ts @@ -387,7 +387,7 @@ describe("chat panel", () => { "", "Context: 50,000 of 200,000 tokens (25%)\nPlan limits: session 34%, resets in 2h", "", - "Held for after the turn (chat unsend / chat edit ):\n r7 then this [1 image]", + "Held messages (chat unsend / chat edit ):\n r7 then this [1 image]", ].join("\n"), ); }); diff --git a/tests/unit/main/features/remote/serve.test.ts b/tests/unit/main/features/remote/serve.test.ts index fb38da9fc..737e4c735 100644 --- a/tests/unit/main/features/remote/serve.test.ts +++ b/tests/unit/main/features/remote/serve.test.ts @@ -1354,6 +1354,31 @@ describe("when a message goes, and the ones held for after the turn", () => { }); }); + test("a default Codex send can be held and keeps its authenticated device and nonce", async () => { + const clientNonce = "4df598dc-f794-42a4-b204-d43a3a137be3"; + const codex = { workspaceId: "w2", tabId: "t4" }; + const { serve, asked } = sendServices(() => ({ heldId: "held" })); + expect( + await serve({ + from: "phone", + method: "chat.send", + params: { ...codex, text: "next", clientNonce }, + }), + ).toEqual({ at: 1000, heldId: "held", clientNonce }); + expect(asked).toEqual([ + [ + "chat.send", + { + ...codex, + text: "next", + user: true, + device: "phone", + submission: { clientNonce, clientDeviceId: "phone" }, + }, + ], + ]); + }); + test("a held message is taken back whole, or changed; an unread one withdrawn; the unread hurried", async () => { const { serve, asked } = sendServices((op) => op === "chat.unqueue" diff --git a/tests/unit/renderer/components/chat/composer-hint.test.ts b/tests/unit/renderer/components/chat/composer-hint.test.ts index de1744906..2b5eb2354 100644 --- a/tests/unit/renderer/components/chat/composer-hint.test.ts +++ b/tests/unit/renderer/components/chat/composer-hint.test.ts @@ -24,10 +24,11 @@ describe("the composer's hint", () => { ); }); - test("a Codex tab's turn: Enter goes in at once, so no now key", () => { + test("a Codex tab's turn: Enter waits for a tool and the now key explains what it discards", () => { const { send, nowKey, queueKey } = composerKeys(); const hint = composerHint(t, true, "codex"); - expect(hint).toBe(`${send} deliver now · ${queueKey} deliver after the turn`); - expect(hint).not.toContain(`${nowKey} `); + expect(hint).toBe( + `${send} after tool · ${nowKey} now (discards current response) · ${queueKey} after turn`, + ); }); }); diff --git a/tests/unit/renderer/components/chat/status-line.test.ts b/tests/unit/renderer/components/chat/status-line.test.ts new file mode 100644 index 000000000..7cea0a56a --- /dev/null +++ b/tests/unit/renderer/components/chat/status-line.test.ts @@ -0,0 +1,78 @@ +import { expect, test } from "bun:test"; +import { generatingElapsed } from "../../../../../src/renderer/components/chat/status-line"; +import { + applyCodexLine, + emptyCodexModel, +} from "../../../../../src/renderer/services/chat/codex-model"; +import { + applyLine, + type ChatModel, + emptyModel, +} from "../../../../../src/renderer/services/chat/model"; + +test("Codex silence is measured from the last turn, tool, text, or reasoning signal", () => { + let model = { ...emptyCodexModel(), threadId: "thread" }; + let seq = 0; + const event = (at: number, method: string, params: Record) => { + model = applyCodexLine(model, { + seq: ++seq, + at, + dir: "out", + message: { method, params: { threadId: "thread", turnId: "turn", ...params } }, + }) as typeof model; + }; + event(1_000, "turn/started", { turn: { id: "turn" } }); + expect(generatingElapsed(model, 3_999)).toBeUndefined(); + expect(generatingElapsed(model, 4_000)).toBe(3_000); + + event(5_000, "item/started", { item: { id: "call", type: "commandExecution" } }); + expect(generatingElapsed(model, 10_000)).toBeUndefined(); + event(11_000, "item/completed", { + item: { id: "call", type: "commandExecution", startedAtMs: 5_000 }, + }); + expect(generatingElapsed(model, 12_000)).toBeUndefined(); + expect(generatingElapsed(model, 15_000)).toBe(4_000); + + event(16_000, "item/agentMessage/delta", { itemId: "text", delta: "hello" }); + event(18_000, "item/reasoning/textDelta", { itemId: "thought", delta: "thinking" }); + expect(generatingElapsed(model, 20_999)).toBeUndefined(); + event(21_000, "item/agentMessage/delta", { threadId: "child", itemId: "other", delta: "hi" }); + expect(generatingElapsed(model, 22_000)).toBe(4_000); + expect(generatingElapsed({ ...model, interrupting: true }, 23_000)).toBeUndefined(); + event(23_000, "turn/completed", { turn: { id: "turn" } }); + expect(generatingElapsed(model, 24_000)).toBeUndefined(); +}); + +test("Claude streaming resets the timer even for reasoning and approval suppresses it", () => { + let model: ChatModel = emptyModel(); + let seq = 0; + const stream = (at: number, event: Record) => { + model = applyLine(model, { + seq: ++seq, + at, + dir: "out", + message: { type: "stream_event", event }, + }); + }; + model = applyLine(model, { seq: ++seq, at: 1_000, dir: "in", message: { type: "user" } }); + stream(2_000, { type: "message_start", message: { id: "message" } }); + stream(3_000, { type: "content_block_start", index: 0, content_block: { type: "thinking" } }); + stream(5_000, { + type: "content_block_delta", + index: 0, + delta: { type: "thinking_delta", thinking: "thinking" }, + }); + expect(generatingElapsed(model, 7_999)).toBeUndefined(); + expect(generatingElapsed(model, 8_000)).toBe(3_000); + model = applyLine(model, { + seq: ++seq, + dir: "out", + message: { + type: "control_request", + request_id: "confirm", + request: { subtype: "can_use_tool", tool_name: "Bash" }, + }, + }); + expect(model.permissions).toHaveLength(1); + expect(generatingElapsed(model, 9_000)).toBeUndefined(); +}); diff --git a/tests/unit/renderer/services/chat/agent-tab-send.test.ts b/tests/unit/renderer/services/chat/agent-tab-send.test.ts index f02325a76..5c8832415 100644 --- a/tests/unit/renderer/services/chat/agent-tab-send.test.ts +++ b/tests/unit/renderer/services/chat/agent-tab-send.test.ts @@ -79,6 +79,10 @@ function tab(resumed: number, fail?: Error) { start(); sent.push(`now: ${text}`); }, + sendWithTiming: async (text: string, _images: unknown[], timing: "next" | "now") => { + start(); + sent.push(timing === "now" ? `now: ${text}` : text); + }, enqueue: (text: string) => { sent.push(`held: ${text}`); return "q1"; @@ -119,7 +123,7 @@ describe("sendToAgentTab", () => { expect(sendUnseen(WS, t.tabId)).toBe(true); }); - test("when it goes: now a Claude tab's alone, after the turn held with its id", async () => { + test("both agents send now, and an after-turn message is held with its id", async () => { const t = tab(0); const claude = { ...t.target, agent: "claude" } as Target; expect(await sendToAgentTab(WS, t.tabId, claude, "a", undefined, [], "now")).toEqual({}); @@ -127,7 +131,7 @@ describe("sendToAgentTab", () => { expect(await sendToAgentTab(WS, t.tabId, t.target, "c", undefined, [], "after")).toEqual({ heldId: "q1", }); - expect(t.sent).toEqual(["now: a", "b", "held: c"]); + expect(t.sent).toEqual(["now: a", "now: b", "held: c"]); // Held, it is not sent yet: the tab is not waiting on it. expect(sendUnseen(WS, t.tabId)).toBe(false); }); diff --git a/tests/unit/renderer/services/chat/codex-chosen.test.ts b/tests/unit/renderer/services/chat/codex-chosen.test.ts index 56c84f035..57b32bfce 100644 --- a/tests/unit/renderer/services/chat/codex-chosen.test.ts +++ b/tests/unit/renderer/services/chat/codex-chosen.test.ts @@ -41,6 +41,9 @@ const { CodexController, closeCodexTab, codexController } = await import( const { useChatStore } = await import("../../../../../src/renderer/services/chat/store"); const { chatHandlers } = await import("../../../../../src/renderer/services/cli/chat-actions"); const { useTabsStore } = await import("../../../../../src/renderer/state/stores/tabs"); +const { sendToAgentTab } = await import("../../../../../src/renderer/services/chat/agent-tab"); +const { chatPanelOf } = await import("../../../../../src/renderer/services/remote/chat-panel"); +const { chatPageOf } = await import("../../../../../src/renderer/services/remote/chat-page"); type Controller = InstanceType; let seq = 0; @@ -185,6 +188,209 @@ describe("the pick a Codex tab keeps", () => { }); describe("delivering a Codex queue entry", () => { + function line(c: Controller, message: Message, dir: "in" | "out" = "out") { + c.receive({ seq: ++lineSeq, dir, message } as never); + c.flushNow(); + } + + function item( + c: Controller, + type: string, + id: string, + phase: "started" | "completed" = "completed", + threadId = "t1", + ) { + line(c, { + method: `item/${phase}`, + params: { threadId, turnId: "turn-1", item: { id, type } }, + }); + } + + function end(c: Controller, status = "completed") { + line(c, { + method: "turn/completed", + params: { threadId: "t1", turn: { id: "turn-1", status } }, + }); + } + + function delivered() { + return sent.flatMap(({ method, params }) => { + if (method !== "turn/start" && method !== "turn/steer") return []; + const [input] = params?.input as { text: string }[]; + return [{ method, text: input?.text, expectedTurnId: params?.expectedTurnId }]; + }); + } + + async function running(c: Controller) { + await c.sendWithTiming("begin", [], "next", undefined, undefined, "first-id"); + sent.length = 0; + } + + test("steers in order on a tool completion in the current turn, using the edited text", async () => { + const c = tab(); + await running(c); + item(c, "webSearch", "earlier"); + await c.send("first"); + await c.send("second"); + await c.send("cancelled"); + const [first, , cancelled] = c.state.queue; + c.editQueued(first.id, "edited"); + c.removeQueued(cancelled.id); + item(c, "dynamicToolCall", "child", "completed", "child-thread"); + item(c, "agentMessage", "text"); + item(c, "commandExecution", "shell", "started"); + expect(delivered()).toEqual([]); + + item(c, "commandExecution", "shell"); + await Bun.sleep(0); + expect(delivered()).toEqual([ + { method: "turn/steer", text: "edited", expectedTurnId: "turn-1" }, + { method: "turn/steer", text: "second", expectedTurnId: "turn-1" }, + ]); + expect(c.state.queue).toEqual([]); + }); + + test("an approval, its answer, and a declined tool leave the message held", async () => { + const c = tab(); + await running(c); + item(c, "commandExecution", "shell", "started"); + line(c, { + id: 10, + method: "item/commandExecution/requestApproval", + params: { threadId: "t1", turnId: "turn-1", itemId: "shell" }, + }); + await c.send("held"); + item(c, "mcpToolCall", "other-tool"); + expect(c.model.permissions).toHaveLength(1); + expect(delivered()).toEqual([]); + + line(c, { id: 10, result: { decision: "decline" } }, "in"); + item(c, "commandExecution", "shell"); + expect(c.model.permissions).toEqual([]); + expect(delivered()).toEqual([]); + expect(c.state.queue.map(({ text }) => text)).toEqual(["held"]); + + item(c, "webSearch", "search"); + await Bun.sleep(0); + expect(delivered()).toEqual([{ method: "turn/steer", text: "held", expectedTurnId: "turn-1" }]); + }); + + test.each([ + "completed", + "interrupted", + ])("starts the next turn when a tool never completed (%s)", async (status) => { + const c = tab(); + await running(c); + await c.send("next"); + if (status === "interrupted") await c.interrupt(); + end(c, status); + await Bun.sleep(0); + expect(delivered()).toEqual([ + { method: "turn/start", text: "next", expectedTurnId: undefined }, + ]); + }); + + test("a rejected steer waits for the turn's end without letting later messages overtake it", async () => { + const c = tab(undefined, undefined, ({ method }) => + method === "turn/steer" + ? { error: { code: -32602, message: "NonSteerableTurn" } } + : undefined, + ); + await running(c); + await c.send("first"); + await c.send("second"); + item(c, "mcpToolCall", "call"); + await Bun.sleep(0); + expect(c.state.queue[0]).toMatchObject({ text: "first" }); + expect(c.state.queue[0].afterTool).toBeUndefined(); + item(c, "webSearch", "search"); + await Bun.sleep(0); + expect(delivered()).toEqual([ + { method: "turn/steer", text: "first", expectedTurnId: "turn-1" }, + ]); + end(c); + await Bun.sleep(0); + expect(delivered().at(-1)).toMatchObject({ method: "turn/start", text: "first" }); + expect(c.state.queue.map(({ text }) => text)).toEqual(["second"]); + }); + + test("now steers without a tool and after-turn messages ignore tool completions", async () => { + const c = tab(); + await running(c); + c.enqueue("after"); + await c.sendNow("now"); + item(c, "fileChange", "patch"); + expect(delivered()).toEqual([{ method: "turn/steer", text: "now", expectedTurnId: "turn-1" }]); + end(c); + await Bun.sleep(0); + expect(delivered().at(-1)).toMatchObject({ method: "turn/start", text: "after" }); + }); + + test("an immediate follow-up during turn/start waits for that turn's id", async () => { + let accept!: (reply: { result: { turn: { id: string } } }) => void; + const starting = new Promise<{ result: { turn: { id: string } } }>((resolve) => { + accept = resolve; + }); + const c = tab(undefined, undefined, ({ method }) => + method === "turn/start" ? starting : undefined, + ); + await c.send("begin"); + await c.send("after tool"); + const immediate = c.sendNow("now"); + await Bun.sleep(0); + expect(delivered()).toEqual([ + { method: "turn/start", text: "begin", expectedTurnId: undefined }, + ]); + accept({ result: { turn: { id: "turn-1" } } }); + await immediate; + expect(delivered().at(-1)).toMatchObject({ + method: "turn/steer", + text: "now", + expectedTurnId: "turn-1", + }); + expect(c.state.queue.map(({ text }) => text)).toEqual(["after tool"]); + }); + + test("a remote submission keeps its nonce and id from the held panel to the conversation", async () => { + const workspaceId = "ws-codex-send-peer"; + const { id: tabId } = useTabsStore.getState().createTab(workspaceId, { + type: "codex", + props: { cwd: "/p", threadId: "t1" }, + }); + const c = tab(undefined, undefined, undefined, { workspaceId, tabId }); + await running(c); + const submission = { clientNonce: crypto.randomUUID(), clientDeviceId: "phone" }; + const { heldId } = await sendToAgentTab( + workspaceId, + tabId, + { agent: "codex", controller: c }, + "peer", + undefined, + [], + "next", + "phone", + submission, + ); + const source = () => ({ agent: "codex" as const, title: "Codex", chat: c.state }); + expect(heldId).toBeString(); + expect(chatPanelOf(source()).held).toEqual([ + { id: heldId as string, text: "peer", ...submission }, + ]); + expect(c.state.queue[0].device).toBe("phone"); + + item(c, "dynamicToolCall", "call"); + await Bun.sleep(0); + c.flushNow(); + expect(chatPanelOf(source()).held).toBeUndefined(); + expect(chatPageOf(source()).items).toContainEqual( + expect.objectContaining({ + key: `u-peer-${heldId}`, + text: "peer", + ...submission, + }), + ); + }); + test("keeps a rejected prompt and its image recoverable without retrying it", async () => { let rejectDelivery!: (reply: { error: { code: number; message: string } }) => void; const delivery = new Promise<{ error: { code: number; message: string } }>((resolve) => { @@ -195,7 +401,7 @@ describe("delivering a Codex queue entry", () => { ? delivery : undefined, ); - await c.sendPeer("first turn", [], "first-id"); + await c.sendWithTiming("first turn", [], "next", undefined, undefined, "first-id"); const images = [{ mediaType: "image/png", data: "image bytes" }]; expect(c.enqueue("recover me", images, undefined, "phone", "queued-id")).toBe("queued-id"); diff --git a/tests/unit/renderer/services/remote/peer-composer.test.ts b/tests/unit/renderer/services/remote/peer-composer.test.ts index 8f264c145..a1ca265f6 100644 --- a/tests/unit/renderer/services/remote/peer-composer.test.ts +++ b/tests/unit/renderer/services/remote/peer-composer.test.ts @@ -146,16 +146,26 @@ describe("the composer of another computer's chat", () => { ]); }); - test("a Codex chat's ↩ goes into the turn: no ⌘↩ of its own, nothing to withdraw", () => { + test("a Codex peer composer passes the three send timings to the host", async () => { + const { calls, call } = recording(); const made = peerComposerController({ ref, agent: "codex", settings: () => settings, onSettings: () => {}, filesRefused: "images only", - call: recording().call, + can: () => ({ now: true }), + call, }); - expect(made.sendNow).toBeUndefined(); + await made.send("next"); + await made.sendNow?.("now"); + made.enqueue("later"); + await Promise.resolve(); + expect(calls).toEqual([ + { method: "peerChatSend", args: { ...ref, text: "next" } }, + { method: "peerChatSend", args: { ...ref, text: "now", when: "now" } }, + { method: "peerChatSend", args: { ...ref, text: "later", when: "after" } }, + ]); expect(made.withdraw).toBeUndefined(); expect(made.readHeldNow).toBeUndefined(); }); From ad84632523d3aaa1bcf16fc2f96931afdf0713d3 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 17:27:02 +0900 Subject: [PATCH 016/208] fix(test): isolate remote file transfer timing and state --- src/main/features/cli/file-transfer.ts | 13 +- src/main/features/remote/file-writes.ts | 21 ++- src/main/features/remote/room.ts | 18 +-- tests/unit/main/cli/fake-services.ts | 2 +- tests/unit/main/cli/file-pull.test.ts | 22 ++- .../main/features/remote/file-writes.test.ts | 24 ++- tests/unit/main/features/remote/room.test.ts | 139 ++++++++++-------- 7 files changed, 143 insertions(+), 96 deletions(-) diff --git a/src/main/features/cli/file-transfer.ts b/src/main/features/cli/file-transfer.ts index 7d1b23350..17537614d 100644 --- a/src/main/features/cli/file-transfer.ts +++ b/src/main/features/cli/file-transfer.ts @@ -12,7 +12,7 @@ import { import { speaks } from "../../../shared/remote/room"; import { FILE_WRITE_BUSY, filePathRules } from "../remote/file-io"; import { RpcFailure } from "../remote/room"; -import { type CliContext, type CliDevice, CliError } from "./context"; +import { type CliContext, type CliDevice, CliError, type CliRemote } from "./context"; import { onAppMachine } from "./paths"; import { agentSenderOf, @@ -61,11 +61,12 @@ const BUSY_RETRIES = 5; const BUSY_RETRY_BASE_MS = 250; // Leave room for chats and terminals on the relay's 50-frame-per-second budget. const REQUESTS_PER_SECOND = 24; -const sent: number[] = []; +// Pulls and pushes on the same app connection share its request budget. +const sentByRemote = new WeakMap(); // Leave time to unwind before the hook server (35m) and client (36m) deadlines. const TRANSFER_TIMEOUT_MS = 34 * 60_000; -async function waitForFileRequest(signal: AbortSignal): Promise { +async function waitForFileRequest(sent: number[], signal: AbortSignal): Promise { for (;;) { signal.throwIfAborted(); const now = performance.now(); @@ -154,6 +155,10 @@ function filePeer( ): FilePeer { const current = speaks(device.schema, "0.14.0"); let sender: Promise | undefined; + const remote = ctx.services.remote; + const previous = sentByRemote.get(remote); + const sent = previous ?? []; + if (!previous) sentByRemote.set(remote, sent); const transferId = current ? randomUUID() : undefined; return async ( method: M, @@ -172,7 +177,7 @@ function filePeer( ...(anywhere ? { anywhere: true } : {}), } as RpcParams; for (let retry = 0; ; retry++) { - await waitForFileRequest(signal); + await waitForFileRequest(sent, signal); try { return await askDevice(ctx, device, method, request, signal); } catch (error) { diff --git a/src/main/features/remote/file-writes.ts b/src/main/features/remote/file-writes.ts index 87ceac872..af78d99d7 100644 --- a/src/main/features/remote/file-writes.ts +++ b/src/main/features/remote/file-writes.ts @@ -38,6 +38,14 @@ type UploadResult = RpcResult<"files.write.end">; type Range = [start: number, end: number]; type Authorize = (destination?: string) => void; +type ScheduleExpiry = (expire: () => Promise, idleMs: number) => () => void; + +const scheduleExpiry: ScheduleExpiry = (expire, idleMs) => { + const timer = setTimeout(() => void expire(), idleMs); + timer.unref(); + return () => clearTimeout(timer); +}; + interface Destination { path: string; parent: string; @@ -58,7 +66,7 @@ interface Upload { file?: FileHandle; fileInfo?: Stats; reserved: number; - timer?: ReturnType; + cancelExpiry?: () => void; cleanup?: Promise; } @@ -194,7 +202,7 @@ export async function makeRemoteDirectory( export class FileWrites { private readonly uploads = new Map(); - constructor(private readonly idleMs = MAX_IDLE_MS) {} + constructor(private readonly schedule: ScheduleExpiry = scheduleExpiry) {} async begin( device: string, @@ -293,7 +301,7 @@ export class FileWrites { if (!file || !destination || !temporary || !fileInfo) throw invalid("the upload has not started"); upload.sealed = true; - clearTimeout(upload.timer); + upload.cancelExpiry?.(); const signal = upload.controller.signal; try { return await this.work(upload, async () => { @@ -391,15 +399,14 @@ export class FileWrites { } private touch(id: string, upload: Upload): void { - clearTimeout(upload.timer); - upload.timer = setTimeout(() => void this.discard(id, upload), this.idleMs); - upload.timer.unref(); + upload.cancelExpiry?.(); + upload.cancelExpiry = this.schedule(() => this.discard(id, upload), MAX_IDLE_MS); } private discard(id: string, upload: Upload): Promise { if (upload.cleanup) return upload.cleanup; upload.controller.abort(new RpcFailure(RpcErrorCode.Unavailable, "the upload was cancelled")); - clearTimeout(upload.timer); + upload.cancelExpiry?.(); upload.cleanup = (async () => { try { await Promise.allSettled(upload.work); diff --git a/src/main/features/remote/room.ts b/src/main/features/remote/room.ts index a5c77216c..7b1f04b36 100644 --- a/src/main/features/remote/room.ts +++ b/src/main/features/remote/room.ts @@ -103,19 +103,17 @@ class FileReadBudget { } } -const imageReadBudget = new FileReadBudget(2, 16); -const fileReadBudget = new FileReadBudget(8, 32); const FILE_READ_SOCKET_HIGH_WATER = 4 * MAX_FRAME_BYTES; -function readBudget(params: unknown): FileReadBudget { +function readsWholeImage(params: unknown): boolean { const { as, path } = (params ?? {}) as { as?: unknown; path?: unknown }; const image = /\.(png|jpe?g|gif|webp)$/i; - return as !== "bytes" && + return ( + as !== "bytes" && typeof path === "string" && (image.test(posix.normalize(path).replace(/\/+$/, "")) || image.test(win32.normalize(path).replace(/\\+$/, ""))) - ? imageReadBudget - : fileReadBudget; + ); } /** A request that failed, with its JSON-RPC error. */ @@ -184,6 +182,8 @@ interface Pending { export class RemoteRoom { private readonly connection: RoomConnection; + private readonly imageReadBudget = new FileReadBudget(2, 16); + private readonly fileReadBudget = new FileReadBudget(8, 32); private status: RoomStatus = "off"; private peers = new Map(); private seq = 0; @@ -576,7 +576,7 @@ export class RemoteRoom { this.heard.get(from)?.epoch === epoch && this.peers.get(from)?.online === true; if (message.method === "files.read") { - const budget = readBudget(message.params); + const budget = readsWholeImage(message.params) ? this.imageReadBudget : this.fileReadBudget; if (!current()) return; if (!(await budget.acquire(current))) { // Every refused request is told, each with its own small reply: left @@ -674,8 +674,8 @@ export class RemoteRoom { } private cancelQueuedReads(): void { - imageReadBudget.cancelWaiting(); - fileReadBudget.cancelWaiting(); + this.imageReadBudget.cancelWaiting(); + this.fileReadBudget.cancelWaiting(); } private async answer( diff --git a/tests/unit/main/cli/fake-services.ts b/tests/unit/main/cli/fake-services.ts index c12919f04..9efe7b8e5 100644 --- a/tests/unit/main/cli/fake-services.ts +++ b/tests/unit/main/cli/fake-services.ts @@ -407,7 +407,7 @@ export function fakeApp(now = Date.now()): FakeApp { const agents: FakeApp["agents"] = new Map(); const stops: string[] = []; const screens = new Map([[CODEX_TAB, "› Summarize the API\n\n• Working (12s)"]]); - const workspaces = [...WORKSPACES]; + const workspaces = structuredClone(WORKSPACES); const added: FakeApp["added"] = []; const sidebar: FakeApp["sidebar"] = []; /** diff --git a/tests/unit/main/cli/file-pull.test.ts b/tests/unit/main/cli/file-pull.test.ts index 3a33518e1..39cf31b5e 100644 --- a/tests/unit/main/cli/file-pull.test.ts +++ b/tests/unit/main/cli/file-pull.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { createHash } from "node:crypto"; +import { once } from "node:events"; import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { setTimeout as delay } from "node:timers/promises"; import { MAX_BYTES_CHUNK, RpcErrorCode, @@ -193,14 +193,19 @@ test("starts four positioned chunk reads and assembles out-of-order answers", as ); let active = 0; let peak = 0; + const batchArrived = Promise.withResolvers(); + const laterCompleted = Promise.withResolvers(); const completed: number[] = []; const app = peer(async (request) => { if (request.offset === 0) return piece(request, data); const offset = request.offset ?? 0; peak = Math.max(++active, peak); + if (active === 4) batchArrived.resolve(); try { - await delay(offset === MAX_BYTES_CHUNK ? 40 : 5); + await batchArrived.promise; + if (offset === MAX_BYTES_CHUNK) await laterCompleted.promise; completed.push(offset); + if (offset !== MAX_BYTES_CHUNK) laterCompleted.resolve(); return piece(request, data); } finally { active--; @@ -225,18 +230,19 @@ test("a changed version lets outstanding reads unwind and keeps the old file", a const data = Buffer.alloc(MAX_BYTES_CHUNK * 2 + 1, 42); const saved = path.join(cwd, "source.bin"); await writeFile(saved, "previous"); + const otherArrived = Promise.withResolvers(); let otherAborted = false; const app = peer(async (request, signal) => { if (request.offset === 0) return piece(request, data); if (request.offset === MAX_BYTES_CHUNK) { - await delay(5); + await otherArrived.promise; return fail(RpcErrorCode.InvalidParams, "file version changed"); } - try { - await delay(2000, undefined, { signal }); - } finally { - otherAborted = signal?.aborted ?? false; - } + if (!signal) throw new Error("the outstanding read must be cancellable"); + const aborted = once(signal, "abort"); + otherArrived.resolve(); + await aborted; + otherAborted = signal.aborted; }); const result = await pull(app, "source.bin"); expect(result.stderr).toContain("changed while copying"); diff --git a/tests/unit/main/features/remote/file-writes.test.ts b/tests/unit/main/features/remote/file-writes.test.ts index c62319f5d..6edfdbad0 100644 --- a/tests/unit/main/features/remote/file-writes.test.ts +++ b/tests/unit/main/features/remote/file-writes.test.ts @@ -14,7 +14,6 @@ import { } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { setTimeout as delay } from "node:timers/promises"; import { MAX_BYTES_CHUNK, RpcErrorCode, @@ -208,12 +207,25 @@ test("another peer cannot complete or abort an upload; owner abort is idempotent expect(await readdir(root)).toEqual([]); }); -test("idle expiry and device disconnect remove incomplete files", async () => { - writes = new FileWrites(80); - await begin("idle", 0); - for (let attempt = 0; attempt < 30 && (await readdir(root)).length > 0; attempt++) - await delay(20); +test("idle expiry is reset by a chunk and removes the temporary file", async () => { + const pending = new Set<() => Promise>(); + writes = new FileWrites((expire, idleMs) => { + expect(idleMs).toBe(120_000); + pending.add(expire); + return () => pending.delete(expire); + }); + const { uploadId } = await begin("idle", 3); + expect(pending.size).toBe(1); + const [atBegin] = pending; + await writes.chunk(DEVICE, piece(uploadId, 0, "new")); + expect(pending.size).toBe(1); + expect(pending.has(atBegin as () => Promise)).toBe(false); + await Promise.all([...pending].map((expire) => expire())); + expect(pending.size).toBe(0); expect(await readdir(root)).toEqual([]); +}); + +test("disconnect waits for a pending chunk before removing its temporary file", async () => { const { uploadId } = await begin("gone", 3); await Promise.all([writes.chunk(DEVICE, piece(uploadId, 0, "new")), writes.drop(DEVICE)]); expect(await readdir(root)).toEqual([]); diff --git a/tests/unit/main/features/remote/room.test.ts b/tests/unit/main/features/remote/room.test.ts index b1a22a699..b45ce4dea 100644 --- a/tests/unit/main/features/remote/room.test.ts +++ b/tests/unit/main/features/remote/room.test.ts @@ -4,6 +4,7 @@ import { createHash } from "node:crypto"; import { mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; +import { setImmediate as flushRelay } from "node:timers/promises"; import type { ClientFrame, Delivered, @@ -117,8 +118,8 @@ class MockRelay { } } -const tick = () => new Promise((r) => setTimeout(r, 20)); - +// Initialize sodium before the fake relay starts so frame delivery can drain +// through microtasks when a test yields to the next event-loop turn. async function roomKey(): Promise { return { kid: 1, key: roomKeyOf(await newAccountKey()) }; } @@ -156,7 +157,7 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); expect(b.room.state()).toEqual({ status: "online", peers: [ @@ -186,15 +187,15 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); const known = relay.devices.find((d) => d.id === "a") as RoomDevice; known.alias = "Studio"; b.reopen(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]).toMatchObject({ id: "a", name: "Studio", hostName: "a-pc" }); known.alias = null; b.reopen(); - await tick(); + await flushRelay(); const peer = b.room.state().peers[0]; expect(peer?.name).toBe("a-pc"); expect(peer && "hostName" in peer).toBe(false); @@ -207,7 +208,7 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); await expect( b.room.request("a", "terminal.read", { workspaceId: "w", tabId: "t" }), ).rejects.toMatchObject({ code: RpcErrorCode.Forbidden }); @@ -225,7 +226,7 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); const tab = { workspaceId: "w1", tabId: "t1" }; const from = { kind: "tab" as const, workspaceId: "bw", tabId: "bt" }; // People may control the chats; agents may not. @@ -237,7 +238,7 @@ describe("the room", () => { // Agents may, but people may not: neither may, for an agent does no more than people may. serves = ["sessions", "agents"]; a.room.announce(); - await tick(); + await flushRelay(); for (const params of [{ ...tab, from }, tab]) { await expect(b.room.request("a", "chat.interrupt", params)).rejects.toMatchObject({ code: RpcErrorCode.Forbidden, @@ -248,7 +249,7 @@ describe("the room", () => { // Both may. serves = ["sessions", "chat.control", "agents"]; a.room.announce(); - await tick(); + await flushRelay(); await b.room.request("a", "chat.interrupt", { ...tab, from }); expect(a.served).toEqual([{ from: "b", method: "chat.interrupt" }]); }); @@ -262,7 +263,7 @@ describe("the room", () => { }); a.room.start(); phone.room.start(); - await tick(); + await flushRelay(); const tab = { workspaceId: "w1", tabId: "t1" }; const from = { kind: "tab" as const, workspaceId: "pw", tabId: "pt" }; await expect(phone.room.request("a", "chat.interrupt", { ...tab, from })).rejects.toMatchObject( @@ -279,7 +280,7 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); const from = { kind: "tab" as const, workspaceId: "bw", tabId: "bt" }; // consent.answer's params have no `from`: parsing them drops it. const params = { id: "c1", answer: "once" as const, from } as { id: string; answer: "once" }; @@ -303,7 +304,7 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); const params = { workspaceId: "w1", tabId: "t1", set: { changes: { web_search: "disabled" } } }; await expect(b.room.request("a", "chat.config", params)).rejects.toMatchObject({ code: RpcErrorCode.Forbidden, @@ -329,11 +330,11 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]?.serves).toEqual(["sessions", "chat.control"]); control = false; a.room.announce(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]?.serves).toEqual(["sessions"]); await expect( b.room.request("a", "chat.interrupt", { workspaceId: "w1", tabId: "t1" }), @@ -348,7 +349,7 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]?.app).toEqual({ name: "NexusCode", version: "0.0.0-test", @@ -358,7 +359,7 @@ describe("the room", () => { expect(a.room.state().peers[0]?.app).toEqual({ name: "NexusCode", version: "0.0.0-test" }); theme = "github-light"; a.room.announce(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]?.app.theme).toBe("github-light"); }); @@ -369,9 +370,9 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); a.room.stop(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]?.online).toBe(false); const asked = b.room.request("a", "sessions.list", {}); await expect(asked).rejects.toBeInstanceOf(RpcFailure); @@ -385,7 +386,7 @@ describe("the room", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); relay.tamper = (frame) => (frame.t === "message" ? { ...frame, seq: frame.seq + 1 } : frame); await expect(b.room.request("a", "sessions.list", {})).rejects.toMatchObject({ code: RpcErrorCode.Unavailable, @@ -406,14 +407,14 @@ describe("the room", () => { ); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); for (const frame of relay.between("b", "a")) relay.deliver("a", frame); - await tick(); + await flushRelay(); expect(foreign).toEqual([2]); expect(a.room.state().peers[0]?.serves).toBeUndefined(); // An older version is no reset: the key is not fetched for it. for (const frame of relay.between("a", "b")) relay.deliver("b", frame); - await tick(); + await flushRelay(); expect(older).toEqual([]); }); }); @@ -426,7 +427,7 @@ describe("what the relay keeps and sends again", () => { const b = device(relay, "b", key); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); return { relay, key, a, b }; } @@ -434,7 +435,7 @@ describe("what the relay keeps and sends again", () => { const { relay, a, b } = await pair(); await b.room.request("a", "sessions.list", {}); for (const frame of relay.between("b", "a")) relay.deliver("a", frame); - await tick(); + await flushRelay(); expect(a.served).toHaveLength(1); }); @@ -445,9 +446,9 @@ describe("what the relay keeps and sends again", () => { // Days later, both connected again. a.reopen(); b.reopen(); - await tick(); + await flushRelay(); for (const frame of kept) relay.deliver("a", frame); - await tick(); + await flushRelay(); expect(a.served).toHaveLength(1); // The two said hello again: a new request goes. await b.room.request("a", "sessions.list", {}); @@ -459,10 +460,10 @@ describe("what the relay keeps and sends again", () => { await b.room.request("a", "sessions.list", {}); const kept = relay.between("b", "a"); b.reopen(); - await tick(); + await flushRelay(); // Sealed for a's epoch, which has not changed, but in b's old one. for (const frame of kept) relay.deliver("a", frame); - await tick(); + await flushRelay(); expect(a.served).toHaveLength(1); await b.room.request("a", "sessions.list", {}); expect(a.served).toHaveLength(2); @@ -473,13 +474,13 @@ describe("what the relay keeps and sends again", () => { expect(b.room.state().peers[0]?.rejoins).toBeUndefined(); // a's socket dropped and opened again; the room showed it online all the while. a.reopen(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]).toMatchObject({ id: "a", online: true, rejoins: 1 }); // a itself started over: it counts none of b. expect(a.room.state().peers[0]?.rejoins).toBeUndefined(); // Told again in each presence, and once more for the next connection. a.reopen(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]?.rejoins).toBe(2); // b asks a as before. await b.room.request("a", "sessions.list", {}); @@ -490,14 +491,14 @@ describe("what the relay keeps and sends again", () => { const { relay, key, a, b } = await pair(); const c = device(relay, "c", key); c.room.start(); - await tick(); + await flushRelay(); await b.room.request("a", "sessions.list", {}); for (const frame of relay.between("b", "a")) { relay.deliver("c", frame); // Its `to` is sealed with it: changed, it does not open. relay.deliver("c", { ...frame, to: "c" }); } - await tick(); + await flushRelay(); expect(c.served).toEqual([]); expect(a.served).toHaveLength(1); }); @@ -510,14 +511,14 @@ describe("what the relay keeps and sends again", () => { const b = device(relay, "b", key); b.room.start(); a.room.start(); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]?.serves).toEqual(["sessions", "chat.control"]); const kept = [...relay.between("a", "b")]; serves = ["sessions"]; a.room.announce(); - await tick(); + await flushRelay(); for (const frame of kept) relay.deliver("b", frame); - await tick(); + await flushRelay(); expect(b.room.state().peers[0]?.serves).toEqual(["sessions"]); }); @@ -528,9 +529,9 @@ describe("what the relay keeps and sends again", () => { const b = device(relay, "b", key, { requestTimeoutMs: 10_000 }); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); const asked = b.room.request("a", "sessions.list", {}); - await tick(); + await flushRelay(); b.reopen(); await expect(asked).rejects.toMatchObject({ code: RpcErrorCode.Unavailable, @@ -563,7 +564,7 @@ describe("what goes in a frame", () => { }); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); const failure = await a.room.request("b", "sessions.list", {}).catch((e: RpcFailure) => e); expect(failure).toMatchObject({ code: RpcErrorCode.InternalError }); expect((failure as RpcFailure).message).toContain("too large"); @@ -592,7 +593,7 @@ describe("what goes in a frame", () => { }); a.room.start(); b.room.start(); - await tick(); + await flushRelay(); const update = { watchId: "w1", rev: 1, @@ -612,7 +613,7 @@ describe("what goes in a frame", () => { ], }), ).toBe(false); - await tick(); + await flushRelay(); expect(told).toEqual([["a", "chat.update", update]]); }); }); @@ -654,10 +655,15 @@ describe("the host's file reads", () => { }, }); const client = device(relay, "client", key, { requestTimeoutMs: 5000 }); + const otherHost = device(relay, "other-host", key, { + serves: ["files"], + serve: async () => answered, + }); host.room.start(); + otherHost.room.start(); client.room.start(); try { - await tick(); + await flushRelay(); // 8 reading, 32 waiting; the five after those are refused. const requests = Array.from({ length: 45 }, (_, i) => client.room.request("host", "files.read", read(`/w/${i}`)).then( @@ -665,16 +671,15 @@ describe("the host's file reads", () => { (e: RpcFailure) => e, ), ); - const refused = await Promise.race([ - Promise.all(requests.slice(40)), - new Promise((resolve) => setTimeout(() => resolve(null), 1500)), - ]); - // Told while the reads still wait, not after the request timeout. - expect(refused).not.toBeNull(); - for (const failure of refused ?? []) { - expect(failure).toMatchObject({ code: RpcErrorCode.Unavailable }); - expect((failure as RpcFailure).message).toContain("busy"); + const refused = await Promise.all(requests.slice(40)); + // The first host still holds all its slots. A second host has its own budget. + for (const failure of refused) { + expect(failure).toMatchObject({ + code: RpcErrorCode.Unavailable, + message: expect.stringContaining("busy"), + }); } + expect(await client.room.request("other-host", "files.read", read("/w/f"))).toEqual(answered); release(); const rest = await Promise.all(requests.slice(0, 40)); expect(rest.every((outcome) => outcome === "read")).toBe(true); @@ -682,6 +687,7 @@ describe("the host's file reads", () => { } finally { release(); client.room.stop(); + otherHost.room.stop(); host.room.stop(); } }); @@ -690,6 +696,7 @@ describe("the host's file reads", () => { const relay = new MockRelay(); const key = await roomKey(); let buffered = 1 << 30; + const checkedSocket = Promise.withResolvers(); let served = 0; const host = device(relay, "host", key, { serves: ["files"], @@ -703,16 +710,21 @@ describe("the host's file reads", () => { { id: "host", name: "host-pc", platform: "darwin" }, handlers, ); - return Object.defineProperty(connection, "bufferedAmount", { get: () => buffered }); + return Object.defineProperty(connection, "bufferedAmount", { + get: () => { + checkedSocket.resolve(); + return buffered; + }, + }); }, }); const client = device(relay, "client", key, { requestTimeoutMs: 5000 }); host.room.start(); client.room.start(); try { - await tick(); + await flushRelay(); const pending = client.room.request("host", "files.read", read("/w/f")); - await new Promise((resolve) => setTimeout(resolve, 100)); + await checkedSocket.promise; expect(served).toBe(0); buffered = 0; // `.resolves` here hung Bun 1.4.4 on Windows past the test timeout; a plain await does not. @@ -732,29 +744,33 @@ describe("the host's file reads", () => { release = resolve; }); let served = 0; + const filled = Promise.withResolvers(); const host = device(relay, "host", key, { serves: ["files"], requestTimeoutMs: 5000, serve: async () => { - served++; + if (++served === 8) filled.resolve(); await gate; return answered; }, }); - const leaving = device(relay, "leaving", key, { requestTimeoutMs: 200 }); + const leaving = device(relay, "leaving", key, { requestTimeoutMs: 5000 }); const staying = device(relay, "staying", key, { requestTimeoutMs: 5000 }); host.room.start(); leaving.room.start(); staying.room.start(); try { - await tick(); + await flushRelay(); // Fill the 8 reads, then queue one from a device that leaves. const holding = Array.from({ length: 8 }, (_, i) => staying.room.request("host", "files.read", read(`/w/${i}`)).catch(() => null), ); - await tick(); + await filled.promise; const lost = leaving.room.request("host", "files.read", read("/w/gone")).catch(() => null); - await tick(); + // This request uses the same inbox without waiting on the file read budget. + await expect(leaving.room.request("host", "sessions.list", {})).rejects.toMatchObject({ + code: RpcErrorCode.Forbidden, + }); leaving.room.stop(); await lost; release(); @@ -763,6 +779,7 @@ describe("the host's file reads", () => { expect(served).toBe(9); } finally { release(); + leaving.room.stop(); staying.room.stop(); host.room.stop(); } @@ -804,7 +821,7 @@ test("peer cache transfer through sealed room requests on open, reopen and same- host.room.start(); client.room.start(); try { - await tick(); + await flushRelay(); const measure = async () => { const requests = relay.between("client", "host").length; const responses = relay.between("host", "client").length; @@ -880,7 +897,7 @@ test("serves file transfers by scope and cleans pending uploads when the sending host.start(); peer.start(); try { - await tick(); + await flushRelay(); const from = { kind: "tab" as const, workspaceId: "pw", tabId: "pt" }; const scoped = { workspaceId: workspace.id, path: "data", size: 0, from }; const absolute = { ...scoped, path: outside, anywhere: true as const }; From c16577aed460d0b13190f51e7a808e385cc6b277 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 17:27:29 +0900 Subject: [PATCH 017/208] test: prune presentation-only renderer assertions - agent-view/panel-mark.test.tsx: drop direct marker markup and placement tests. remote-sessions.test.tsx exercises the shared marker on session rows for shown, held and absent states. Keep panel placement logic. - agent-view/remote-terminal-screen.test.tsx: drop the wrapping class check. App QA can exercise wrapping in a narrow pane. Keep ANSI content, caret and keyboard access coverage. - settings/remote-panel.test.tsx: drop fixed logo colors, font and SVG attributes along with provider data attributes. Keep coverage of available providers, the local-only notice and the usage warning. --- .../components/agent-view/panel-mark.test.tsx | 22 +------------------ .../remote-terminal-screen.test.tsx | 6 ----- .../components/settings/remote-panel.test.tsx | 11 +--------- 3 files changed, 2 insertions(+), 37 deletions(-) diff --git a/tests/unit/renderer/components/agent-view/panel-mark.test.tsx b/tests/unit/renderer/components/agent-view/panel-mark.test.tsx index d41d4b1d6..391a4f1fe 100644 --- a/tests/unit/renderer/components/agent-view/panel-mark.test.tsx +++ b/tests/unit/renderer/components/agent-view/panel-mark.test.tsx @@ -3,10 +3,9 @@ * and another computer's: shown in front of a panel, or held behind another tab. */ import { describe, expect, test } from "bun:test"; -import { renderToStaticMarkup } from "react-dom/server"; import type { SplitNode } from "../../../../../src/renderer/engine"; -const { PanelMark, panelPlaceOf } = await import( +const { panelPlaceOf } = await import( "../../../../../src/renderer/components/agent-view/panel-mark" ); @@ -30,22 +29,3 @@ describe("panelPlaceOf", () => { expect(panelPlaceOf(root, "ws:c")).toBeNull(); }); }); - -describe("PanelMark", () => { - test("a bright bar where shown, a dim one where held, each saying which", () => { - const shown = renderToStaticMarkup(); - expect(shown).toContain('aria-label="Shown in a panel"'); - expect(shown).toContain("bg-[var(--state-selected-indicator)]"); - const held = renderToStaticMarkup(); - expect(held).toContain('aria-label="In a panel, behind another tab"'); - expect(held).toContain("bg-muted-foreground/60"); - }); - - test("its row sets where it sits", () => { - const html = renderToStaticMarkup( - , - ); - expect(html).toContain("top-1 bottom-1"); - expect(html).not.toContain("top-1.5"); - }); -}); diff --git a/tests/unit/renderer/components/agent-view/remote-terminal-screen.test.tsx b/tests/unit/renderer/components/agent-view/remote-terminal-screen.test.tsx index e0240afdd..40c7f8dde 100644 --- a/tests/unit/renderer/components/agent-view/remote-terminal-screen.test.tsx +++ b/tests/unit/renderer/components/agent-view/remote-terminal-screen.test.tsx @@ -64,12 +64,6 @@ describe("the screen", () => { expect(html).not.toContain("\x1b"); }); - test("goes on in the next line where the pane is narrower, as a terminal does", () => { - const html = renderToStaticMarkup(); - expect(html).toContain("whitespace-pre-wrap"); - expect(html).toContain("break-all"); - }); - test("takes the keyboard only where the computer lets this one type", () => { const looking = renderToStaticMarkup(); expect(looking).not.toContain("remote-terminal-input"); diff --git a/tests/unit/renderer/components/settings/remote-panel.test.tsx b/tests/unit/renderer/components/settings/remote-panel.test.tsx index 1b7ee649e..7a651e02f 100644 --- a/tests/unit/renderer/components/settings/remote-panel.test.tsx +++ b/tests/unit/renderer/components/settings/remote-panel.test.tsx @@ -28,17 +28,8 @@ describe("the remote panel's account", () => { expect(both).toContain("Sign in with GitHub"); }); - test("marks each sign-in with its provider, and the dev one as local only", () => { + test("marks the dev sign-in as local only", () => { const html = render({ status: "signed-out", server }, ["google", "github", "dev"]); - expect(html).toContain('data-provider="google"'); - // Google's four-color G, as its branding asks, and Roboto. - for (const color of ["#EA4335", "#4285F4", "#FBBC05", "#34A853"]) { - expect(html).toContain(color); - } - expect(html).toContain("Roboto"); - expect(html).toContain('data-provider="github"'); - expect(html).toContain('fill="currentColor"'); - expect(html).toContain('data-provider="dev"'); expect(html).toContain("Local server only"); }); From 44f12368cba93f56f6e94af161c6ed8c28f5e87d Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 17:30:14 +0900 Subject: [PATCH 018/208] test: speed up timing and retry coverage Advance the fake clock through file-pull retries and Codex child refresh cooldowns. Let PortWatcher lookups settle through microtasks instead of real event loop turns between fake clock steps. Drive terminal startup and SSH shutdown retries with fake timers. Run isolated Go host watchdog and shutdown deadline cases in parallel so their real timeout windows overlap. --- internal/stdioserver/host_idle_test.go | 3 ++ internal/stdioserver/host_stress_test.go | 3 ++ tests/unit/main/cli/file-pull.test.ts | 33 ++++++++++++----- tests/unit/main/pty/ports.test.ts | 10 +++--- .../manager-reattach-lifecycle.test.ts | 35 ++++++++++++------- .../chat/codex-before-handshake.test.ts | 20 +++++++---- .../services/terminal-services.test.ts | 28 +++++++++------ 7 files changed, 91 insertions(+), 41 deletions(-) diff --git a/internal/stdioserver/host_idle_test.go b/internal/stdioserver/host_idle_test.go index 2fb19a74d..74f46edd3 100644 --- a/internal/stdioserver/host_idle_test.go +++ b/internal/stdioserver/host_idle_test.go @@ -23,6 +23,7 @@ func newTestHost() *Host { // Watchdog fires when no inbound line arrives within the limit. func TestIdleWatchdogExitsWhenClientVanishes(t *testing.T) { + t.Parallel() host := newTestHost() exited := make(chan int, 1) host.exit = func(code int) { @@ -53,6 +54,7 @@ func TestIdleWatchdogExitsWhenClientVanishes(t *testing.T) { // runner stalling this goroutine for a while does not read as client silence: // a 60ms limit with 20ms stamps failed on macOS runners. func TestIdleWatchdogStaysAliveWithTraffic(t *testing.T) { + t.Parallel() host := newTestHost() exited := make(chan int, 1) host.exit = func(code int) { @@ -82,6 +84,7 @@ func TestIdleWatchdogStaysAliveWithTraffic(t *testing.T) { // A non-positive limit disables the watchdog entirely. func TestIdleWatchdogDisabledWhenLimitNonPositive(t *testing.T) { + t.Parallel() host := newTestHost() exited := make(chan int, 1) host.exit = func(code int) { diff --git a/internal/stdioserver/host_stress_test.go b/internal/stdioserver/host_stress_test.go index 5592a9bcb..e1fea69f9 100644 --- a/internal/stdioserver/host_stress_test.go +++ b/internal/stdioserver/host_stress_test.go @@ -133,6 +133,7 @@ func (r *constReader) Read(p []byte) (int, error) { // daemon's closes a channel and panics on a second call — and the host // context must be cancelled so the stuck handler can unwind. func TestDrainAndExitCallsExitOnceWhenHandlerIsStuck(t *testing.T) { + t.Parallel() host := New(dispatch.New(), io.NopCloser(strings_reader("")), io.Discard, slog.Default()) var exits atomic.Int32 exited := make(chan struct{}) @@ -164,6 +165,7 @@ func TestDrainAndExitCallsExitOnceWhenHandlerIsStuck(t *testing.T) { // hooks from running: they are what kills the terminals and removes the // hook socket, and an exit without them left both behind. func TestDrainThatGivesUpStillRunsShutdownHooks(t *testing.T) { + t.Parallel() host := New(dispatch.New(), io.NopCloser(strings_reader("")), io.Discard, slog.Default()) exited := make(chan struct{}) host.SetExitFunc(func(int) { close(exited) }) @@ -188,6 +190,7 @@ func TestDrainThatGivesUpStillRunsShutdownHooks(t *testing.T) { // A shutdown hook that hangs cannot hold the exit off for good. func TestHungShutdownHookDoesNotHoldTheExit(t *testing.T) { + t.Parallel() host := New(dispatch.New(), io.NopCloser(strings_reader("")), io.Discard, slog.Default()) exited := make(chan struct{}) host.SetExitFunc(func(int) { close(exited) }) diff --git a/tests/unit/main/cli/file-pull.test.ts b/tests/unit/main/cli/file-pull.test.ts index 39cf31b5e..2da008a70 100644 --- a/tests/unit/main/cli/file-pull.test.ts +++ b/tests/unit/main/cli/file-pull.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test"; import { createHash } from "node:crypto"; import { once } from "node:events"; import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; @@ -303,13 +303,30 @@ test("retries a busy host and saves the complete file", async () => { }); test("reports the busy error after five retries", async () => { - const app = peer(() => fail(RpcErrorCode.Unavailable, "the host is busy reading files")); - const result = await pull(app, "source.bin"); - expect(result.stderr).toContain("the host is busy reading files"); - expect(result.exitCode).not.toBe(0); - expect(reads(app)).toHaveLength(6); - expect(await readdir(cwd)).toEqual([]); -}, 12000); + const firstRead = Promise.withResolvers(); + const app = peer(() => { + firstRead.resolve(); + return fail(RpcErrorCode.Unavailable, "the host is busy reading files"); + }); + jest.useFakeTimers(); + try { + const pending = pull(app, "source.bin"); + await firstRead.promise; + for (let attempt = 1; attempt <= 5; attempt++) { + // Let each busy response schedule its retry before advancing time. + await new Promise((resolve) => setImmediate(resolve)); + expect(reads(app)).toHaveLength(attempt); + jest.advanceTimersToNextTimer(); + } + const result = await pending; + expect(result.stderr).toContain("the host is busy reading files"); + expect(result.exitCode).not.toBe(0); + expect(reads(app)).toHaveLength(6); + expect(await readdir(cwd)).toEqual([]); + } finally { + jest.useRealTimers(); + } +}); test("a failed rename leaves no temporary file", async () => { await mkdir(path.join(cwd, "source.bin")); diff --git a/tests/unit/main/pty/ports.test.ts b/tests/unit/main/pty/ports.test.ts index 239e6a4f7..916d37221 100644 --- a/tests/unit/main/pty/ports.test.ts +++ b/tests/unit/main/pty/ports.test.ts @@ -24,9 +24,8 @@ function host() { const TIMING = { settleMs: 50, busyPollMs: 100, portsPollMs: 150 }; -// The watcher's timers run on a fake clock: `wait` moves it on a few -// milliseconds at a time, letting what each step starts settle, so the -// watcher sees time pass as it would, without the test waiting for it. +// Advance the fake clock in small steps so a lookup can settle and schedule +// its next timer before the next step. beforeEach(() => jest.useFakeTimers()); afterEach(() => jest.useRealTimers()); @@ -35,7 +34,10 @@ const STEP_MS = 5; async function wait(ms: number): Promise { for (let passed = 0; passed < ms; passed += STEP_MS) { jest.advanceTimersByTime(Math.min(STEP_MS, ms - passed)); - await new Promise((resolve) => setImmediate(resolve)); + // Flush the delayed lookup, the answer, and the follow-up scheduling. + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); } } diff --git a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts index d5152a615..f13531fcf 100644 --- a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts +++ b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts @@ -833,19 +833,28 @@ describe("removing an SSH workspace", () => { channel.emitLifecycle({ type: "degraded" }); channel.shutdownFailures.push(createAgentReconnectError("agent.reconnect-in-progress")); - manager.remove(meta.id); - await new Promise((resolve) => setTimeout(resolve, 400)); - expect(channel.events).toEqual(["agent.shutdown", "agent.shutdown"]); - - channel.answerShutdown(); - await new Promise((resolve) => setTimeout(resolve, 0)); - expect(channel.events).toEqual([ - "agent.shutdown", - "agent.shutdown", - "dispose", - "bootstrap.dispose", - ]); - globalDb.close(); + jest.useFakeTimers(); + try { + manager.remove(meta.id); + // Let the first rejection reach the shutdown loop and schedule its retry. + await new Promise((resolve) => setImmediate(resolve)); + expect(channel.events).toEqual(["agent.shutdown"]); + jest.advanceTimersByTime(400); + await new Promise((resolve) => setImmediate(resolve)); + expect(channel.events).toEqual(["agent.shutdown", "agent.shutdown"]); + + channel.answerShutdown(); + await new Promise((resolve) => setImmediate(resolve)); + expect(channel.events).toEqual([ + "agent.shutdown", + "agent.shutdown", + "dispose", + "bootstrap.dispose", + ]); + } finally { + jest.useRealTimers(); + globalDb.close(); + } }); test("closes a channel whose agent cannot be reached without asking again", async () => { diff --git a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts index 3c5c64f79..099a1dc94 100644 --- a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts +++ b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts @@ -5,7 +5,7 @@ * defaults) waits for the introduction. The real ipc client is spread * under a spy, so later files keep its other exports. */ -import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"; +import { afterEach, describe, expect, jest, mock, spyOn, test } from "bun:test"; import { defaultProfileId } from "../../../../../src/shared/agent-profiles/profiles"; import { ipcContract } from "../../../../../src/shared/ipc/contract"; import type { WorkspaceMeta } from "../../../../../src/shared/types/workspace"; @@ -70,6 +70,7 @@ let hostFolder: { canonicalCwd?: string } = {}; afterEach(() => { for (const c of live.splice(0)) c.dispose(); + jest.useRealTimers(); codex = undefined; sent.length = 0; starts.length = 0; @@ -287,6 +288,7 @@ test("a busy metadata response blocks a historical rewind before paging", async }); test("child events refresh only that child, including an event during its cooldown", async () => { + jest.useFakeTimers(); const children = ["child-a", "child-b"].map((id) => ({ id, parentThreadId: "t1", @@ -304,8 +306,13 @@ test("child events refresh only that child, including an event during its cooldo sent .filter(({ method }) => method === "thread/list" || method === "thread/read") .map(({ method, params }) => [method, (params as { threadId?: string }).threadId]); - await c.prepareSend(); - await Bun.sleep(500); + const flushResponses = () => new Promise((resolve) => setImmediate(resolve)); + const prepared = c.prepareSend(); + await flushResponses(); + jest.advanceTimersByTime(30); // initialize reply from tab() + await prepared; + jest.advanceTimersByTime(500); + await flushResponses(); expect(childRequests()).toEqual([ ["thread/list", undefined], ["thread/read", "child-a"], @@ -328,10 +335,11 @@ test("child events refresh only that child, including an event during its cooldo params: { threadId: "t1", turnId: "parent-turn", itemId: "parent-message", delta: "token" }, }, } as never); - await Bun.sleep(500); + jest.advanceTimersByTime(500); + await flushResponses(); expect(childRequests()).toEqual([]); - const deadline = Date.now() + 2_000; - while (childRequests().length === 0 && Date.now() < deadline) await Bun.sleep(25); + jest.advanceTimersByTime(2_000); + await flushResponses(); expect(childRequests()).toEqual([["thread/read", "child-a"]]); }); diff --git a/tests/unit/renderer/services/terminal-services.test.ts b/tests/unit/renderer/services/terminal-services.test.ts index c95e2f9f2..af5a61a40 100644 --- a/tests/unit/renderer/services/terminal-services.test.ts +++ b/tests/unit/renderer/services/terminal-services.test.ts @@ -138,7 +138,9 @@ const { oscCursorStyle, escapeDroppedPath, } = await import("../../../../src/renderer/services/terminal/controller"); -const { createPtyClient } = await import("../../../../src/renderer/services/terminal/pty-client"); +const { createPtyClient, STARTUP_INPUT_QUIET_MS } = await import( + "../../../../src/renderer/services/terminal/pty-client" +); const { closeGroup } = await import("../../../../src/renderer/state/operations"); const { startTerminalExitListener } = await import("../../../../src/renderer/state/terminal-exit"); const { useLayoutStore } = await import("../../../../src/renderer/state/stores/layout"); @@ -976,7 +978,8 @@ describe("services/terminal controller focus asked for before xterm opens", () = }); describe("services/terminal controller ready for input", () => { - beforeEach(() => resetIpc()); + beforeEach(resetIpc); + afterEach(() => jest.useRealTimers()); /** * A controller whose fonts load when `loaded` is called, and whose session @@ -1003,8 +1006,6 @@ describe("services/terminal controller ready for input", () => { return { harness, controller, loaded: () => loaded() }; } - const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); - it("not before it opens; then at once, with no shell to wait for", async () => { const { controller, loaded } = terminal("tab-ready-ended"); expect(controller.input("x", "keys")).toBe(false); @@ -1018,31 +1019,38 @@ describe("services/terminal controller ready for input", () => { }); it("tells a wait no once it is gone, or after it", async () => { + jest.useFakeTimers(); const gone = terminal("tab-ready-gone"); const waiting = gone.controller.whenReady(1000); gone.controller.dispose(); expect(await waiting).toBe(false); const slow = terminal("tab-ready-slow"); - expect(await slow.controller.whenReady(5)).toBe(false); + const timedOut = slow.controller.whenReady(5); + jest.advanceTimersByTime(5); + expect(await timedOut).toBe(false); slow.controller.dispose(); }); it("a shell just started: once it has printed its prompt and gone quiet", async () => { + jest.useFakeTimers(); const { harness, controller, loaded } = terminal("tab-ready-shell", { pid: 7 }); let ready: boolean | undefined; - void controller.whenReady(3000).then((answer) => { + const waiting = controller.whenReady(3000).then((answer) => { ready = answer; + return answer; }); loaded(); await flushTerminalInit(); // Open, but the shell has not printed: PowerShell would drop the input. - await pause(20); + jest.advanceTimersByTime(20); + await Promise.resolve(); expect(ready).toBeUndefined(); harness.getPtyOptions()?.onData("PS C:\\> ", false); - await pause(100); + jest.advanceTimersByTime(STARTUP_INPUT_QUIET_MS - 1); + await Promise.resolve(); expect(ready).toBeUndefined(); - await pause(400); - expect(ready).toBe(true); + jest.advanceTimersByTime(1); + expect(await waiting).toBe(true); controller.dispose(); }); From f7c48c4e7abb6e8214a746f59d2a170514c77dd7 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 17:30:14 +0900 Subject: [PATCH 019/208] ci: keep the Bun install cache on the checkout volume MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Windows Tests steps spent 46–58 seconds installing dependencies while the native modules cache hit on both runs. Keep Bun's package cache on the checkout volume so the Windows hardlink backend can link into node_modules. --- .github/workflows/ci.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 75a92e037..648c13150 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -131,6 +131,10 @@ jobs: # and the costly one was cpu-features (ssh2's optional CPU probe): a # node-gyp build of one to two minutes on Windows. The native module # steps below are the rest of our postinstall. + env: + # Windows checks out on D: while the default cache is in the home + # directory on C:. Bun can hardlink packages on the same volume. + BUN_INSTALL_CACHE_DIR: ${{ github.workspace }}/.cache/bun-install run: bun install --frozen-lockfile --ignore-scripts - name: Cache native modules From 809204fc694c2210ba39afeafdcab09bc3a1bfa9 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:27:00 +0900 Subject: [PATCH 020/208] fix(editor): retain open buffers through remote session expiry Co-Authored-By: Claude Opus 5.5 --- src/renderer/services/editor/model/cache.ts | 68 ++++++++- src/renderer/services/editor/model/entry.ts | 4 +- .../editor/model-cache-reconnect.test.ts | 129 ++++++++++++++++++ 3 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 tests/unit/renderer/services/editor/model-cache-reconnect.test.ts diff --git a/src/renderer/services/editor/model/cache.ts b/src/renderer/services/editor/model/cache.ts index 863a5c07d..9a1141c10 100644 --- a/src/renderer/services/editor/model/cache.ts +++ b/src/renderer/services/editor/model/cache.ts @@ -7,11 +7,14 @@ import type * as Monaco from "monaco-editor"; import { fileUriToAbsolutePath } from "../../../../shared/fs/file-uri"; import { parseWorkspaceUri, workspaceUriFor } from "../../../../shared/fs/workspace-uri"; import { resolveLspPresetLanguageId } from "../../../../shared/lsp/config"; +import { type Tab, useTabsStore } from "../../../state/stores/tabs"; +import { selectIsWorkspaceOnline, useWorkspacesStore } from "../../../state/stores/workspaces"; import { registerWorkspaceCleanup } from "../../../state/workspace-cleanup"; import type { FileErrorCode } from "../../../utils/file-error"; import type { TextEncoding } from "../encoding/text-encoding"; import { registerKnownModelUri } from "../lsp/known-uris"; import { initializeMonacoSingleton, requireMonaco } from "../runtime/monaco-singleton"; +import { workingFileOfDiff } from "../tabs/diff-working-file"; import { attachDirtyTracker } from "./dirty-tracker"; import { cleanupEntry, @@ -19,6 +22,7 @@ import { createUntitledEntry, errorCodeFromUnknown, notifySubscribers, + reconcileIfStatChanged, rehydrateEntry, reloadEntryFromDisk, snapshot, @@ -99,6 +103,7 @@ export function initializeModelCache(monaco: typeof Monaco): void { } const entries = new Map(); +const retainedByTabs = new Map(); /** * External loads in flight by cacheUri. Their entry is registered only @@ -120,6 +125,37 @@ function cacheUriForInput(input: EditorInput): string { return cacheUriFor(input.workspaceId, input.filePath); } +/** Whether an open tab still owns this editable buffer between view mounts. */ +function hasOpenBufferTab(entry: ModelEntry, tabs: Record | undefined): boolean { + if (!tabs) return false; + const { filePath, workspaceId } = entry.input; + return Object.values(tabs).some((tab) => { + if (entry.origin === "untitled") { + return tab.type === "untitled" && `Untitled-${tab.props.untitledIndex}` === filePath; + } + if (tab.type === "editor") { + return tab.props.origin !== "external" && tab.props.filePath === filePath; + } + return ( + tab.type === "editor.diff" && + tab.props.workspaceId === workspaceId && + workingFileOfDiff(tab.props) === filePath + ); + }); +} + +// Remote views unmount when the connection expires. An open tab keeps its +// loaded model until a view acquires it again or the tab is closed. +useTabsStore.subscribe((state, previous) => { + for (const [cacheUri, entry] of retainedByTabs) { + const { workspaceId } = entry.input; + const tabs = state.byWorkspace[workspaceId]; + if (tabs !== previous.byWorkspace[workspaceId] && !hasOpenBufferTab(entry, tabs)) { + disposeReleasedEntry(cacheUri, entry); + } + } +}); + export function subscribeOnRelease(callback: ModelReleaseSubscriber): () => void { releaseSubscribers.add(callback); return () => { @@ -198,6 +234,14 @@ export async function acquireModel(input: EditorInput): Promise 0) return; + const workspace = useWorkspacesStore + .getState() + .workspaces.find((w) => w.id === input.workspaceId); + if ( + workspace && + workspace.location.kind !== "local" && + entry.origin !== "external" && + entry.model && + !entry.model.isDisposed() && + hasOpenBufferTab(entry, useTabsStore.getState().byWorkspace[input.workspaceId]) + ) { + retainedByTabs.set(cacheUri, entry); + return; + } + + disposeReleasedEntry(cacheUri, entry); +} + +/** Evict a model after its final view and tab owners are gone. */ +function disposeReleasedEntry(cacheUri: string, entry: ModelEntry): void { + retainedByTabs.delete(cacheUri); entries.delete(cacheUri); const released: ReleasedModelInfo = { input: entry.input, @@ -447,6 +512,7 @@ export function forceDisposeExternalsForWorkspace(workspaceId: string): void { const isUntitledForWorkspace = entry.origin === "untitled" && entry.input.workspaceId === workspaceId; if (isExternalForWorkspace || isUntitledForWorkspace) { + retainedByTabs.delete(cacheUri); entries.delete(cacheUri); cleanupEntry(entry); } diff --git a/src/renderer/services/editor/model/entry.ts b/src/renderer/services/editor/model/entry.ts index fee08b77a..751952f9d 100644 --- a/src/renderer/services/editor/model/entry.ts +++ b/src/renderer/services/editor/model/entry.ts @@ -399,12 +399,12 @@ export async function reconcileExternalChange(entry: ModelEntry): Promise * save and reload). Any stat failure falls through to the full reconcile, * which owns error handling. */ -async function reconcileIfStatChanged(entry: ModelEntry): Promise { +export async function reconcileIfStatChanged(entry: ModelEntry): Promise { if (entry.disposed) return; const deps = depsFor(entry); try { const loaded = deps.getDirtyEntry(entry.cacheUri); - if (loaded) { + if (loaded && entry.phase === "ready") { const stat = await deps.statFileForModel(entry.input); if (entry.disposed) return; if (stat.mtime === loaded.loadedMtime && stat.size === loaded.loadedSize) return; diff --git a/tests/unit/renderer/services/editor/model-cache-reconnect.test.ts b/tests/unit/renderer/services/editor/model-cache-reconnect.test.ts new file mode 100644 index 000000000..1495b63ea --- /dev/null +++ b/tests/unit/renderer/services/editor/model-cache-reconnect.test.ts @@ -0,0 +1,129 @@ +import { expect, mock, test } from "bun:test"; +import { useTabsStore } from "../../../../../src/renderer/state/stores/tabs"; +import { useWorkspacesStore } from "../../../../../src/renderer/state/stores/workspaces"; +import { untitledCacheUriFor } from "../../../../../src/shared/fs/workspace-uri"; + +const workspaceId = "model-cache-reconnect"; +const rootPath = "/remote"; +const file = { workspaceId, filePath: "/remote/file.txt" }; +const untitled = { workspaceId, filePath: "Untitled-1", origin: "untitled" as const }; +const disk = { + content: "disk", + encoding: "utf8" as const, + isBinary: false, + mtime: "T1", + sizeBytes: 4, +}; + +mock.module("../../../../../src/renderer/ipc/client", () => ({ + ipcCallResult: async (channel: string, method: string) => { + if (channel === "fs" && method === "readFile") { + return { ok: true, value: { kind: "text", ...disk } }; + } + if (channel === "fs" && method === "stat") { + return { ok: true, value: { mtime: disk.mtime, size: disk.sizeBytes } }; + } + throw new Error(`Unexpected IPC: ${channel}.${method}`); + }, + ipcListen: () => () => {}, +})); + +/** Simulates a model instance with edits and undo surviving view disposal. */ +function makeModel(content: string) { + const history = [content]; + const listeners = new Set<(event: { changes: [] }) => void>(); + let disposed = false; + return { + getValue: () => history.at(-1), + getLanguageId: () => "plaintext", + getAlternativeVersionId: () => history.length, + onDidChangeContent(listener: (event: { changes: [] }) => void) { + listeners.add(listener); + return { dispose: () => listeners.delete(listener) }; + }, + isDisposed: () => disposed, + dispose() { + disposed = true; + history.length = 0; + }, + edit(text: string) { + history.push(text); + for (const listener of listeners) listener({ changes: [] }); + }, + undo() { + history.pop(); + for (const listener of listeners) listener({ changes: [] }); + }, + }; +} + +mock.module("../../../../../src/renderer/services/editor/runtime/monaco-singleton", () => ({ + requireMonaco: () => ({ + Uri: { parse: (value: string) => ({ toString: () => value }) }, + editor: { getModel: () => null, createModel: makeModel }, + }), +})); + +const { acquireModel, cacheUriFor, getModelSnapshot, releaseModel } = await import( + "../../../../../src/renderer/services/editor/model/cache" +); +const { isDirty } = await import("../../../../../src/renderer/services/editor/model/dirty-tracker"); + +test("open SSH file and Untitled models keep dirty edits and Undo across session expiry", async () => { + const workspaces = useWorkspacesStore.getState(); + const tabs = useTabsStore.getState(); + workspaces.upsert({ + id: workspaceId, + rootPath, + name: "Remote", + location: { kind: "ssh", host: "example.invalid", remotePath: rootPath }, + colorTone: "default", + pinned: false, + sortOrder: 1, + pinnedSortOrder: 0, + tabs: [], + }); + tabs.createTab(workspaceId, { type: "editor", props: file }); + tabs.createTab(workspaceId, { type: "untitled", props: { untitledIndex: 1 } }); + + try { + workspaces.setConnectionStatus(workspaceId, "connected"); + const fileModel = (await acquireModel(file)).model as unknown as ReturnType; + const untitledModel = (await acquireModel(untitled)).model as unknown as ReturnType< + typeof makeModel + >; + fileModel.edit("dirty file"); + untitledModel.edit("dirty untitled"); + + // Simulate ContentPool unmounting and releasing its last references. + workspaces.setConnectionStatus(workspaceId, "held-then-expired"); + releaseModel(file); + releaseModel(untitled); + expect(isDirty(cacheUriFor(workspaceId, file.filePath))).toBe(true); + expect(isDirty(untitledCacheUriFor(workspaceId, 1))).toBe(true); + + workspaces.setConnectionStatus(workspaceId, "connected"); + expect((await acquireModel(file)).model).toBe(fileModel as never); + expect((await acquireModel(untitled)).model).toBe(untitledModel as never); + expect(fileModel.getValue()).toBe("dirty file"); + expect(untitledModel.getValue()).toBe("dirty untitled"); + fileModel.undo(); + untitledModel.undo(); + expect(fileModel.getValue()).toBe(disk.content); + expect(untitledModel.getValue()).toBe(""); + + workspaces.setConnectionStatus(workspaceId, "held-then-expired"); + releaseModel(file); + releaseModel(untitled); + tabs.closeAllForWorkspace(workspaceId); + expect(getModelSnapshot(file)).toBeNull(); + expect(getModelSnapshot(untitled)).toBeNull(); + expect(fileModel.isDisposed()).toBe(true); + expect(untitledModel.isDisposed()).toBe(true); + } finally { + tabs.closeAllForWorkspace(workspaceId); + releaseModel(file); + releaseModel(untitled); + workspaces.remove(workspaceId); + } +}); From 46718e86e6257a2aab60ec8bc315b51e50c420bc Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:27:47 +0900 Subject: [PATCH 021/208] fix(chat): reset the Codex cursor when the agent loses its log Co-Authored-By: Claude Opus 5.5 --- .../services/chat/codex-controller.ts | 23 +++- src/renderer/services/chat/codex-model.ts | 46 ++++++-- src/renderer/services/chat/model.ts | 2 +- .../chat/codex-before-handshake.test.ts | 102 ++++++++++++++++++ 4 files changed, 162 insertions(+), 11 deletions(-) diff --git a/src/renderer/services/chat/codex-controller.ts b/src/renderer/services/chat/codex-controller.ts index 956fe1490..4dfa24765 100644 --- a/src/renderer/services/chat/codex-controller.ts +++ b/src/renderer/services/chat/codex-controller.ts @@ -40,6 +40,7 @@ import { codexModelsOf, emptyCodexModel, idKey, + loseCodexLog, nextThreadModel, shownUserText, } from "./codex-model"; @@ -1205,11 +1206,21 @@ export class CodexController { } return; } - // A new agent: what the tab showed stays, and the thread goes on when it starts again. + // The next program starts a fresh log for the same conversation. + this.limitsReadable = false; + this.ready = Promise.resolve(false); + this.canonicalCwd = undefined; + this.deferToolSendsForTurn = undefined; this.update((prev) => ({ ...prev, phase: "ended", - model: { ...this.model, process: "exited", running: false, turn: null, permissions: [] }, + model: loseCodexLog(this.model), + // In-flight entries keep their identity until delivery settles. + queue: prev.queue.map((item) => + item.afterTool !== undefined && item.status !== "sending" + ? { ...item, afterTool: 0 } + : item, + ), })); this.rejectPending("the program is gone"); } @@ -1456,12 +1467,17 @@ export class CodexController { this.state.queue, (update) => this.update(update), async (next) => { + const offset = this.model.logSeqOffset; const held = await this.sendMessage(next.text, next.images, { from: next.from, id: next.id, queued: next, }); - if (held) return held.afterTurn ? { ...next, afterTool: undefined } : next; + if (!held) return; + if (held.afterTurn) return { ...next, afterTool: undefined }; + if (next.afterTool !== undefined && offset !== this.model.logSeqOffset) + return { ...next, afterTool: 0 }; + return next; }, (error) => error instanceof CodexReplyError, (id) => this.sawQueuedMessage(id), @@ -1656,6 +1672,7 @@ export class CodexController { /** Answers an approval or a question the server asked. */ async answerPermission(request: PermissionRequest, answer: PermissionAnswer): Promise { + if (!this.model.permissions.includes(request)) return; const asked = this.model.requests[request.requestId]; if (!asked) return; const id = JSON.parse(request.requestId) as string | number; diff --git a/src/renderer/services/chat/codex-model.ts b/src/renderer/services/chat/codex-model.ts index c894b00d0..972de6206 100644 --- a/src/renderer/services/chat/codex-model.ts +++ b/src/renderer/services/chat/codex-model.ts @@ -47,6 +47,7 @@ import { num, type PermissionRequest, rec, + stopRunningTasks, stopRunningTools, str, type TaskInfo, @@ -85,6 +86,8 @@ export interface CodexServerRequest { } export interface CodexModel extends ChatModel { + /** Keeps sequence-based item keys unique across the tab's agent logs. */ + logSeqOffset?: number; /** The thread the program runs, once it started or resumed one. */ threadId?: string; appServerVersion?: string; @@ -138,6 +141,33 @@ export function emptyCodexModel(): CodexModel { return { ...emptyModel(), blocks: {}, requests: {}, originals: {} }; } +/** Keeps the conversation when the agent loses its log and sequence counter. */ +export function loseCodexLog(prev: CodexModel): CodexModel { + const draft = new Draft({ + ...prev, + logSeqOffset: (prev.logSeqOffset ?? 0) + prev.lastSeq, + lastSeq: 0, + process: "exited", + running: false, + turn: null, + turnId: undefined, + toolCompletedSeq: undefined, + interrupting: false, + streaming: null, + permissions: [], + requests: {}, + outgoing: {}, + blocks: {}, + forkSource: undefined, + reviewTurn: undefined, + mcpServers: undefined, + mcpLogin: undefined, + }); + stopRunningTools(draft); + stopRunningTasks(draft, undefined); + return draft.next; +} + /** * The model a tab starts another thread with (/new, /resume): empty but * for what is the program's or the account's, shown on while the next @@ -212,6 +242,7 @@ export function applyCodexLine( const message = rec(line.message); if (!message) return draft.next; const at = line.at ?? (line.replay ? undefined : now); + const keySeq = (prev.logSeqOffset ?? 0) + line.seq; if (line.dir === "sys" && message.event === "snapshot") { const path = str(message.path); const before = message.before; @@ -219,7 +250,7 @@ export function applyCodexLine( draft.next.originals = { ...draft.next.originals, [path]: before }; } } else if (line.dir === "sys") { - applySys(draft, message, line.seq, at); + applySys(draft, message, keySeq, at); if (message.event === "start") draft.next.canonicalCwd = str(message.canonicalCwd); if (message.event === "start" || message.event === "exit") { // A program's requests and turn end with it; the thread goes on. @@ -231,7 +262,7 @@ export function applyCodexLine( draft.next.mcpServers = undefined; draft.next.mcpLogin = undefined; } - } else if (line.dir === "in") applyIn(draft, message, line.seq, at); + } else if (line.dir === "in") applyIn(draft, message, keySeq, at); else applyOut(draft, message, line.seq, at); return draft.next; } @@ -318,7 +349,7 @@ function applyOut(draft: CodexDraft, message: Rec, seq: number, at: number | und const params = rec(message.params) ?? {}; if (method && key) applyServerRequest(draft, key, method, params); else if (method) applyNotification(draft, method, params, seq, at); - else if (key) applyResponse(draft, key, message, seq, at); + else if (key) applyResponse(draft, key, message, (draft.next.logSeqOffset ?? 0) + seq, at); } function applyResponse( @@ -814,7 +845,8 @@ function applyNotification( at: number | undefined, ): void { const m = draft.next; - const tag = String(seq); + const keySeq = (m.logSeqOffset ?? 0) + seq; + const tag = String(keySeq); // Another thread's (a subagent's) turns and items are not the tab's, nor // its context's size and compactions. const threadId = str(params.threadId); @@ -838,7 +870,7 @@ function applyNotification( return; } case "turn/completed": - applyTurnCompleted(draft, rec(params.turn) ?? {}, seq, at); + applyTurnCompleted(draft, rec(params.turn) ?? {}, keySeq, at); return; case "item/started": case "item/completed": { @@ -990,7 +1022,7 @@ function applyNotification( return; } case "thread/compacted": - pushCompacted(draft, `n${seq}`, at); + pushCompacted(draft, `n${keySeq}`, at); return; case "thread/goal/updated": m.threadGoal = nextGoal(m.threadGoal, params.goal, at); @@ -1019,7 +1051,7 @@ function applyNotification( } return; } - pushError(draft, str(error?.message) ?? "error", `n${seq}`, at); + pushError(draft, str(error?.message) ?? "error", `n${keySeq}`, at); return; } case "serverRequest/resolved": { diff --git a/src/renderer/services/chat/model.ts b/src/renderer/services/chat/model.ts index 3f312cb40..ea8e28ac1 100644 --- a/src/renderer/services/chat/model.ts +++ b/src/renderer/services/chat/model.ts @@ -858,7 +858,7 @@ function applyTask(draft: Draft, message: Rec, at: number | undefined): void { } /** The program ended: so did the tasks it ran. */ -function stopRunningTasks(draft: Draft, at: number | undefined): void { +export function stopRunningTasks(draft: Draft, at: number | undefined): void { const m = draft.next; let tasks: Record | null = null; for (const task of Object.values(m.tasks)) { diff --git a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts index 099a1dc94..f9d0839c8 100644 --- a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts +++ b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts @@ -37,8 +37,10 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ } } if (method === "send") codex?.(args.message as Message); + if (method === "replay") return Promise.resolve({ ok: true, value: replayResponse?.() }); if (method === "codexStart") { starts.push(args); + onStart?.(); const value = { ok: true, pid: 1, attached: false, version: null, ...hostFolder }; return Promise.resolve({ ok: true, @@ -67,6 +69,8 @@ const live: Controller[] = []; const sent: Message[] = []; const starts: Message[] = []; let hostFolder: { canonicalCwd?: string } = {}; +let replayResponse: (() => unknown) | undefined; +let onStart: (() => void) | undefined; afterEach(() => { for (const c of live.splice(0)) c.dispose(); @@ -77,6 +81,8 @@ afterEach(() => { catalogCalls.length = 0; invalidateCodexHistory(catalogWorkspace); hostFolder = {}; + replayResponse = undefined; + onStart = undefined; }); /** A tab whose program is not running and answers initialize a while after it is asked. */ @@ -120,6 +126,102 @@ function tab(respond?: (message: Message) => unknown | Promise): Contro const order = () => sent.map((m) => m.method); +test("resumes a Codex thread after agent replacement and queues against the new log", async () => { + jest.useFakeTimers(); + const c = tab(); + let seq = 400; + const line = (dir: "sys" | "in" | "out", message: Message, replay = false) => + c.receive({ seq: ++seq, dir, message, replay } as never); + const turn = (id: string) => + line("out", { method: "turn/started", params: { threadId: "t1", turn: { id } } }); + const approve = (turnId: string) => + line("out", { + id: 1, + method: "item/commandExecution/requestApproval", + params: { turnId, command: "pwd" }, + }); + codex = () => {}; + replayResponse = () => { + line("sys", { event: "start" }, true); + line("in", { id: "resume", method: "thread/resume" }, true); + line("out", { id: "resume", result: { thread: { id: "t1" } } }, true); + line( + "in", + { method: "turn/start", params: { input: [{ type: "text", text: "old prompt" }] } }, + true, + ); + line("sys", { event: "dropped" }, true); + return { found: true, running: true, truncated: false, lastSeq: seq }; + }; + await c.open(); + turn("old"); + approve("old"); + await c.sendWithTiming("queued prompt", [], "next", undefined, undefined, "queued"); + const oldPermission = c.model.permissions[0]; + expect(oldPermission?.requestId).toBe("1"); + expect(c.state.queue[0]?.afterTool).toBe(seq); + + c.held(); + replayResponse = () => ({ found: false, running: false, truncated: false, lastSeq: 0 }); + await c.resync(); + expect(c.model.lastSeq).toBe(0); + expect(c.model.permissions).toEqual([]); + expect(c.model.requests).toEqual({}); + await c.answerPermission(oldPermission, { kind: "allow" }); + expect(c.state.queue[0]?.afterTool).toBe(0); + + seq = 0; + const steered = Promise.withResolvers(); + onStart = () => line("sys", { event: "start" }); + codex = (message) => { + sent.push(message); + line("in", message); + if (message.id === undefined) return; + const result = message.method === "thread/resume" ? { thread: { id: "t1" } } : {}; + line("out", { id: message.id, result }); + if (message.method === "turn/steer") steered.resolve(message); + }; + await c.prepareSend(); + expect(sent.find((m) => m.method === "thread/resume")?.params).toMatchObject({ + threadId: "t1", + excludeTurns: true, + }); + expect(c.model.process).toBe("running"); + expect(c.model.items.filter((item) => item.kind === "user").map((item) => item.text)).toEqual([ + "old prompt", + ]); + expect(new Set(c.model.items.map((item) => item.key)).size).toBe(c.model.items.length); + + turn("new"); + approve("new"); + c.flushNow(); + expect(c.model.requests["1"]?.params.turnId).toBe("new"); + const writes = sent.length; + await c.answerPermission(oldPermission, { kind: "allow" }); + expect(sent).toHaveLength(writes); + await c.answerPermission(c.model.permissions[0], { kind: "allow" }); + expect(order()).not.toContain("turn/steer"); + line("out", { + method: "item/completed", + params: { + threadId: "t1", + turnId: "new", + item: { id: "cmd", type: "commandExecution", command: "pwd", status: "completed" }, + }, + }); + c.flushNow(); + expect(c.model.toolCompletedSeq).toBe(seq); + expect((await steered.promise).params).toMatchObject({ + threadId: "t1", + expectedTurnId: "new", + input: [{ type: "text", text: "queued prompt" }], + }); + seq = 404; + line("sys", { event: "dropped" }); + c.flushNow(); + expect(new Set(c.model.items.map((item) => item.key)).size).toBe(c.model.items.length); +}); + describe("what a Codex tab asks as its program starts", () => { test("goes after the program knows the app", async () => { const c = tab(); From d80d6ff019fda02df9fc9afff521244b46d2228a Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:30:28 +0900 Subject: [PATCH 022/208] fix(editor): preserve newer edits during manual disk reads Co-Authored-By: Claude Opus 5.5 --- .../components/workbench/encoding-segment.tsx | 4 +- src/renderer/services/cli/actions.ts | 4 +- src/renderer/services/editor/model/cache.ts | 14 +-- src/renderer/services/editor/model/entry.ts | 114 +++++++++--------- .../services/editor/model/file-loader.ts | 10 +- src/renderer/services/editor/model/types.ts | 7 +- src/renderer/services/editor/save/service.ts | 8 +- .../services/editor/disk-diverged.test.ts | 93 +++++++++++++- .../editor/model-cache-reconnect.test.ts | 65 ++++++++-- .../services/editor/save-service.test.ts | 17 +++ 10 files changed, 250 insertions(+), 86 deletions(-) diff --git a/src/renderer/components/workbench/encoding-segment.tsx b/src/renderer/components/workbench/encoding-segment.tsx index b477108d0..32a5d442f 100644 --- a/src/renderer/components/workbench/encoding-segment.tsx +++ b/src/renderer/components/workbench/encoding-segment.tsx @@ -23,7 +23,6 @@ import { subscribeModel, } from "../../services/editor/model/cache"; import { isDirty, subscribeFileDirty } from "../../services/editor/model/dirty-tracker"; -import { setEncodingOverride } from "../../services/editor/model/file-loader"; import { reportSaveFailure, saveModelInteractive } from "../../services/editor/save/service"; import { useLayoutStore } from "../../state/stores/layout"; import { useTabsStore } from "../../state/stores/tabs"; @@ -181,8 +180,7 @@ function EncodingPopover({ function choose(encoding: TextEncoding): void { onClose(); if (mode === "reopen") { - setEncodingOverride(input, encoding); - void reloadModelFromDisk(input); + void reloadModelFromDisk(input, encoding); } else { void saveModelInteractive(input, { encoding }).then(reportSaveFailure); } diff --git a/src/renderer/services/cli/actions.ts b/src/renderer/services/cli/actions.ts index 8901330a5..c41430dd7 100644 --- a/src/renderer/services/cli/actions.ts +++ b/src/renderer/services/cli/actions.ts @@ -336,8 +336,8 @@ export const actionHandlers: { const tab = tabRecord(workspaceId, tabId); const input = fileOfTab(workspaceId, tab); if (!hasUnsavedChanges(workspaceId, tab)) return { filePath: input.filePath, reverted: false }; - await reloadModelFromDisk(input); - return { filePath: input.filePath, reverted: !hasUnsavedChanges(workspaceId, tab) }; + const applied = await reloadModelFromDisk(input); + return { filePath: input.filePath, reverted: applied && !hasUnsavedChanges(workspaceId, tab) }; }, "browser.open": async ({ workspaceId, url, placement }) => { diff --git a/src/renderer/services/editor/model/cache.ts b/src/renderer/services/editor/model/cache.ts index 9a1141c10..7eaacbb41 100644 --- a/src/renderer/services/editor/model/cache.ts +++ b/src/renderer/services/editor/model/cache.ts @@ -365,15 +365,15 @@ export function getEntryLspVersion(cacheUri: string): number | null { } /** - * Reload the model entry for `input` from disk, replacing the buffer with - * the on-disk content. Used by the conflict-resolution "reload" path. - * Returns false when no tracked entry exists for the input. + * Ask to revert a buffer to disk, or reopen a clean buffer in `encoding`. + * Returns true only when the requested disk result was applied. */ -export async function reloadModelFromDisk(input: EditorInput): Promise { +export async function reloadModelFromDisk( + input: EditorInput, + encoding?: TextEncoding, +): Promise { const entry = entries.get(cacheUriForInput(input)); - if (!entry) return false; - await reloadEntryFromDisk(entry); - return true; + return entry ? reloadEntryFromDisk(entry, encoding) : false; } /** diff --git a/src/renderer/services/editor/model/entry.ts b/src/renderer/services/editor/model/entry.ts index 751952f9d..49a584540 100644 --- a/src/renderer/services/editor/model/entry.ts +++ b/src/renderer/services/editor/model/entry.ts @@ -4,6 +4,7 @@ import { absolutePathToFileUri } from "../../../../shared/fs/file-uri"; import { isLspEnabledForWorkspace } from "../../../state/stores/lsp-settings"; import { type FileErrorCode, parseFileErrorCode } from "../../../utils/file-error"; +import type { TextEncoding } from "../encoding/text-encoding"; import { registerKnownModelUri, unregisterKnownModelUri } from "../lsp/known-uris"; import { isLspLanguage } from "../lsp/language"; import { monacoContentChangesToLsp } from "../lsp/monaco-converters"; @@ -22,7 +23,9 @@ import { markSaved as markDirtyTrackerSaved, } from "./dirty-tracker"; import { + type FileLoadResult, readFileForModel, + setEncodingOverride, statFileForModel, subscribeFsChanged, subscribeGitStatusChanged, @@ -361,24 +364,7 @@ export async function reconcileExternalChange(entry: ModelEntry): Promise const model = entry.model; if (!model || model.isDisposed()) return; - entry.encoding = result.encoding; - entry.phase = "ready"; - entry.errorCode = undefined; - entry.diskDiverged = undefined; - if (model.getValue() !== result.content) { - model.setValue(result.content); - } - entry.lastLoadedValue = model.getValue(); - - deps.markDirtyTrackerSaved({ - cacheUri: entry.cacheUri, - model, - savedAlternativeVersionId: model.getAlternativeVersionId(), - loadedMtime: result.mtime, - loadedSize: result.sizeBytes, - }); - - notifySubscribers(entry); + applyDiskText(entry, model, result); } catch (error) { if (entry.disposed || entry.diskReadSeq !== seq) return; // The edits exist only in this buffer; keep it editable so the user can @@ -416,59 +402,79 @@ export async function reconcileIfStatChanged(entry: ModelEntry): Promise { } /** - * Force-reload the entry's buffer from disk, discarding any unsaved edits. - * Used by the conflict-resolution "reload" path where the user has explicitly - * chosen to accept the on-disk version. Unlike `reconcileExternalChange`, this - * runs without a dirty guard and always replaces the buffer. - * - * On success: model content = disk content, dirty tracker re-baselined, - * `diskDiverged` cleared, subscribers notified. + * Apply a manual read only while it still owns the generation and the + * buffer is unchanged since the request. An explicit revert authorizes + * discarding existing edits. Reopening with an encoding requires a clean + * buffer when the encoding is chosen. */ -export async function reloadEntryFromDisk(entry: ModelEntry): Promise { - if (entry.disposed) return; +export async function reloadEntryFromDisk( + entry: ModelEntry, + encoding?: TextEncoding, +): Promise { + if (entry.disposed) return false; const deps = depsFor(entry); - // The user asked for this read; reconcile reads already in flight predate - // it and must not land after it. - entry.diskReadSeq = (entry.diskReadSeq ?? 0) + 1; + if (encoding !== undefined && deps.getDirtyEntry(entry.cacheUri)?.isDirty) return false; + + const seq = (entry.diskReadSeq ?? 0) + 1; + entry.diskReadSeq = seq; + const model = entry.model; + const version = model?.getVersionId(); + // getVersionId also changes on undo/redo, even when the text matches again. + const isCurrent = () => + !entry.disposed && + entry.diskReadSeq === seq && + entry.model === model && + (!model || (!model.isDisposed() && model.getVersionId() === version)); try { - const result = await deps.readFileForModel(entry.input); - if (entry.disposed) return; + const result = await deps.readFileForModel(entry.input, encoding); + if (!isCurrent()) return false; if (result.isBinary) { entry.phase = "binary"; entry.diskDiverged = undefined; notifySubscribers(entry); - return; + return true; } - const model = entry.model; - if (!model || model.isDisposed()) return; - - entry.encoding = result.encoding; - entry.phase = "ready"; - entry.errorCode = undefined; - entry.diskDiverged = undefined; - if (model.getValue() !== result.content) { - model.setValue(result.content); - } - entry.lastLoadedValue = model.getValue(); - - deps.markDirtyTrackerSaved({ - cacheUri: entry.cacheUri, - model, - savedAlternativeVersionId: model.getAlternativeVersionId(), - loadedMtime: result.mtime, - loadedSize: result.sizeBytes, - }); + if (!model) return false; - notifySubscribers(entry); + applyDiskText(entry, model, result, encoding); + return true; } catch (error) { - if (entry.disposed) return; + if (!isCurrent()) return false; entry.phase = "error"; entry.errorCode = errorCodeFromUnknown(error); notifySubscribers(entry); + return false; + } +} + +/** Install accepted disk text and update the model's save baseline. */ +function applyDiskText( + entry: ModelEntry, + model: NonNullable, + result: FileLoadResult, + encodingOverride?: TextEncoding, +): void { + entry.encoding = result.encoding; + entry.phase = "ready"; + entry.errorCode = undefined; + entry.diskDiverged = undefined; + if (model.getValue() !== result.content) { + model.setValue(result.content); } + entry.lastLoadedValue = model.getValue(); + if (encodingOverride !== undefined) setEncodingOverride(entry.input, encodingOverride); + + depsFor(entry).markDirtyTrackerSaved({ + cacheUri: entry.cacheUri, + model, + savedAlternativeVersionId: model.getAlternativeVersionId(), + loadedMtime: result.mtime, + loadedSize: result.sizeBytes, + }); + notifySubscribers(entry); } async function notifyDidCloseAfterDidOpen(entry: ModelEntry): Promise { diff --git a/src/renderer/services/editor/model/file-loader.ts b/src/renderer/services/editor/model/file-loader.ts index ec5a03433..c7fc802bf 100644 --- a/src/renderer/services/editor/model/file-loader.ts +++ b/src/renderer/services/editor/model/file-loader.ts @@ -27,7 +27,7 @@ function overrideKey(input: EditorInput): string { return workspaceUriFor(input.workspaceId, input.filePath); } -/** Reads `input` in `encoding` from now on, as Reopen with Encoding asks. */ +/** Remembers the encoding from an applied reopen or a successful save. */ export function setEncodingOverride(input: EditorInput, encoding: TextEncoding): void { encodingOverrides.set(overrideKey(input), encoding); } @@ -76,7 +76,11 @@ export function relPathForInput(input: EditorInput): string { return relPath(input.filePath, workspaceRootForInput(input)); } -export async function readFileForModel(input: EditorInput): Promise { +/** Reads using the requested encoding or the override current when the read starts. */ +export async function readFileForModel( + input: EditorInput, + encoding = encodingOverrides.get(overrideKey(input)), +): Promise { const rp = relPathForInput(input); const result = unwrapIpcResult( await ipcCallResult("fs", "readFile", { workspaceId: input.workspaceId, relPath: rp }), @@ -85,7 +89,7 @@ export async function readFileForModel(input: EditorInput): Promise Promise; + readFileForModel: (input: EditorInput, encoding?: TextEncoding) => Promise; statFileForModel: (input: EditorInput) => Promise<{ mtime: string; size: number }>; getDirtyEntry: typeof getDirtyEntry; subscribeFsChanged: ( diff --git a/src/renderer/services/editor/save/service.ts b/src/renderer/services/editor/save/service.ts index 89acf1dbc..2ac6266d2 100644 --- a/src/renderer/services/editor/save/service.ts +++ b/src/renderer/services/editor/save/service.ts @@ -102,8 +102,8 @@ export function reportSaveFailure(result: SaveResult): void { * cleared to `""` which causes `saveModel` to build `{exists:false}` as the * expected value — matching the writeFile IPC guard. * - **reload**: replaces the buffer with the on-disk content via - * `reloadModelFromDisk`, discarding unsaved edits. Returns `{kind:"not-dirty"}` - * (the buffer is now clean). + * `reloadModelFromDisk`, discarding edits present at approval. Returns + * `{kind:"not-dirty"}` only when the disk version was applied. * - **cancel**: returns the original conflict result unchanged so callers can * decide whether to keep the tab open. * @@ -128,8 +128,8 @@ export async function saveModelInteractive( } if (choice === "reload") { - await reloadModelFromDisk(input); - return { kind: "not-dirty" }; + const applied = await reloadModelFromDisk(input); + return { kind: applied ? "not-dirty" : "superseded" }; } // choice === "overwrite": sync dirty-tracker metadata to the actual disk diff --git a/tests/unit/renderer/services/editor/disk-diverged.test.ts b/tests/unit/renderer/services/editor/disk-diverged.test.ts index b9c7605bb..3b99251fe 100644 --- a/tests/unit/renderer/services/editor/disk-diverged.test.ts +++ b/tests/unit/renderer/services/editor/disk-diverged.test.ts @@ -6,7 +6,7 @@ // We inject deps directly to avoid touching the real dirty-tracker, file-loader, // or Monaco singleton — keeping this test self-contained and fast. -import { describe, expect, test } from "bun:test"; +import { describe, expect, mock, test } from "bun:test"; import type { ModelEntry, ModelEntryDeps, @@ -15,6 +15,7 @@ import { reconcileExternalChange, reloadEntryFromDisk, } from "../../../../../src/renderer/services/editor/model/entry"; +import type { FileLoadResult } from "../../../../../src/renderer/services/editor/model/file-loader"; // --------------------------------------------------------------------------- // Helpers @@ -25,13 +26,16 @@ import { */ function makeModel(value: string) { let content = value; + let version = 1; return { getValue: () => content, setValue: (next: string) => { content = next; + version += 1; }, isDisposed: () => false, getAlternativeVersionId: () => 1, + getVersionId: () => version, }; } @@ -49,6 +53,7 @@ function makeDeps(overrides: Partial = {}): ModelEntryDeps { }), detachDirtyTracker: () => {}, markDirtyTrackerSaved: () => {}, + getDirtyEntry: () => undefined, readFileForModel: () => Promise.resolve({ content: "disk-content", @@ -170,6 +175,92 @@ describe("reconcileExternalChange — clean buffer", () => { // --------------------------------------------------------------------------- describe("reloadEntryFromDisk", () => { + test("keeps edits made while reopening with another encoding", async () => { + const read = Promise.withResolvers(); + const markDirtyTrackerSaved = mock(() => {}); + const entry = makeEntry( + "base", + "base", + makeDeps({ + readFileForModel: () => read.promise, + markDirtyTrackerSaved, + }), + ); + entry.encoding = "utf8"; + + const reload = reloadEntryFromDisk(entry, "shift_jis"); + entry.model?.setValue("typed while waiting"); + read.resolve({ + content: "disk", + mtime: "T2", + sizeBytes: 4, + isBinary: false, + encoding: "shift_jis", + }); + await reload; + + expect(entry.model?.getValue()).toBe("typed while waiting"); + expect(entry.encoding).toBe("utf8"); + expect(entry.lastLoadedValue).toBe("base"); + expect(markDirtyTrackerSaved).not.toHaveBeenCalled(); + }); + + test("preserves edits made after approving a discard even when the read fails", async () => { + const read = Promise.withResolvers(); + const entry = makeEntry( + "discard approved", + "base", + makeDeps({ + readFileForModel: () => read.promise, + }), + ); + const reload = reloadEntryFromDisk(entry); + entry.model?.setValue("edit after approval"); + read.reject(new Error("NOT_FOUND: file deleted")); + await reload; + + expect(entry.phase).toBe("ready"); + expect(entry.model?.getValue()).toBe("edit after approval"); + expect(entry.lastLoadedValue).toBe("base"); + }); + + test("keeps the newer manual reload when an older read completes last without changing the model version", async () => { + const first = Promise.withResolvers(); + const second = Promise.withResolvers(); + const reads = [first.promise, second.promise]; + const markDirtyTrackerSaved = mock(() => {}); + const entry = makeEntry( + "same", + "same", + makeDeps({ + readFileForModel: () => reads.shift()!, + markDirtyTrackerSaved, + }), + ); + + const earlier = reloadEntryFromDisk(entry); + const later = reloadEntryFromDisk(entry); + second.resolve({ + content: "same", + mtime: "T2", + sizeBytes: 4, + isBinary: false, + encoding: "utf8", + }); + await later; + first.resolve({ + content: "old disk", + mtime: "T1", + sizeBytes: 8, + isBinary: false, + encoding: "utf8", + }); + await earlier; + + expect(entry.model?.getValue()).toBe("same"); + expect(markDirtyTrackerSaved).toHaveBeenCalledTimes(1); + }); + test("replaces dirty buffer with disk content and clears diskDiverged", async () => { const deps = makeDeps({ readFileForModel: () => diff --git a/tests/unit/renderer/services/editor/model-cache-reconnect.test.ts b/tests/unit/renderer/services/editor/model-cache-reconnect.test.ts index 1495b63ea..26f48b689 100644 --- a/tests/unit/renderer/services/editor/model-cache-reconnect.test.ts +++ b/tests/unit/renderer/services/editor/model-cache-reconnect.test.ts @@ -14,11 +14,12 @@ const disk = { mtime: "T1", sizeBytes: 4, }; +const readDisk = mock(async () => disk); mock.module("../../../../../src/renderer/ipc/client", () => ({ ipcCallResult: async (channel: string, method: string) => { if (channel === "fs" && method === "readFile") { - return { ok: true, value: { kind: "text", ...disk } }; + return { ok: true, value: { kind: "text", ...(await readDisk()) } }; } if (channel === "fs" && method === "stat") { return { ok: true, value: { mtime: disk.mtime, size: disk.sizeBytes } }; @@ -33,10 +34,17 @@ function makeModel(content: string) { const history = [content]; const listeners = new Set<(event: { changes: [] }) => void>(); let disposed = false; + let version = 1; return { getValue: () => history.at(-1), getLanguageId: () => "plaintext", getAlternativeVersionId: () => history.length, + getVersionId: () => version, + setValue(text: string) { + history.splice(0, history.length, text); + version += 1; + for (const listener of listeners) listener({ changes: [] }); + }, onDidChangeContent(listener: (event: { changes: [] }) => void) { listeners.add(listener); return { dispose: () => listeners.delete(listener) }; @@ -48,10 +56,12 @@ function makeModel(content: string) { }, edit(text: string) { history.push(text); + version += 1; for (const listener of listeners) listener({ changes: [] }); }, undo() { history.pop(); + version += 1; for (const listener of listeners) listener({ changes: [] }); }, }; @@ -64,15 +74,23 @@ mock.module("../../../../../src/renderer/services/editor/runtime/monaco-singleto }), })); -const { acquireModel, cacheUriFor, getModelSnapshot, releaseModel } = await import( - "../../../../../src/renderer/services/editor/model/cache" -); +const { + acquireModel, + cacheUriFor, + getModelSnapshot, + getResolvedModel, + releaseModel, + reloadModelFromDisk, + syncLoadedValueAfterSave, +} = await import("../../../../../src/renderer/services/editor/model/cache"); const { isDirty } = await import("../../../../../src/renderer/services/editor/model/dirty-tracker"); +const { readFileForModel } = await import( + "../../../../../src/renderer/services/editor/model/file-loader" +); -test("open SSH file and Untitled models keep dirty edits and Undo across session expiry", async () => { - const workspaces = useWorkspacesStore.getState(); - const tabs = useTabsStore.getState(); - workspaces.upsert({ +/** Registers a remote workspace without connecting to a host. */ +function addWorkspace(): void { + useWorkspacesStore.getState().upsert({ id: workspaceId, rootPath, name: "Remote", @@ -83,6 +101,12 @@ test("open SSH file and Untitled models keep dirty edits and Undo across session pinnedSortOrder: 0, tabs: [], }); +} + +test("open SSH file and Untitled models keep dirty edits and Undo across session expiry", async () => { + addWorkspace(); + const workspaces = useWorkspacesStore.getState(); + const tabs = useTabsStore.getState(); tabs.createTab(workspaceId, { type: "editor", props: file }); tabs.createTab(workspaceId, { type: "untitled", props: { untitledIndex: 1 } }); @@ -127,3 +151,28 @@ test("open SSH file and Untitled models keep dirty edits and Undo across session workspaces.remove(workspaceId); } }); + +test("a save invalidates an older encoding reopen and keeps the last applied encoding", async () => { + addWorkspace(); + try { + await acquireModel(file); + // Applying a different encoding can leave the text and model version unchanged. + expect(await reloadModelFromDisk(file, "windows-1252")).toBe(true); + expect((await readFileForModel(file)).encoding).toBe("windows-1252"); + + const pending = Promise.withResolvers(); + readDisk.mockImplementationOnce(() => pending.promise); + const reopen = reloadModelFromDisk(file, "utf8"); + syncLoadedValueAfterSave(file, disk.content); + pending.resolve({ ...disk, content: "older disk" }); + + expect(await reopen).toBe(false); + const resolved = getResolvedModel(file); + expect(resolved?.model.getValue()).toBe(disk.content); + expect(resolved?.encoding).toBe("windows-1252"); + expect((await readFileForModel(file)).encoding).toBe("windows-1252"); + } finally { + releaseModel(file); + useWorkspacesStore.getState().remove(workspaceId); + } +}); diff --git a/tests/unit/renderer/services/editor/save-service.test.ts b/tests/unit/renderer/services/editor/save-service.test.ts index b2083341e..d98f18a9b 100644 --- a/tests/unit/renderer/services/editor/save-service.test.ts +++ b/tests/unit/renderer/services/editor/save-service.test.ts @@ -447,6 +447,23 @@ describe("saveModelInteractive — conflict, user chooses reload", () => { // Only the initial conflicting write — no retry expect(ipcCallMock).toHaveBeenCalledTimes(1); }); + + test("reports a skipped conflict reload as superseded so close keeps the buffer open", async () => { + getResolvedModelMock.mockImplementation(() => makeResolvedModel()); + ipcCallMock.mockImplementation(() => + Promise.resolve({ + ok: true as const, + value: { + kind: "conflict", + actual: { exists: true, mtime: "T2", size: 99 }, + }, + }), + ); + showConflictResolutionMock.mockImplementation(() => Promise.resolve("reload")); + reloadModelFromDiskMock.mockImplementationOnce(async () => false); + + expect((await saveModelInteractive(INPUT)).kind).toBe("superseded"); + }); }); describe("saveModelInteractive — conflict, user chooses overwrite", () => { From 88e46ede2eedc3762b231c8bf451f9faeba2a53c Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:30:43 +0900 Subject: [PATCH 023/208] fix(pty): cancel replay when its dialer leaves Co-Authored-By: Claude Opus 5.5 --- cmd/agent/daemon.go | 12 +- cmd/agent/daemon_test.go | 107 +++++++++++- cmd/agent/main.go | 2 +- internal/pty/replay_cancel_test.go | 144 +++++++++++++++++ internal/pty/ring_test.go | 51 +++--- internal/pty/service.go | 225 ++++++++++++++------------ internal/pty/service_test.go | 2 +- internal/pty/terminal_windows_test.go | 2 +- internal/stdioserver/host.go | 6 + 9 files changed, 404 insertions(+), 147 deletions(-) create mode 100644 internal/pty/replay_cancel_test.go diff --git a/cmd/agent/daemon.go b/cmd/agent/daemon.go index 01262bea2..15385d3de 100644 --- a/cmd/agent/daemon.go +++ b/cmd/agent/daemon.go @@ -417,7 +417,8 @@ func runDaemon(root string) { }) git.SetEventSink(host.EmitEvent) lsp.SetEventSink(host.EmitEvent) - pty.SetEventSink(host.EmitEvent) + // Installing this sink also hands renderer credit over after Ready. + pty.SetEventSink(host.Context(), host.EmitEvent) chat.SetEventSink(host.EmitEvent) search.SetEventSink(host.EmitEvent) if hooksrv != nil { @@ -474,15 +475,6 @@ func runDaemon(root string) { close(hostDone) }) - // PTY output debt the previous dialer never acked belongs to it; the - // new renderer will never ack it. Left in place, a session that went - // past the high watermark during a silent disconnect stays paused for - // good, and pty.replay blocks on the same window. Reset after Ready so - // the resumed output does not reach the dialer ahead of that frame, - // and before Run so the dialer's first replay already sees open - // windows. - pty.ResetFlowControl() - // 송신 4s < 판정 5s — 도착 지터 마진. 근거는 proto.HeartbeatSendMs 주석 참조. host.StartHeartbeat(proto.HeartbeatSendMs * time.Millisecond) // The idle watchdog fires after reattachGrace of no inbound traffic. diff --git a/cmd/agent/daemon_test.go b/cmd/agent/daemon_test.go index e500673a2..005079afa 100644 --- a/cmd/agent/daemon_test.go +++ b/cmd/agent/daemon_test.go @@ -7,6 +7,7 @@ import ( "encoding/base64" "encoding/json" "errors" + "fmt" "io" "net" "os" @@ -19,6 +20,7 @@ import ( "github.com/nexus-code/nexus-code/internal/agentrun" "github.com/nexus-code/nexus-code/internal/proto" + "github.com/nexus-code/nexus-code/internal/pty" ) // shortHome returns a temp dir with a SHORT absolute path for use as the @@ -218,7 +220,7 @@ func TestDaemonLongSessionThenReattach(t *testing.T) { // (a renderer that vanished while the socket still absorbed writes), so the // session pauses at the high watermark with ~100 KB of debt. After dialer B // takes over, that stale debt must be dropped and the rest of the output must -// reach B; before ResetFlowControl was wired in, the session stayed paused +// reach B; before takeover reset renderer credit, the session stayed paused // forever. func TestDaemonTakeoverResumesPausedPTY(t *testing.T) { t.Parallel() @@ -284,6 +286,109 @@ func TestDaemonTakeoverResumesPausedPTY(t *testing.T) { t.Fatalf("dialer B never received the output left after the pause (got %d bytes): %v", tail.Len(), sc.Err()) } +// TestDaemonTakeoverCancelsCreditBlockedReplay withholds A's replay ACKs +// while B takes over the daemon's Unix socket. B receives its own full replay. +func TestDaemonTakeoverCancelsCreditBlockedReplay(t *testing.T) { + t.Parallel() + root := t.TempDir() + cmd, runDir := startDaemon(t, agentBinary(t), root, shortHome(t)) + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + sockPath := waitForSocket(t, runDir) + + type frame struct { + proto.Response + Type string `json:"type"` + Event string `json:"event"` + Payload pty.DataPayload `json:"payload"` + } + connect := func() (net.Conn, func() frame) { + conn, err := net.DialTimeout("unix", sockPath, 2*time.Second) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + decoder := json.NewDecoder(conn) + next := func() frame { + var f frame + if err := decoder.Decode(&f); err != nil { + t.Fatalf("read dialer frame: %v", err) + } + if f.Error != nil { + t.Fatalf("request %s failed: %+v", f.ID, f.Error) + } + return f + } + if f := next(); f.Type != "ready" { + t.Fatalf("first frame type = %q, want ready", f.Type) + } + return conn, next + } + send := func(conn net.Conn, id, method, params string) { + if err := json.NewEncoder(conn).Encode(proto.Request{ID: id, Method: method, Params: json.RawMessage(params)}); err != nil { + t.Fatalf("send %s: %v", method, err) + } + } + ack := func(conn net.Conn, id string, count int) { + send(conn, id, "pty.ack", fmt.Sprintf(`{"workspaceId":"ws","tabId":"tab","bytesConsumed":%d}`, count)) + } + chunk := func(f frame) []byte { + data, err := base64.StdEncoding.DecodeString(f.Payload.Chunk) + if err != nil { + t.Fatal(err) + } + return data + } + + a, nextA := connect() + spawnOn(t, a, "tab", root, `stty -echo; head -c 120000 /dev/zero | tr '\0' a; printf '\nHISTORY-END\n'; read -r stop`) + var history strings.Builder + credited := 0 + for replies := 0; replies < 2; { + f := nextA() + if f.ID == "first-ack" || f.ID == "last-ack" { + replies++ + } + if f.Event != pty.EventData { + continue + } + history.Write(chunk(f)) + if credited == 0 && history.Len() >= pty.HighWatermarkBytes { + credited = history.Len() + ack(a, "first-ack", credited) + } + if strings.HasSuffix(history.String(), "HISTORY-END\r\n") { + ack(a, "last-ack", history.Len()-credited) + } + } + + const tab = `{"workspaceId":"ws","tabId":"tab"}` + send(a, "old-replay", "pty.replay", tab) + for received := 0; received < pty.HighWatermarkBytes; { + f := nextA() + if f.ID == "old-replay" { + t.Fatal("old replay finished without credit") + } + if f.Event == pty.EventData && f.Payload.Replay { + received += len(chunk(f)) + } + } + + b, nextB := connect() + send(b, "new-replay", "pty.replay", tab) + var replay strings.Builder + for f := nextB(); f.ID != "new-replay"; f = nextB() { + if f.Event == pty.EventData && f.Payload.Replay { + data := chunk(f) + replay.Write(data) + ack(b, "ack", len(data)) + } + } + if want := "\x1bc" + history.String(); replay.String() != want { + t.Fatalf("replacement replay received %d bytes, want exactly %d bytes starting with terminal reset", replay.Len(), len(want)) + } +} + // A daemon of another workspace sweeping stale run files takes this // workspace's lock for a moment to prove its daemon dead. A daemon starting in // that moment must wait it out instead of exiting with ExitCodeLockHeld as if diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 6a2c800ee..3fec10b47 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -174,7 +174,7 @@ func main() { }) git.SetEventSink(host.EmitEvent) lsp.SetEventSink(host.EmitEvent) - pty.SetEventSink(host.EmitEvent) + pty.SetEventSink(host.Context(), host.EmitEvent) chat.SetEventSink(host.EmitEvent) search.SetEventSink(host.EmitEvent) if hooksrv != nil { diff --git a/internal/pty/replay_cancel_test.go b/internal/pty/replay_cancel_test.go new file mode 100644 index 000000000..11e524b9c --- /dev/null +++ b/internal/pty/replay_cancel_test.go @@ -0,0 +1,144 @@ +package pty + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "sync" + "testing" + "time" +) + +// TestReplayCreditAcrossDialers holds ACKs at the high watermark and verifies +// that cancellation and sink replacement each end the old replay. +func TestReplayCreditAcrossDialers(t *testing.T) { + for _, tc := range []struct { + name string + cancelFirst bool + }{{"disconnect before replacement", true}, {"replace before cancellation", false}} { + t.Run(tc.name, func(t *testing.T) { + svc := New() + ctxA, cancelA := context.WithCancel(context.Background()) + defer cancelA() + ctxB, cancelB := context.WithCancel(context.Background()) + defer cancelB() + key := tabKey{workspaceID: "ws", tabID: "tab"} + sess := newSession(svc, key, nil, nil) + svc.storeSession(key, sess) + history := bytes.Repeat([]byte("a"), HighWatermarkBytes+2*MaxChunkSize) + sess.ringAppend(history) + t.Cleanup(func() { + svc.mu.Lock() + sess.stopped = true + sess.flowCond.Broadcast() + svc.mu.Unlock() + }) + + var gotA, gotB replayCapture + gotA.high = make(chan struct{}) + gotB.high = make(chan struct{}) + svc.SetEventSink(ctxA, gotA.emit) + params := json.RawMessage(`{"workspaceId":"ws","tabId":"tab"}`) + ack := json.RawMessage(`{"workspaceId":"ws","tabId":"tab","bytesConsumed":200000}`) + startReplay := func(ctx context.Context) <-chan error { + done := make(chan error, 1) + go func() { + _, err := svc.Replay(ctx, params) + done <- err + }() + return done + } + oldReplay := startReplay(ctxA) + awaitReplayStep(t, gotA.high) + attachB := func() { + svc.SetEventSink(ctxB, gotB.emit) + } + if tc.cancelFirst { + cancelA() + } else { + attachB() + } + if err := awaitReplayStep(t, oldReplay); !errors.Is(err, context.Canceled) { + t.Fatalf("old replay returned %v, want context cancellation", err) + } + if tc.cancelFirst { + attachB() + } + + newReplay := startReplay(ctxB) + awaitReplayStep(t, gotB.high) + // In the takeover case A's request context is still active. A late + // ACK from it must leave B paused until B sends its own ACK. + _, _ = svc.Ack(ctxA, ack) + svc.mu.Lock() + paused, debt := sess.paused, sess.outstanding + svc.mu.Unlock() + if !paused || debt < HighWatermarkBytes { + t.Fatalf("old ACK changed new dialer's window: paused=%t debt=%d", paused, debt) + } + + liveDone := make(chan struct{}) + go func() { + sess.deliver([]byte("live")) + close(liveDone) + }() + _, _ = svc.Ack(ctxB, ack) + if err := awaitReplayStep(t, newReplay); err != nil { + t.Fatalf("new replay failed: %v", err) + } + awaitReplayStep(t, liveDone) + gotB.mu.Lock() + defer gotB.mu.Unlock() + want := terminalReset + string(history) + if gotB.replay.String() != want || gotB.live.String() != "live" || gotB.replayAfterLive { + t.Fatalf("new dialer output: replay bytes=%d want=%d, live=%q, replay after live=%t", gotB.replay.Len(), len(want), gotB.live.String(), gotB.replayAfterLive) + } + }) + } +} + +// replayCapture signals when replay output fills a renderer's credit window. +type replayCapture struct { + mu sync.Mutex + replay bytes.Buffer + live bytes.Buffer + replayAfterLive bool + high chan struct{} +} + +// emit records output in arrival order and signals the watermark once. +func (c *replayCapture) emit(_ string, payload any) error { + data := payload.(DataPayload) + chunk, err := base64.StdEncoding.DecodeString(data.Chunk) + if err != nil { + return err + } + c.mu.Lock() + defer c.mu.Unlock() + if data.Replay { + c.replayAfterLive = c.replayAfterLive || c.live.Len() > 0 + wasBelow := c.replay.Len() < HighWatermarkBytes + c.replay.Write(chunk) + if wasBelow && c.replay.Len() >= HighWatermarkBytes { + close(c.high) + } + } else { + c.live.Write(chunk) + } + return nil +} + +// awaitReplayStep waits for a test barrier with a deadline for regressions. +func awaitReplayStep[T any](t *testing.T, step <-chan T) T { + t.Helper() + select { + case value := <-step: + return value + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for replay or output") + var zero T + return zero + } +} diff --git a/internal/pty/ring_test.go b/internal/pty/ring_test.go index d54476b57..8ab5adeca 100644 --- a/internal/pty/ring_test.go +++ b/internal/pty/ring_test.go @@ -37,7 +37,6 @@ func newBareSession(ringCap int) *session { readDone: make(chan struct{}), createdAt: time.Now(), } - s.flowCond = sync.NewCond(&s.flowMu) return s } @@ -205,7 +204,7 @@ func TestAccumulateReplayContentMatch(t *testing.T) { t.Parallel() rec := &sinkRecorder{} svc := New() - svc.SetEventSink(rec.sink) + svc.SetEventSink(context.Background(), rec.sink) t.Cleanup(svc.Close) tabID := "replay-match" @@ -246,7 +245,7 @@ func TestReplayRedrawsDeliveredOutput(t *testing.T) { var mu sync.Mutex var live, replayed []byte svc := New() - svc.SetEventSink(func(event string, payload any) error { + svc.SetEventSink(context.Background(), func(event string, payload any) error { dp, ok := payload.(DataPayload) if event != EventData || !ok { return nil @@ -308,7 +307,7 @@ func TestSpawnAttachesToRunningSession(t *testing.T) { t.Parallel() rec := &sinkRecorder{} svc := New() - svc.SetEventSink(rec.sink) + svc.SetEventSink(context.Background(), rec.sink) t.Cleanup(svc.Close) tabID := "spawn-attach" @@ -353,7 +352,7 @@ func TestReplayOrderingNoReversal(t *testing.T) { // then succeed. failRemaining := 1 // fail the first emit call svc := New() - svc.SetEventSink(func(event string, payload any) error { + svc.SetEventSink(context.Background(), func(event string, payload any) error { if event != EventData { return nil } @@ -435,7 +434,7 @@ func TestRingReleasedOnSessionExit(t *testing.T) { svc := New() var mu sync.Mutex var exits []ExitPayload - svc.SetEventSink(func(event string, payload any) error { + svc.SetEventSink(context.Background(), func(event string, payload any) error { if event == EventExit { if ep, ok := payload.(ExitPayload); ok { mu.Lock() @@ -496,21 +495,20 @@ exit 0 } } -// TestResetFlowControlUnblocksZombieDeadlock verifies the fix for the zombie +// TestSetEventSinkClearsPreviousDialerDebt verifies the fix for the zombie // window deadlock scenario: // -// 1. noteEmitted accumulates debt past HighWatermarkBytes without matching acks +// 1. The sink accumulates debt past HighWatermarkBytes without matching acks // (simulating a zombie dialer whose OS socket buffer absorbs writes). // 2. readLoop blocks in waitForOutputWindow — paused=true. -// 3. ResetFlowControl is called (simulating a new dialer wiring its sink). +// 3. A new dialer installs its sink. // 4. pty.replay completes successfully and live output resumes. // -// Without the fix, step 4 would block forever because emitBytes calls -// waitForOutputWindow which re-enters the same paused condition. -func TestResetFlowControlUnblocksZombieDeadlock(t *testing.T) { +// The replay would otherwise block waiting on credit from the previous dialer. +func TestSetEventSinkClearsPreviousDialerDebt(t *testing.T) { t.Parallel() // Phase 1: spawn a PTY that produces continuous output, then drive - // noteEmitted past HighWatermarkBytes without any acks. + // output debt past HighWatermarkBytes without any acks. svc := New() // Sink that succeeds but never triggers acks — models the OS buffer @@ -518,7 +516,7 @@ func TestResetFlowControlUnblocksZombieDeadlock(t *testing.T) { var mu sync.Mutex var afterReset []string zombieActive := true - svc.SetEventSink(func(event string, payload any) error { + sink := func(event string, payload any) error { if event != EventData { return nil } @@ -535,7 +533,8 @@ func TestResetFlowControlUnblocksZombieDeadlock(t *testing.T) { } } return nil - }) + } + svc.SetEventSink(context.Background(), sink) t.Cleanup(svc.Close) tabID := "zombie-deadlock" @@ -562,7 +561,7 @@ sleep 10 sessionFound: // Directly manipulate the session's flow state to simulate the zombie window: - // set outstanding to HighWatermarkBytes and paused=true, as if noteEmitted + // set outstanding to HighWatermarkBytes and paused=true, as if the sink // accumulated that debt without any acks arriving. key := tabKey{workspaceID: testWorkspaceID, tabID: tabID} svc.mu.Lock() @@ -572,27 +571,27 @@ sessionFound: t.Fatal("session not in map") } - sess.flowMu.Lock() + svc.mu.Lock() sess.outstanding = HighWatermarkBytes sess.paused = true - sess.flowMu.Unlock() + svc.mu.Unlock() - // Phase 2: simulate new dialer wiring — ResetFlowControl must unblock. + // Phase 2: simulate new dialer wiring — SetEventSink must unblock. mu.Lock() zombieActive = false mu.Unlock() - svc.ResetFlowControl() + svc.SetEventSink(context.Background(), sink) // Phase 3: verify the flow gate is now open. - sess.flowMu.Lock() + svc.mu.Lock() stillPaused := sess.paused stillOutstanding := sess.outstanding - sess.flowMu.Unlock() + svc.mu.Unlock() if stillPaused { - t.Fatal("paused still true after ResetFlowControl — readLoop would deadlock") + t.Fatal("paused still true after SetEventSink — readLoop would deadlock") } if stillOutstanding != 0 { - t.Fatalf("outstanding = %d after ResetFlowControl, want 0", stillOutstanding) + t.Fatalf("outstanding = %d after SetEventSink, want 0", stillOutstanding) } // Phase 4: replay must complete without blocking (would time out if paused). @@ -611,7 +610,7 @@ sessionFound: t.Fatalf("replay error: %v", err) } case <-time.After(3 * time.Second): - t.Fatal("replay blocked — zombie deadlock not fixed (ResetFlowControl had no effect)") + t.Fatal("replay blocked — zombie deadlock not fixed (SetEventSink had no effect)") } } @@ -634,7 +633,7 @@ func TestReplayWigglesSIGWINCHAfterFlush(t *testing.T) { t.Parallel() rec := &sinkRecorder{} svc := New() - svc.SetEventSink(rec.sink) + svc.SetEventSink(context.Background(), rec.sink) t.Cleanup(svc.Close) tabID := "wiggle-sigwinch" diff --git a/internal/pty/service.go b/internal/pty/service.go index e6d893e3a..25af7dae4 100644 --- a/internal/pty/service.go +++ b/internal/pty/service.go @@ -22,13 +22,21 @@ import ( // Service owns the registry of active PTY-backed terminal sessions. type Service struct { mu sync.Mutex - sink EventSink + output *outputSink sessions map[tabKey]*session // closedTabs are the tabs a kill came for while they had no session, // and when: see Kill. closedTabs map[tabKey]time.Time } +// outputSink identifies a connection and captures its event destination. +// The pointer distinguishes successive sink installations, and the host's +// Done channel identifies the connection that dispatched a replay or ACK. +type outputSink struct { + ctx context.Context + emit EventSink +} + // closedTabMemory is how long a kill that found no session is kept for the // spawn it may have overtaken. const closedTabMemory = 10 * time.Second @@ -69,7 +77,8 @@ type session struct { writeMu sync.Mutex - flowMu sync.Mutex + // The credit window is guarded by service.mu so it changes atomically + // with the active output sink. flowCond *sync.Cond outstanding int paused bool @@ -140,7 +149,11 @@ const wiggleRestoreDelay = 200 * time.Millisecond // New constructs an empty PTY service registry. func New() *Service { - return &Service{sessions: make(map[tabKey]*session), closedTabs: make(map[tabKey]time.Time)} + return &Service{ + output: &outputSink{ctx: context.Background()}, + sessions: make(map[tabKey]*session), + closedTabs: make(map[tabKey]time.Time), + } } // Register binds every pty.* and session.* method onto the dispatcher. @@ -156,40 +169,17 @@ func Register(d *dispatch.Dispatcher, service *Service) { d.Register("session.list", service.SessionList) } -// SetEventSink wires the service to the stdio host after both are constructed. -func (s *Service) SetEventSink(sink EventSink) { +// SetEventSink binds output to the context the host passes to its handlers. +// Outstanding renderer debt belongs to the previous connection, so replacing +// the sink also clears that debt and wakes any paused replay or reader. +func (s *Service) SetEventSink(ctx context.Context, sink EventSink) { s.mu.Lock() defer s.mu.Unlock() - s.sink = sink -} - -// ResetFlowControl zeroes outstanding renderer debt and unblocks every paused -// readLoop across all live sessions. -// -// Call this immediately after wiring a new dialer's event sink. During the -// zombie window between a silent disconnect and the new dialer's takeover, the -// old dialer's OS socket buffer may have absorbed writes that the renderer -// never received — so noteEmitted debt accumulates without matching acks. If -// that debt crossed HighWatermarkBytes the readLoop is already blocked in -// waitForOutputWindow. The new renderer has no knowledge of the old debt and -// will never send acks for it, causing permanent deadlock ("reconnected but -// terminal frozen"). -// -// Resetting here is correct because the stale debt belongs to the old -// renderer generation. In-flight bytes that landed only in the OS buffer (not -// in the renderer) are already lost — the plan explicitly accepts this as -// in-flight loss. Carrying forward a fictitious debt would only harm the new -// renderer. -func (s *Service) ResetFlowControl() { - s.mu.Lock() - sessions := make([]*session, 0, len(s.sessions)) + s.output = &outputSink{ctx: ctx, emit: sink} for _, sess := range s.sessions { - sessions = append(sessions, sess) - } - s.mu.Unlock() - - for _, sess := range sessions { - sess.resetFlow() + sess.outstanding = 0 + sess.paused = false + sess.flowCond.Broadcast() } } @@ -320,7 +310,7 @@ func (s *Service) Resize(_ context.Context, raw json.RawMessage) (any, error) { } // Ack reduces one session's renderer debt and resumes output once the low watermark is reached. -func (s *Service) Ack(_ context.Context, raw json.RawMessage) (any, error) { +func (s *Service) Ack(ctx context.Context, raw json.RawMessage) (any, error) { var p AckParams if err := decodeParams(raw, &p, "pty.ack params must include workspaceId, tabId, and bytesConsumed"); err != nil { return nil, err @@ -333,11 +323,11 @@ func (s *Service) Ack(_ context.Context, raw json.RawMessage) (any, error) { if bytesConsumed < 0 { return nil, protocolError("pty.ack bytesConsumed must be non-negative") } - session := s.lookup(key) - if session == nil { - return struct{}{}, nil + s.mu.Lock() + defer s.mu.Unlock() + if sess := s.sessions[key]; sess != nil && ctx.Done() == s.output.ctx.Done() && ctx.Err() == nil { + sess.ackLocked(bytesConsumed) } - session.ack(bytesConsumed) return struct{}{}, nil } @@ -468,7 +458,7 @@ func newSession(service *Service, key tabKey, child *child, master *terminal) *s ring: make([]byte, RingCapBytes), createdAt: time.Now(), } - s.flowCond = sync.NewCond(&s.flowMu) + s.flowCond = sync.NewCond(&service.mu) return s } @@ -478,7 +468,7 @@ func (s *session) readLoop() { defer close(s.readDone) buf := make([]byte, MaxChunkSize) for { - if !s.waitForOutputWindow() { + if err := s.waitForOutputWindow(context.Background(), nil); err != nil { return } n, err := s.master.Read(buf) @@ -499,13 +489,7 @@ func (s *session) deliver(chunk []byte) { s.outputMu.Lock() defer s.outputMu.Unlock() s.ringAppend(chunk) - s.noteEmitted(len(chunk)) - if err := s.service.emit(EventData, DataPayload{WorkspaceID: s.key.workspaceID, TabID: s.key.tabID, Chunk: base64.StdEncoding.EncodeToString(chunk)}); err != nil { - // Undo the renderer debt — there is no renderer to send acks, so leaving - // the debt would permanently pause readLoop on the next - // waitForOutputWindow check once a dialer reconnects. - s.ack(len(chunk)) - } + _ = s.emitData(chunk, nil) } // resize applies a PTY geometry and records it for wiggleSIGWINCH. @@ -536,30 +520,31 @@ func (s *session) waitLoop() { }) } -// waitForOutputWindow blocks while a prior emission has crossed the high watermark. -func (s *session) waitForOutputWindow() bool { - s.flowMu.Lock() - defer s.flowMu.Unlock() - for s.paused && !s.stopped { +// waitForOutputWindow waits for credit or the end of the session or replay. +// A nil replay lets the live reader use the current connection's window. +func (s *session) waitForOutputWindow(ctx context.Context, replay *outputSink) error { + s.service.mu.Lock() + defer s.service.mu.Unlock() + for { + if err := ctx.Err(); err != nil { + return err + } + if replay != nil && replay != s.service.output { + return context.Canceled + } + if s.stopped { + return errors.New("session stopped") + } + if !s.paused { + return nil + } s.flowCond.Wait() } - return !s.stopped -} - -// noteEmitted adds raw bytes to renderer debt and toggles the paused state at HIGH. -func (s *session) noteEmitted(rawBytes int) { - s.flowMu.Lock() - defer s.flowMu.Unlock() - s.outstanding += rawBytes - if s.outstanding >= HighWatermarkBytes { - s.paused = true - } } -// ack applies renderer credit and wakes the reader only after LOW is reached. -func (s *session) ack(rawBytes int) { - s.flowMu.Lock() - defer s.flowMu.Unlock() +// ackLocked applies renderer credit and wakes waiters when LOW is reached. +// The caller holds service.mu and has checked the sink generation. +func (s *session) ackLocked(rawBytes int) { if rawBytes >= s.outstanding { s.outstanding = 0 } else { @@ -571,19 +556,6 @@ func (s *session) ack(rawBytes int) { } } -// resetFlow clears outstanding renderer debt and wakes any paused readLoop. -// Called by Service.ResetFlowControl on dialer generation change — the old -// renderer's debt must not carry over to the new one. -func (s *session) resetFlow() { - s.flowMu.Lock() - defer s.flowMu.Unlock() - s.outstanding = 0 - if s.paused { - s.paused = false - s.flowCond.Broadcast() - } -} - // wiggleSIGWINCH forces a full TUI repaint after replay by shrinking the PTY // by one row, holding that geometry for wiggleRestoreDelay, then restoring // the original size. The hold is what makes the shrink SIGWINCH observable @@ -691,11 +663,11 @@ func (s *session) discard() { // stopReading wakes any paused reader and closes the PTY master. func (s *session) stopReading() { - s.flowMu.Lock() + s.service.mu.Lock() s.stopped = true s.paused = false s.flowCond.Broadcast() - s.flowMu.Unlock() + s.service.mu.Unlock() _ = s.master.Close() } @@ -972,7 +944,7 @@ func (s *Service) SessionList(_ context.Context, raw json.RawMessage) (any, erro // Ordering guarantee: Replay holds outputMu for the whole send, so live PTY // output read meanwhile waits in readLoop and follows the replayed output on // the wire with no interleaving. -func (s *Service) Replay(_ context.Context, raw json.RawMessage) (any, error) { +func (s *Service) Replay(ctx context.Context, raw json.RawMessage) (any, error) { var p ReplayParams if err := decodeParams(raw, &p, "pty.replay params must include workspaceId and tabId"); err != nil { return nil, err @@ -981,16 +953,21 @@ func (s *Service) Replay(_ context.Context, raw json.RawMessage) (any, error) { if err != nil { return nil, err } - sess := s.lookup(key) + s.mu.Lock() + sess, output := s.sessions[key], s.output + s.mu.Unlock() if sess == nil { return struct{}{}, nil } + if ctx.Done() != output.ctx.Done() { + return nil, context.Canceled + } sess.outputMu.Lock() sess.ringMu.Lock() replay := append([]byte(terminalReset), sess.ringContentsLocked()...) sess.ringMu.Unlock() - err = s.emitReplay(sess, replay) + err = sess.emitReplay(ctx, output, replay) sess.outputMu.Unlock() if err != nil { // Dialer disappeared again mid-replay; the ring still holds everything @@ -1011,38 +988,72 @@ func (s *Service) Replay(_ context.Context, raw json.RawMessage) (any, error) { return struct{}{}, nil } -// emitReplay sends replayed bytes in MaxChunkSize chunks through the -// ack-credit gate, exactly as readLoop does for live output. Stops and -// returns the first emit error. -func (s *Service) emitReplay(sess *session, data []byte) error { +// emitReplay sends chunks through the credit window until it has flushed the +// retained output, is canceled, or encounters a sink error. +func (s *session) emitReplay(ctx context.Context, output *outputSink, data []byte) error { + stopWake := context.AfterFunc(ctx, func() { + // Take the waiter's lock so cancellation cannot signal before Wait. + s.service.mu.Lock() + defer s.service.mu.Unlock() + s.flowCond.Broadcast() + }) + defer stopWake() + for len(data) > 0 { - if !sess.waitForOutputWindow() { - return errors.New("session stopped") - } - n := len(data) - if n > MaxChunkSize { - n = MaxChunkSize + if err := s.waitForOutputWindow(ctx, output); err != nil { + return err } - chunk := data[:n] - data = data[n:] - sess.noteEmitted(len(chunk)) - if err := s.emit(EventData, DataPayload{ - WorkspaceID: sess.key.workspaceID, - TabID: sess.key.tabID, - Chunk: base64.StdEncoding.EncodeToString(chunk), - Replay: true, - }); err != nil { - sess.ack(len(chunk)) // undo debt on failure + n := min(len(data), MaxChunkSize) + if err := s.emitData(data[:n], output); err != nil { return err } + data = data[n:] } return nil } +// emitData charges the selected connection before writing to its captured +// sink. A nil replay uses the active sink for live output. The write can +// block, so it runs outside service.mu and rolls back debt only for its own +// generation. +func (s *session) emitData(chunk []byte, replay *outputSink) error { + svc := s.service + svc.mu.Lock() + output := svc.output + if replay != nil && replay != output { + svc.mu.Unlock() + return context.Canceled + } + if err := output.ctx.Err(); err != nil || output.emit == nil { + svc.mu.Unlock() + return err + } + s.outstanding += len(chunk) + if s.outstanding >= HighWatermarkBytes { + s.paused = true + } + svc.mu.Unlock() + + err := output.emit(EventData, DataPayload{ + WorkspaceID: s.key.workspaceID, + TabID: s.key.tabID, + Chunk: base64.StdEncoding.EncodeToString(chunk), + Replay: replay != nil, + }) + if err != nil { + svc.mu.Lock() + if svc.output == output { + s.ackLocked(len(chunk)) + } + svc.mu.Unlock() + } + return err +} + // emit writes one event through the configured sink, if any. func (s *Service) emit(event string, payload any) error { s.mu.Lock() - sink := s.sink + sink := s.output.emit s.mu.Unlock() if sink == nil { return nil diff --git a/internal/pty/service_test.go b/internal/pty/service_test.go index 369b3a328..4b46796b4 100644 --- a/internal/pty/service_test.go +++ b/internal/pty/service_test.go @@ -221,7 +221,7 @@ func newTestService(t *testing.T) (*Service, *eventRecorder) { t.Helper() recorder := &eventRecorder{} service := New() - service.SetEventSink(recorder.sink) + service.SetEventSink(context.Background(), recorder.sink) t.Cleanup(service.Close) return service, recorder } diff --git a/internal/pty/terminal_windows_test.go b/internal/pty/terminal_windows_test.go index a88807702..7f5db40b0 100644 --- a/internal/pty/terminal_windows_test.go +++ b/internal/pty/terminal_windows_test.go @@ -26,7 +26,7 @@ func newConsoleService(t *testing.T) (*Service, *consoleRecorder) { t.Helper() svc := New() rec := &consoleRecorder{} - svc.SetEventSink(func(event string, payload any) error { + svc.SetEventSink(context.Background(), func(event string, payload any) error { rec.mu.Lock() defer rec.mu.Unlock() switch p := payload.(type) { diff --git a/internal/stdioserver/host.go b/internal/stdioserver/host.go index 7f6929d58..6e530818a 100644 --- a/internal/stdioserver/host.go +++ b/internal/stdioserver/host.go @@ -144,6 +144,12 @@ func New(d *dispatch.Dispatcher, in io.Reader, out io.Writer, logger *slog.Logge } } +// Context returns the connection context passed to request handlers. The +// host cancels it once the drain finishes or reaches its deadline. +func (h *Host) Context() context.Context { + return h.ctx +} + // stampInbound records "now" (monotonic, relative to startMono) as the last // time an inbound line arrived. Single encoding point for lastInbound so the // watchdog's idleElapsed reads the same units. From 68601e991890ff0ccd080cb872cfd3fc9d2ad936 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:32:25 +0900 Subject: [PATCH 024/208] fix(workspace): refresh chat hooks after a local agent reconnects Co-Authored-By: Claude Opus 5.5 --- src/main/features/chat/host.ts | 103 ++++++---- src/main/features/workspace/manager.ts | 183 +++++++++++------ tests/unit/main/chat/host.test.ts | 4 +- .../manager-local-lifecycle-degraded.test.ts | 188 ++++++++++++++++-- 4 files changed, 354 insertions(+), 124 deletions(-) diff --git a/src/main/features/chat/host.ts b/src/main/features/chat/host.ts index 122689d98..3bd391bfe 100644 --- a/src/main/features/chat/host.ts +++ b/src/main/features/chat/host.ts @@ -35,7 +35,7 @@ export interface ChatWorkspaceManager { getAgentChannel(workspaceId: string): Promise; tryGetAgentChannel(workspaceId: string): Promise; onProviderReady(listener: (workspaceId: string) => void): () => void; - getHookInfo(workspaceId: string): HookInfo | null; + getChatHookInfo(workspaceId: string, channel: AgentChannel): Promise; getWrapperBinDir(workspaceId: string): string | null; getWrapperAgentBin(workspaceId: string): string | null; getWrapperShimDir(workspaceId: string): string | null; @@ -63,6 +63,7 @@ export type StartResult = interface Subscription { channel: AgentChannel; + revision: number; dispose: () => void; } @@ -83,6 +84,8 @@ export class ChatHost { .then(async (channel) => { if (!channel) return; await channel.ready; + await this.options.workspaceManager.getChatHookInfo(workspaceId, channel); + if (this.disposed) return; this.subscribe(workspaceId, channel); this.options.broadcast("resync", { workspaceId }); }) @@ -127,7 +130,6 @@ export class ChatHost { log.warn(`claude --version failed: ${(err as Error).message}`); } - const hookInfo = workspaceManager.getHookInfo(workspaceId); const wrapperBinDir = workspaceManager.getWrapperBinDir(workspaceId); const agentBin = workspaceManager.getWrapperAgentBin(workspaceId); let program = found.path; @@ -146,20 +148,21 @@ export class ChatHost { // the PATH has after it. program = hostJoin(wrapperBinDir, "claude", false); } - const env = claudeTabEnv({ - workspaceId, - tabId, - path: found.envPath, - wrapperBinDir, - agentBin, - agentSocket: hookInfo?.socketPath, - hookToken: hookInfo ? tabHookToken(hookInfo, workspaceId, tabId) : undefined, - withoutWrapper: windows, - ...(gitBash ? { gitBash } : {}), - }); - try { - Object.assign(env, await this.profileEnv(channel, "claude", profileId)); + const profile = await this.profileEnv(channel, "claude", profileId); + const hookInfo = await workspaceManager.getChatHookInfo(workspaceId, channel); + const env = claudeTabEnv({ + workspaceId, + tabId, + path: found.envPath, + wrapperBinDir, + agentBin, + agentSocket: hookInfo?.socketPath, + hookToken: hookInfo ? tabHookToken(hookInfo, workspaceId, tabId) : undefined, + withoutWrapper: windows, + ...(gitBash ? { gitBash } : {}), + }); + Object.assign(env, profile); const result = await channel.call<{ pid: number; attached?: boolean }>("chat.start", { workspaceId, tabId, @@ -211,23 +214,24 @@ export class ChatHost { log.warn(`codex --version failed: ${(err as Error).message}`); } const { workspaceManager } = this.options; - const hookInfo = workspaceManager.getHookInfo(workspaceId); // Windows commands run in PowerShell or cmd, which read no shim files. const windows = this.options.windowsAgentFiles !== undefined && workspaceManager.isLocal?.(workspaceId) === true; - const env = codexTabEnv({ - workspaceId, - tabId, - path: found.envPath, - wrapperBinDir: workspaceManager.getWrapperBinDir(workspaceId), - agentBin: workspaceManager.getWrapperAgentBin(workspaceId), - agentSocket: hookInfo?.socketPath, - hookToken: hookInfo ? tabHookToken(hookInfo, workspaceId, tabId) : undefined, - shimDir: windows ? null : workspaceManager.getWrapperShimDir(workspaceId), - }); try { - Object.assign(env, await this.profileEnv(channel, "codex", options.profileId)); + const profile = await this.profileEnv(channel, "codex", options.profileId); + const hookInfo = await workspaceManager.getChatHookInfo(workspaceId, channel); + const env = codexTabEnv({ + workspaceId, + tabId, + path: found.envPath, + wrapperBinDir: workspaceManager.getWrapperBinDir(workspaceId), + agentBin: workspaceManager.getWrapperAgentBin(workspaceId), + agentSocket: hookInfo?.socketPath, + hookToken: hookInfo ? tabHookToken(hookInfo, workspaceId, tabId) : undefined, + shimDir: windows ? null : workspaceManager.getWrapperShimDir(workspaceId), + }); + Object.assign(env, profile); const result = await channel.call<{ pid: number; attached?: boolean; canonicalCwd?: string }>( "chat.start", { @@ -488,28 +492,43 @@ export class ChatHost { }; const offLine = channel.on("chat.line", relay("line")); const offExit = channel.on("chat.exit", relay("exit")); - const offLifecycle = channel.onLifecycle((event) => this.handleLifecycle(workspaceId, event)); - this.subscriptions.set(workspaceId, { + const subscription: Subscription = { channel, + revision: 0, dispose: () => { offLine(); offExit(); offLifecycle(); }, - }); + }; + const offLifecycle = channel.onLifecycle((event) => + this.handleLifecycle(workspaceId, subscription, event), + ); + this.subscriptions.set(workspaceId, subscription); } /** - * A dropped connection holds the tabs; the same agent back (a daemon that - * survived) has them replay what they missed. A new agent comes through - * onProviderReady. + * A dropped connection holds the tabs. A replacement local process needs + * its hook endpoint before the tabs can resume. A surviving daemon can + * replay immediately. */ - private handleLifecycle(workspaceId: string, event: ChannelLifecycleEvent): void { + private handleLifecycle( + workspaceId: string, + subscription: Subscription, + event: ChannelLifecycleEvent, + ): void { switch (event.type) { case "reconnecting": + subscription.revision += 1; this.options.broadcast("held", { workspaceId }); return; case "ready": + if (this.options.workspaceManager.isLocal?.(workspaceId)) { + void this.resyncAfterHooks(workspaceId, subscription); + return; + } + this.options.broadcast("resync", { workspaceId }); + return; // A new daemon behind the same channel: the tabs find it has no logs. case "held-then-expired": this.options.broadcast("resync", { workspaceId }); @@ -524,4 +543,20 @@ export class ChatHost { return; } } + + /** Resyncs only if this ready event still belongs to the live connection. */ + private async resyncAfterHooks(workspaceId: string, subscription: Subscription): Promise { + const { revision, channel } = subscription; + try { + await this.options.workspaceManager.getChatHookInfo(workspaceId, channel); + if ( + this.subscriptions.get(workspaceId) === subscription && + revision === subscription.revision + ) { + this.options.broadcast("resync", { workspaceId }); + } + } catch (error) { + log.warn(`chat reconnect failed for ${workspaceId}: ${(error as Error).message}`); + } + } } diff --git a/src/main/features/workspace/manager.ts b/src/main/features/workspace/manager.ts index 527c5e937..064d7700a 100644 --- a/src/main/features/workspace/manager.ts +++ b/src/main/features/workspace/manager.ts @@ -187,6 +187,11 @@ export interface HookInfo { readonly tabTokens?: boolean; } +interface LocalHookRefresh { + promise: Promise; + resolve: () => void; +} + /** * Type guard for the hook.getInfo response. * A response is valid only when both socketPath and token are strings. @@ -373,6 +378,8 @@ export class WorkspaceManager { private readonly connectionStatuses = new Map(); // Cache of pull-based hookserver connection info — filled by the hook.getInfo RPC right after channel.ready. private readonly hookInfoByWorkspace = new Map(); + /** One wait per local reconnect, until the replacement's hooks are known. */ + private readonly localHookRefreshes = new WeakMap(); /** * Tracks workspaces with an in-flight automatic re-authentication attempt so * the manager never opens a second prompt for the same workspace concurrently. @@ -585,6 +592,40 @@ export class WorkspaceManager { return this.hookInfoByWorkspace.get(workspaceId) ?? null; } + /** Returns the hooks for the channel a chat is about to use. */ + async getChatHookInfo(workspaceId: string, channel: AgentChannel): Promise { + let refresh = this.localHookRefreshes.get(channel); + while (refresh) { + await refresh.promise; + refresh = this.localHookRefreshes.get(channel); + } + if ((this.localChannels.get(workspaceId) ?? this.sshChannels.get(workspaceId)) !== channel) { + throw new Error(`agent channel changed for workspace: ${workspaceId}`); + } + return this.getHookInfo(workspaceId); + } + + /** Reads the hook endpoint, allowing workspaces whose agent cannot host hooks. */ + private async readHookInfo(workspaceId: string, channel: AgentChannel): Promise { + try { + const raw = await channel.call("hook.getInfo", {}); + if (!isHookInfo(raw)) throw new Error("hook.getInfo returned no socketPath or token"); + return raw; + } catch (error) { + if (!isHookUnavailable(error)) throw error; + log.warn( + `hookserver unavailable for ${workspaceId}; hook integration disabled for this session.`, + ); + return null; + } + } + + /** Installs the current agent's endpoint or clears it when hooks are unavailable. */ + private cacheHookInfo(workspaceId: string, info: HookInfo | null): void { + if (info) this.hookInfoByWorkspace.set(workspaceId, info); + else this.hookInfoByWorkspace.delete(workspaceId); + } + /** * Returns the absolute path of the bin directory that holds the wrapper binaries, by workspace kind. * @@ -1366,34 +1407,21 @@ export class WorkspaceManager { throw error; } - // Right after channel.ready, pull hook.getInfo and cache the hookserver connection info. - // The agent waits at most 5s internally, so a response always arrives within the 30s default timeout. - // - // The server.unavailable code is a graceful-degrade signal that the agent failed to create the - // hookserver — boot continues with hookInfo left empty instead of killing the whole workspace. - // (Same as the push-era behavior: without a hookserver only the Claude hook feature is off and the workspace is fine.) try { - const raw = await channel.call("hook.getInfo", {}); - if (!isHookInfo(raw)) { - throw new Error("hook.getInfo returned no socketPath or token"); + const info = await this.readHookInfo(meta.id, channel); + if (this.localChannels.get(meta.id) === channel && !this.localHookRefreshes.has(channel)) { + this.cacheHookInfo(meta.id, info); } - this.hookInfoByWorkspace.set(meta.id, raw); } catch (err) { - if (isHookUnavailable(err)) { - log.warn( - `hookserver unavailable for ${meta.id}; Claude Code hook integration disabled for this session.`, - ); - this.hookInfoByWorkspace.delete(meta.id); - } else { - disposeLifecycleListener(); - if (this.localChannels.get(meta.id) === channel) { - this.localChannels.delete(meta.id); - } - channel.dispose(); - ctx.setFsProvider(createInitialFsProvider(meta)); - log.warn(`agent hook setup failed for ${meta.id}: ${(err as Error).message}`); - throw new Error(`Agent hook setup failed: ${(err as Error).message}`, { cause: err }); + disposeLifecycleListener(); + if (this.localChannels.get(meta.id) === channel) { + this.localChannels.delete(meta.id); } + this.finishLocalHookRefresh(channel); + channel.dispose(); + ctx.setFsProvider(createInitialFsProvider(meta)); + log.warn(`agent hook setup failed for ${meta.id}: ${(err as Error).message}`); + throw new Error(`Agent hook setup failed: ${(err as Error).message}`, { cause: err }); } // Write the PTY shim files into the workspace-specific directory. @@ -1418,6 +1446,7 @@ export class WorkspaceManager { const provider = new AgentFsProvider("local", channel, { disposeChannel: true }); ctx.setFsProvider(provider, () => { disposeLifecycleListener(); + this.finishLocalHookRefresh(channel); provider.dispose(); if (this.localChannels.get(meta.id) === channel) { this.localChannels.delete(meta.id); @@ -1582,37 +1611,21 @@ export class WorkspaceManager { throw error; } - // Right after channel.ready, pull hook.getInfo and cache the hookserver connection info. - // Latency may be higher over SSH, but the 30s default timeout is enough. - // - // The server.unavailable code is a graceful-degrade signal that the agent failed to create the - // hookserver. On an SSH remote the socket path is more likely than locally to hit the length - // limit (104 chars on macOS), so graceful handling matters especially. try { - const raw = await channel.call("hook.getInfo", {}); - if (!isHookInfo(raw)) { - throw new Error("hook.getInfo returned no socketPath or token"); - } - this.hookInfoByWorkspace.set(meta.id, raw); + const info = await this.readHookInfo(meta.id, channel); + if (this.sshChannels.get(meta.id) === channel) this.cacheHookInfo(meta.id, info); } catch (err) { - if (isHookUnavailable(err)) { - log.warn( - `hookserver unavailable for ${meta.id}; Claude Code hook integration disabled for this session.`, - ); - this.hookInfoByWorkspace.delete(meta.id); - } else { - disposeLifecycleListener(); - this.broadcastConnectionStatus(meta.id, "error"); - if (this.sshChannels.get(meta.id) === channel) { - this.sshChannels.delete(meta.id); - } - this.sshBootstraps.delete(meta.id); - bootstrap.dispose?.(); - channel.dispose(); - ctx.setFsProvider(createInitialFsProvider(ctx.getMeta())); - log.warn(`agent hook setup failed for ${meta.id}: ${(err as Error).message}`); - throw new Error(`Agent hook setup failed: ${(err as Error).message}`, { cause: err }); + disposeLifecycleListener(); + this.broadcastConnectionStatus(meta.id, "error"); + if (this.sshChannels.get(meta.id) === channel) { + this.sshChannels.delete(meta.id); } + this.sshBootstraps.delete(meta.id); + bootstrap.dispose?.(); + channel.dispose(); + ctx.setFsProvider(createInitialFsProvider(ctx.getMeta())); + log.warn(`agent hook setup failed for ${meta.id}: ${(err as Error).message}`); + throw new Error(`Agent hook setup failed: ${(err as Error).message}`, { cause: err }); } // Write the PTY shim files into the workspace-specific directory. @@ -1952,30 +1965,40 @@ export class WorkspaceManager { if (!ctx) { this.localChannels.delete(workspaceId); this.localProviderReady.delete(workspaceId); + this.finishLocalHookRefresh(channel); + return; + } + + if (event.type === "reconnecting") { + const previous = this.localHookRefreshes.get(channel); + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + this.localHookRefreshes.set(channel, { promise, resolve }); + this.hookInfoByWorkspace.delete(workspaceId); + previous?.resolve(); + return; + } + if (event.type === "ready") { + const refresh = this.localHookRefreshes.get(channel); + if (refresh) void this.refreshLocalHooks(workspaceId, channel, refresh); + return; + } + if (event.type === "disposed") { + this.finishLocalHookRefresh(channel); return; } // Teardown is reserved for genuine terminal events (`exit`, `failure`). - // Everything else must keep the provider wired: - // - `reconnecting` is transient — the internal reconnect path recovers - // transparently. - // - `degraded` / `degraded-recovered` are heartbeat-quality signals - // (one late heartbeat fires `degraded`) and `ready` is a successful - // recovery — the channel is alive in all three cases. Before v0.6.1 - // these fell into the teardown branch below, which abandoned a live - // agent WITHOUT disposing it (orphan process keeping every fs/git - // watch) and lazily booted a fresh watch-less agent: push events - // (fs.changed / git.changed) went silent while RPC kept working, and - // existing PTY sessions were stranded on the abandoned channel. - // - `held-then-expired` cannot occur on local channels (no epoch). - // - `disposed` is an intentional teardown whose cleanup already ran via - // the setFsProvider dispose callback. + // Heartbeat quality signals leave the provider and its watches wired. if (event.type !== "exit" && event.type !== "failure") { return; } this.localChannels.delete(workspaceId); this.localProviderReady.delete(workspaceId); + this.finishLocalHookRefresh(channel); // Stale hookInfo is invalid once the channel dies — the next boot fills it again. // Keeping it could let a spawn right after reconnect put a dead socket path in the env. this.hookInfoByWorkspace.delete(workspaceId); @@ -1985,6 +2008,34 @@ export class WorkspaceManager { log.warn(`shim dir removal failed for ${workspaceId}: ${(err as Error).message}`); }); } + + /** Refreshes the endpoint for the process that just completed its handshake. */ + private async refreshLocalHooks( + workspaceId: string, + channel: AgentChannel, + refresh: LocalHookRefresh, + ): Promise { + try { + const info = await this.readHookInfo(workspaceId, channel); + if (this.localHookRefreshes.get(channel) !== refresh) return; + this.cacheHookInfo(workspaceId, info); + this.finishLocalHookRefresh(channel); + } catch (error) { + if (this.localHookRefreshes.get(channel) !== refresh) return; + log.warn(`agent hook setup failed for ${workspaceId}: ${(error as Error).message}`); + this.handleLocalChannelLifecycle(workspaceId, channel, { + type: "failure", + error: error instanceof Error ? error : new Error(String(error)), + }); + } + } + + /** Releases chat callers so they can check whether their channel is still current. */ + private finishLocalHookRefresh(channel: AgentChannel): void { + const refresh = this.localHookRefreshes.get(channel); + this.localHookRefreshes.delete(channel); + refresh?.resolve(); + } } /** diff --git a/tests/unit/main/chat/host.test.ts b/tests/unit/main/chat/host.test.ts index b40df44f7..da0054bb1 100644 --- a/tests/unit/main/chat/host.test.ts +++ b/tests/unit/main/chat/host.test.ts @@ -82,7 +82,7 @@ function setup( providerReady = listener; return () => {}; }, - getHookInfo: () => ({ socketPath: "/tmp/h.sock", token: "tok" }), + getChatHookInfo: async () => ({ socketPath: "/tmp/h.sock", token: "tok" }), getWrapperBinDir: () => "/home/u/.nexus-code/bin", getWrapperAgentBin: () => "/home/u/.nexus-code/bin/agent", getWrapperShimDir: () => "/home/u/.nexus-code/shim/ws", @@ -336,7 +336,7 @@ describe("ChatHost", () => { getAgentChannel: async () => channel, tryGetAgentChannel: async () => channel, onProviderReady: () => () => {}, - getHookInfo: () => null, + getChatHookInfo: async () => null, getWrapperBinDir: () => "C:\\Users\\u\\.nexus-code\\cli", getWrapperAgentBin: () => null, getWrapperShimDir: () => "C:\\Users\\u\\.nexus-code\\shim\\ws", diff --git a/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts b/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts index 17f12b83d..dfedcd0b1 100644 --- a/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts +++ b/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts @@ -32,6 +32,7 @@ const { GlobalStorage } = await import("../../../../src/main/infra/storage/globa const { WorkspaceStorage } = await import("../../../../src/main/infra/storage/workspace-storage"); const { StateService } = await import("../../../../src/main/infra/storage/state-service"); const { WorkspaceManager } = await import("../../../../src/main/features/workspace/manager"); +const { ChatHost } = await import("../../../../src/main/features/chat/host"); type ChannelLifecycleCallback = (event: { type: string }) => void; @@ -40,6 +41,8 @@ class StubChannel { private resolveReady!: () => void; private lifecycleListeners: Set = new Set(); disposed = false; + hookInfo = mock(async (): Promise => ({ socketPath: "/tmp/hook.sock", token: "tok" })); + readonly spawns: Array<{ env: Record }> = []; constructor() { this.ready = new Promise((res) => { @@ -47,9 +50,13 @@ class StubChannel { }); } - async call(method: string, _params?: unknown): Promise { - if (method === "hook.getInfo") { - return { socketPath: "/tmp/hook.sock", token: "tok" }; + async call(method: string, params?: unknown): Promise { + if (method === "hook.getInfo") return this.hookInfo(); + if (method === "lsp.findBinary") return { path: "/stub/model" }; + if (method === "chat.exec") return { code: 0, stdout: "2.1.400" }; + if (method === "chat.start") { + this.spawns.push(params as (typeof this.spawns)[number]); + return { pid: 1 }; } return {}; } @@ -66,7 +73,7 @@ class StubChannel { } emitLifecycle(event: { type: string }): void { - for (const cb of this.lifecycleListeners) cb(event); + for (const cb of [...this.lifecycleListeners]) cb(event); } resolveChannel(): void { @@ -98,34 +105,38 @@ function makeHarness() { ); const broadcast = mock((_ch: string, _ev: string, _args: unknown) => {}); + const channels: StubChannel[] = []; + const createChannel = () => { + const channel = new StubChannel(); + channels.push(channel); + if (channels.length > 1) { + channel.hookInfo.mockResolvedValue({ socketPath: "/tmp/new-provider.sock", token: "new" }); + } + channel.resolveChannel(); + return channel; + }; + const bootstrap = async () => ({ + remoteCommand: "/stub/agent --dial sock", + remoteHome: "/stub", + remoteBinDir: "/stub/bin", + platform: { os: "linux", arch: "amd64" } as const, + uploaded: false, + }); const manager = new WorkspaceManager( globalStorage, workspaceStorage, stateService, broadcast, - undefined as never, // sshChannelFactory - undefined as never, // sshBootstrap - undefined as never, // localChannelFactory — overridden below - undefined as never, // localAgentCommandResolver — overridden below + createChannel as never, // sshChannelFactory + bootstrap, + createChannel as never, // localChannelFactory + () => ({ bin: "/stub/agent", args: [] }), undefined as never, // sshLspBootstrap writeShimFilesMock, removeShimDirMock, + { bootstrap, createChannel } as never, ); - const channels: StubChannel[] = []; - const m = manager as unknown as { - localChannelFactory: unknown; - localAgentCommandResolver: unknown; - }; - m.localAgentCommandResolver = () => ({ bin: "/usr/bin/agent", args: [] }); - m.localChannelFactory = (_opts: unknown) => { - const channel = new StubChannel(); - channels.push(channel); - // Resolve immediately so awaited boots settle without manual pumping. - channel.resolveChannel(); - return channel; - }; - return { manager, globalDb, channels, removeShimDirMock }; } @@ -140,6 +151,139 @@ async function bootLocalWorkspace(harness: ReturnType) { const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); +for (const available of [true, false]) { + test(`local reconnect waits for refreshed hooks before resync and spawn (${available ? "available" : "unavailable"})`, async () => { + const harness = makeHarness(); + const { manager, channels, globalDb } = harness; + const resynced = Promise.withResolvers(); + const events: string[] = []; + const host = new ChatHost({ + workspaceManager: manager, + broadcast: (event) => { + events.push(event); + if (event === "resync") resynced.resolve(); + }, + }); + try { + const { id } = await bootLocalWorkspace(harness); + await host.startCodex(id, "before", "/project", {}); + const [channel] = channels; + const answer = Promise.withResolvers(); + channel.hookInfo.mockImplementation(() => answer.promise); + channel.emitLifecycle({ type: "reconnecting" }); + channel.emitLifecycle({ type: "ready" }); + expect(events).toEqual(["held"]); + expect(channel.hookInfo).toHaveBeenCalledTimes(2); + const starting = Promise.all([ + host.startCodex(id, "codex", "/project", {}), + host.start(id, "claude", "/project", {}), + ]); + // Let both starts reach the pending hook lookup. + await new Promise((resolve) => setImmediate(resolve)); + expect(channel.spawns).toHaveLength(1); + expect(manager.getHookInfo(id)).toBeNull(); + expect(events).toEqual(["held"]); + const socketPath = "/tmp/replacement.sock"; + if (available) answer.resolve({ socketPath, token: "replacement-token" }); + else answer.reject(Object.assign(new Error("unavailable"), { code: "server.unavailable" })); + const [results] = await Promise.all([starting, resynced.promise]); + expect(results.map((result) => result.ok)).toEqual([true, true]); + expect(channels).toHaveLength(1); + expect(channel.spawns).toHaveLength(3); + for (const { env } of channel.spawns.slice(1)) { + expect(env.NEXUS_AGENT_SOCKET).toBe(available ? socketPath : undefined); + expect(env.NEXUS_HOOK_TOKEN).toBe(available ? "replacement-token" : undefined); + } + expect(events).toEqual(["held", "resync"]); + } finally { + host.dispose(); + globalDb.close(); + } + }); +} + +test("a superseded local hook reply cannot release chat resync", async () => { + const harness = makeHarness(); + const { manager, channels, globalDb } = harness; + const resynced = Promise.withResolvers(); + const events: string[] = []; + const host = new ChatHost({ + workspaceManager: manager, + broadcast: (event) => { + events.push(event); + if (event === "resync") resynced.resolve(); + }, + }); + try { + const { id } = await bootLocalWorkspace(harness); + await host.startCodex(id, "tab", "/project", {}); + const [channel] = channels; + const first = Promise.withResolvers(); + const second = Promise.withResolvers(); + channel.hookInfo.mockImplementationOnce(() => first.promise); + channel.hookInfo.mockImplementationOnce(() => second.promise); + channel.emitLifecycle({ type: "reconnecting" }); + channel.emitLifecycle({ type: "ready" }); + channel.emitLifecycle({ type: "reconnecting" }); + channel.emitLifecycle({ type: "ready" }); + first.resolve({ socketPath: "/tmp/stale.sock", token: "stale" }); + await new Promise((resolve) => setImmediate(resolve)); + expect(events).toEqual(["held", "held"]); + expect(manager.getHookInfo(id)).toBeNull(); + + const current = { socketPath: "/tmp/current.sock", token: "current" }; + second.resolve(current); + await resynced.promise; + expect(events).toEqual(["held", "held", "resync"]); + expect(manager.getHookInfo(id)).toEqual(current); + } finally { + host.dispose(); + globalDb.close(); + } +}); + +for (const kind of ["ssh", "wsl"] as const) { + test(`${kind} reattach keeps hooks and daemon replacement loads them on a new provider`, async () => { + const { manager, channels, globalDb } = makeHarness(); + const location = + kind === "ssh" + ? { + kind, + host: "example.test", + user: "test", + remotePath: "/project", + authMode: "key-only" as const, + } + : { kind, distro: "Test", remotePath: "/project" }; + const context = manager.create({ location }); + const host = new ChatHost({ workspaceManager: manager, broadcast: () => {} }); + try { + await host.startCodex(context.id, "before", "/project", {}); + const [first] = channels; + first.emitLifecycle({ type: "reconnecting" }); + first.emitLifecycle({ type: "ready" }); + expect(first.hookInfo).toHaveBeenCalledTimes(1); + expect(manager.getHookInfo(context.id)?.socketPath).toBe("/tmp/hook.sock"); + + first.emitLifecycle({ type: "reconnecting" }); + first.emitLifecycle({ type: "held-then-expired" }); + expect(manager.getHookInfo(context.id)).toBeNull(); + await host.startCodex(context.id, "after", "/project", {}); + expect(first.disposed).toBe(true); + expect(first.hookInfo).toHaveBeenCalledTimes(1); + expect(channels).toHaveLength(2); + expect(channels[1].hookInfo).toHaveBeenCalledTimes(1); + expect(channels[1].spawns[0]?.env).toMatchObject({ + NEXUS_AGENT_SOCKET: "/tmp/new-provider.sock", + NEXUS_HOOK_TOKEN: "new", + }); + } finally { + host.dispose(); + globalDb.close(); + } + }); +} + describe("handleLocalChannelLifecycle: health signals must not tear down the provider", () => { for (const type of ["degraded", "degraded-recovered", "ready"] as const) { test(`'${type}' keeps the provider and does not boot a second channel`, async () => { From 561ab64bd6a95008ba1b138755f05957708961ac Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:36:44 +0900 Subject: [PATCH 025/208] fix(layout): restore external editor tab origins Co-Authored-By: Claude Opus 5.5 --- src/main/features/app-state/index.ts | 8 +- src/main/features/app-state/layout-origins.ts | 53 +++ src/main/index.ts | 1 + src/renderer/bootstrap.ts | 41 +- src/renderer/state/persistence.ts | 42 +- src/renderer/utils/path.ts | 37 +- src/shared/fs/workspace-path.ts | 34 ++ src/shared/types/layout.ts | 1 + .../state/stores/tabs/new-tab-types.test.ts | 388 +++++++++--------- 9 files changed, 334 insertions(+), 271 deletions(-) create mode 100644 src/main/features/app-state/layout-origins.ts create mode 100644 src/shared/fs/workspace-path.ts diff --git a/src/main/features/app-state/index.ts b/src/main/features/app-state/index.ts index 1814334bd..437bce126 100644 --- a/src/main/features/app-state/index.ts +++ b/src/main/features/app-state/index.ts @@ -1,11 +1,16 @@ import { ipcContract } from "../../../shared/ipc/contract"; import type { AppState } from "../../../shared/types/app-state"; +import type { WorkspaceMeta } from "../../../shared/types/workspace"; import { register, validateArgs } from "../../infra/ipc-router"; import type { StateService } from "../../infra/storage/state-service"; +import { restoreLayoutOrigins } from "./layout-origins"; + const c = ipcContract.appState.call; export interface AppStateChannelOptions { + /** Current workspace metadata for restoring legacy layout records. */ + listWorkspaces?: () => WorkspaceMeta[]; /** * Invoked synchronously after a `set` call that includes a `language` * field, with the newly requested language value. @@ -62,7 +67,8 @@ export function registerAppStateChannel( register("appState", { call: { get: (_args: unknown) => { - return stateService.getState(); + const state = stateService.getState(); + return opts.listWorkspaces ? restoreLayoutOrigins(state, opts.listWorkspaces()) : state; }, set: (args: unknown) => { const patch = validateArgs(c.set.args, args); diff --git a/src/main/features/app-state/layout-origins.ts b/src/main/features/app-state/layout-origins.ts new file mode 100644 index 000000000..4bc24e280 --- /dev/null +++ b/src/main/features/app-state/layout-origins.ts @@ -0,0 +1,53 @@ +import { toSlashPath } from "../../../shared/fs/drive-path"; +import { isWithinWorkspace } from "../../../shared/fs/workspace-path"; +import type { AppState } from "../../../shared/types/app-state"; +import type { SerializedTab } from "../../../shared/types/layout"; +import type { WorkspaceMeta } from "../../../shared/types/workspace"; + +/** Recognize absolute paths in the formats Open File stores. */ +function pathStyle(path: string): "posix" | "drive" | null { + if (path.split("/").some((part) => part === "." || part === "..")) return null; + if (/^[A-Z]:\//.test(path)) return "drive"; + return path.startsWith("/") && !path.startsWith("//") ? "posix" : null; +} + +/** + * Restore a legacy file tab using Open File's containment check. A remote + * or ambiguous path cannot establish that the file is safe to route to the + * local external loader. Omit it so the user can reopen it explicitly. + */ +function restoreTabOrigin(tab: SerializedTab, workspace: WorkspaceMeta): SerializedTab | null { + if (tab.type !== "editor" || tab.props.origin !== undefined) return tab; + const filePath = toSlashPath(tab.props.filePath); + const root = toSlashPath(workspace.rootPath); + const style = pathStyle(filePath); + if (tab.props.workspaceId !== workspace.id || !style || style !== pathStyle(root)) return null; + if (isWithinWorkspace(filePath, root)) return tab; + if ( + workspace.location.kind !== "local" || + isWithinWorkspace(filePath.toLowerCase(), root.toLowerCase()) + ) { + return null; + } + return { ...tab, props: { ...tab.props, filePath, origin: "external" } }; +} + +/** Upgrade origin-less records on read, once workspace metadata is available. */ +export function restoreLayoutOrigins( + state: Readonly, + workspaces: WorkspaceMeta[], +): Readonly { + if (!state.layoutByWorkspace) return state; + const byId = new Map(workspaces.map((workspace) => [workspace.id, workspace])); + return { + ...state, + layoutByWorkspace: Object.fromEntries( + Object.entries(state.layoutByWorkspace).map(([id, snapshot]) => { + const workspace = byId.get(id); + if (!workspace) return [id, snapshot]; + const tabs = snapshot.tabs.flatMap((tab) => restoreTabOrigin(tab, workspace) ?? []); + return [id, { ...snapshot, tabs }]; + }), + ), + }; +} diff --git a/src/main/index.ts b/src/main/index.ts index a31cafff8..5a67a0334 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -305,6 +305,7 @@ registerWorkspaceChannel(workspaceManager, { }); registerDialogChannel(); registerAppStateChannel(stateService, { + listWorkspaces: () => workspaceManager.list(), /** * Called synchronously inside the appState.set IPC handler whenever the * renderer persists a new language preference. By the time any renderer diff --git a/src/renderer/bootstrap.ts b/src/renderer/bootstrap.ts index cd29b857d..f19309a98 100644 --- a/src/renderer/bootstrap.ts +++ b/src/renderer/bootstrap.ts @@ -28,9 +28,8 @@ import { initLspSettingsSync } from "./state/operations/lsp-settings"; import { initLspStatusSync } from "./state/operations/lsp-status"; import { initPortsSync } from "./state/operations/ports"; import { hydrateReleaseNotesSeen } from "./state/operations/release-notes"; -import { normalizeWorkspaceTabOrder } from "./state/operations/tab-order"; import { initUpdatesSubscriptions } from "./state/operations/updates"; -import { registerStatePersistence } from "./state/persistence"; +import { hydrateLayoutSnapshots, registerStatePersistence } from "./state/persistence"; import { useAgentCliStore } from "./state/stores/agent-cli"; import { useAgentListViewStore } from "./state/stores/agent-list-view"; import { loadProfilesHome, useAgentProfilesStore } from "./state/stores/agent-profiles"; @@ -44,11 +43,9 @@ import { useIconThemeStore } from "./state/stores/icon-theme"; import { useInactivePanelDimStore } from "./state/stores/inactive-panel-dim"; import { useKeybindingsStore } from "./state/stores/keybindings"; import { useLanguageStore } from "./state/stores/language"; -import { useLayoutStore } from "./state/stores/layout"; import { useLspSettingsStore } from "./state/stores/lsp-settings"; import { useNotificationsStore } from "./state/stores/notifications"; import { usePreviewDefaultsStore } from "./state/stores/preview-defaults"; -import { restoredTitles, useTabsStore } from "./state/stores/tabs"; import { useTerminalStore } from "./state/stores/terminal"; import { useThemeStore } from "./state/stores/theme"; import { useUIStore } from "./state/stores/ui"; @@ -283,41 +280,7 @@ export async function bootstrapAppState(): Promise { // reflects persisted state on first render. useBrowserPermissionsStore.getState().hydrate(state.browserPermissionGrants); - if (state.layoutByWorkspace) { - for (const [wsId, snap] of Object.entries(state.layoutByWorkspace)) { - try { - const tabsMap: Record< - string, - (typeof snap.tabs)[number] & { - isPreview: boolean; - isPinned: boolean; - defaultTitle: string; - } - > = {}; - for (const t of snap.tabs) { - const isPreview = - "isPreview" in t && typeof t.isPreview === "boolean" ? t.isPreview : false; - const isPinned = "isPinned" in t && typeof t.isPinned === "boolean" ? t.isPinned : false; - // Its titles as saved: a rename stays the user's, and a name the - // app gives follows its language (restoredTitles). - tabsMap[t.id] = { ...t, isPreview, isPinned, ...restoredTitles(t) }; - } - useTabsStore.setState((s) => ({ - byWorkspace: { ...s.byWorkspace, [wsId]: tabsMap }, - })); - - const knownTabIds = new Set(snap.tabs.map((t) => t.id)); - useLayoutStore - .getState() - .hydrate(wsId, { root: snap.root, activeGroupId: snap.activeGroupId }, knownTabIds); - // Layouts saved before pinning reordered tabs can hold pinned tabs - // behind unpinned ones. - normalizeWorkspaceTabOrder(wsId); - } catch { - // Silent repair: skip invalid snapshot for this workspace - } - } - } + hydrateLayoutSnapshots(state.layoutByWorkspace); // The agent view's panels hold tabs, so they come back after the tabs, // keeping those that still exist, and let go of each tab as it closes. diff --git a/src/renderer/state/persistence.ts b/src/renderer/state/persistence.ts index 94f753d34..82381364e 100644 --- a/src/renderer/state/persistence.ts +++ b/src/renderer/state/persistence.ts @@ -14,8 +14,9 @@ import { createLogger } from "../../shared/log/renderer"; import type { AppState } from "../../shared/types/app-state"; import { STATE_PERSIST_DEBOUNCE_MS } from "../../shared/util/timing-constants"; import { ipcCallResult } from "../ipc/client"; +import { normalizeWorkspaceTabOrder } from "./operations/tab-order"; import { useLayoutStore } from "./stores/layout"; -import { useTabsStore } from "./stores/tabs"; +import { restoredTitles, useTabsStore } from "./stores/tabs"; // Re-exported so existing callers (e.g. tests) can keep importing from this module. export { STATE_PERSIST_DEBOUNCE_MS }; @@ -47,6 +48,45 @@ function toSnapshot(workspaceId: string): LayoutSnapshot | null { }; } +/** Restore tabs and repair layout references before installing persistence. */ +export function hydrateLayoutSnapshots(snapshots: AppState["layoutByWorkspace"]): void { + if (snapshots) { + for (const [wsId, snap] of Object.entries(snapshots)) { + try { + const tabsMap: Record< + string, + (typeof snap.tabs)[number] & { + isPreview: boolean; + isPinned: boolean; + defaultTitle: string; + } + > = {}; + for (const t of snap.tabs) { + const isPreview = + "isPreview" in t && typeof t.isPreview === "boolean" ? t.isPreview : false; + const isPinned = "isPinned" in t && typeof t.isPinned === "boolean" ? t.isPinned : false; + // Its titles as saved: a rename stays the user's, and a name the + // app gives follows its language (restoredTitles). + tabsMap[t.id] = { ...t, isPreview, isPinned, ...restoredTitles(t) }; + } + useTabsStore.setState((s) => ({ + byWorkspace: { ...s.byWorkspace, [wsId]: tabsMap }, + })); + + const knownTabIds = new Set(snap.tabs.map((t) => t.id)); + useLayoutStore + .getState() + .hydrate(wsId, { root: snap.root, activeGroupId: snap.activeGroupId }, knownTabIds); + // Layouts saved before pinning reordered tabs can hold pinned tabs + // behind unpinned ones. + normalizeWorkspaceTabOrder(wsId); + } catch { + // Silent repair: skip invalid snapshot for this workspace + } + } + } +} + // --------------------------------------------------------------------------- // Debounce helper // --------------------------------------------------------------------------- diff --git a/src/renderer/utils/path.ts b/src/renderer/utils/path.ts index 3319455c8..55818644f 100644 --- a/src/renderer/utils/path.ts +++ b/src/renderer/utils/path.ts @@ -1,3 +1,5 @@ +export { isWithinWorkspace } from "../../shared/fs/workspace-path"; + // Tiny path helpers for renderer code that already speaks in absolute // POSIX-style paths (the `filePath` strings stored in EditorTabProps). // @@ -6,22 +8,6 @@ // `/` separators and don't try to handle Windows backslashes (the main // process normalizes incoming paths already). -/** Resolve `.` and `..` segments in a POSIX absolute path without Node. */ -function normalizePosix(p: string): string { - const parts = p.split("/"); - const resolved: string[] = []; - for (const part of parts) { - if (part === "..") { - resolved.pop(); - } else if (part !== ".") { - resolved.push(part); - } - } - const result = resolved.join("/"); - // Preserve the leading `/` — an absolute path should always start with one. - return result.startsWith("/") ? result : `/${result}`; -} - /** * Last `/`-separated segment of a path. Returns the input unchanged for * paths without a separator (so `basename("foo")` → `"foo"`, matching @@ -56,22 +42,3 @@ export function shownPath(path: string, cwd: string): string { const rel = relPath(slashed, base); return rel && rel !== slashed ? rel : path; } - -/** - * Returns true when `absPath` is inside (or exactly equal to) `workspaceRootPath`. - * - * Both paths are POSIX-normalized (`.` / `..` resolved) and trailing slashes - * are stripped before comparison, so naive prefix matches like `/workspace2` - * starting with `/workspace` are rejected correctly. - */ -export function isWithinWorkspace(absPath: string, workspaceRootPath: string): boolean { - if (!workspaceRootPath || !absPath) return false; - - const root = normalizePosix(workspaceRootPath).replace(/\/+$/, ""); - const target = normalizePosix(absPath).replace(/\/+$/, ""); - - if (!root) return false; - - if (target === root) return true; - return target.startsWith(`${root}/`); -} diff --git a/src/shared/fs/workspace-path.ts b/src/shared/fs/workspace-path.ts new file mode 100644 index 000000000..8572be41b --- /dev/null +++ b/src/shared/fs/workspace-path.ts @@ -0,0 +1,34 @@ +/** Resolve `.` and `..` segments in a POSIX absolute path without Node. */ +function normalizePosix(p: string): string { + const parts = p.split("/"); + const resolved: string[] = []; + for (const part of parts) { + if (part === "..") { + resolved.pop(); + } else if (part !== ".") { + resolved.push(part); + } + } + const result = resolved.join("/"); + // Preserve the leading `/` — an absolute path should always start with one. + return result.startsWith("/") ? result : `/${result}`; +} + +/** + * Returns true when `absPath` is inside (or exactly equal to) `workspaceRootPath`. + * + * Both paths are POSIX-normalized (`.` / `..` resolved) and trailing slashes + * are stripped before comparison, so naive prefix matches like `/workspace2` + * starting with `/workspace` are rejected correctly. + */ +export function isWithinWorkspace(absPath: string, workspaceRootPath: string): boolean { + if (!workspaceRootPath || !absPath) return false; + + const root = normalizePosix(workspaceRootPath).replace(/\/+$/, ""); + const target = normalizePosix(absPath).replace(/\/+$/, ""); + + if (!root) return absPath.startsWith("/"); + + if (target === root) return true; + return target.startsWith(`${root}/`); +} diff --git a/src/shared/types/layout.ts b/src/shared/types/layout.ts index 92cebd395..48222afc7 100644 --- a/src/shared/types/layout.ts +++ b/src/shared/types/layout.ts @@ -22,6 +22,7 @@ export type TerminalTabProps = z.infer; export const EditorTabPropsSchema = z.object({ filePath: z.string(), workspaceId: WorkspaceIdSchema, + origin: z.enum(["workspace", "external"]).optional(), }); export type EditorTabProps = z.infer; diff --git a/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts b/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts index a29ac81e3..834579002 100644 --- a/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts +++ b/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts @@ -1,218 +1,216 @@ -/** - * Unit tests for UntitledTab and BrowserTab additions. - * - * Covers: - * - BrowserTab round-trip through toSnapshot (present) and fromSnapshot - * - UntitledTab is stripped from toSnapshot (not persisted) - */ - -import { beforeEach, describe, expect, it } from "bun:test"; - -// --------------------------------------------------------------------------- -// Shims -// --------------------------------------------------------------------------- - -(globalThis as Record).window = { - ipc: { - call: () => Promise.resolve(null), - listen: () => {}, - off: () => {}, +import { afterEach, beforeAll, expect, mock, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { registerAppStateChannel } from "../../../../../../src/main/features/app-state"; +import { setupRouter } from "../../../../../../src/main/infra/ipc-router"; +import { StateService } from "../../../../../../src/main/infra/storage/state-service"; +import type { WorkspaceLayoutSnapshot } from "../../../../../../src/shared/types/layout"; +import type { WorkspaceMeta } from "../../../../../../src/shared/types/workspace"; + +type Invoke = ( + event: { sender?: { id: number } }, + channel: string, + method: string, + args: unknown, +) => Promise; + +let invoke: Invoke; +mock.module("electron", () => ({ + ipcMain: { + handle: (channel: string, handler: Invoke) => { + if (channel === "ipc:call") invoke = handler; + }, + on: () => {}, }, +})); + +const originalWindow = globalThis.window; +let write: ReturnType>; +let schedule: (() => void) | undefined; + +const { hydrateLayoutSnapshots, registerStatePersistence, unregisterStatePersistence } = + await import("../../../../../../src/renderer/state/persistence"); +const { useLayoutStore } = await import("../../../../../../src/renderer/state/stores/layout"); +const { useTabsStore } = await import("../../../../../../src/renderer/state/stores/tabs"); +const { ipcCallResult, mustSucceed } = await import("../../../../../../src/renderer/ipc/client"); + +const workspaceId = "aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa"; +const workspace: WorkspaceMeta = { + id: workspaceId, + rootPath: "/repo", + name: "Repo", + location: { kind: "local", rootPath: "/repo" }, + colorTone: "default", + pinned: false, + sortOrder: 1, + pinnedSortOrder: 0, + tabs: [], }; -if (typeof (globalThis as Record).crypto === "undefined") { - let counter = 0; - (globalThis as Record).crypto = { - randomUUID: () => { - counter++; - return `00000000-0000-0000-0000-${String(counter).padStart(12, "0")}`; +/** Pass renderer calls through the real router, using an in-process transport. */ +function connectRenderer(): void { + Object.assign(globalThis, { + window: { + ipc: { + call: async (channel: string, method: string, args: unknown) => { + const result = await invoke( + { sender: { id: 1 } }, + channel, + method, + structuredClone(args), + ); + if (channel === "appState" && method === "set") write.resolve(result); + return structuredClone(result); + }, + }, }, - }; + }); } -// --------------------------------------------------------------------------- -// Imports after shims -// --------------------------------------------------------------------------- - -import { useLayoutStore } from "../../../../../../src/renderer/state/stores/layout"; -import type { Tab } from "../../../../../../src/renderer/state/stores/tabs"; -import { useTabsStore } from "../../../../../../src/renderer/state/stores/tabs"; -import { WorkspaceLayoutSnapshotSchema } from "../../../../../../src/shared/types/layout"; - -// --------------------------------------------------------------------------- -// Fixtures -// --------------------------------------------------------------------------- - -const WS = "aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaaa"; - -function resetStores() { +/** Clear the two stores to simulate a new render process. */ +function resetStores(): void { useTabsStore.setState({ byWorkspace: {} }); useLayoutStore.setState({ byWorkspace: {} }); } -/** - * Inline equivalent of persistence.ts toSnapshot (strips untitled tabs). - */ -function buildSnapshot(workspaceId: string) { - const layout = useLayoutStore.getState().byWorkspace[workspaceId]; - const tabRecord = useTabsStore.getState().byWorkspace[workspaceId] ?? {}; - if (!layout) return null; - const tabs = Object.values(tabRecord).filter((t) => t.type !== "untitled") as Tab[]; - return { - root: layout.root, - activeGroupId: layout.activeGroupId, - tabs, - }; +/** Restore the app state's layouts through the bootstrap hydration path. */ +async function restore(): Promise { + resetStores(); + const state = mustSucceed(await ipcCallResult("appState", "get", undefined)); + hydrateLayoutSnapshots(state.layoutByWorkspace); } -// --------------------------------------------------------------------------- -// Persistence: BrowserTab roundtrip (present in snapshot), UntitledTab stripped -// --------------------------------------------------------------------------- - -describe("persistence — BrowserTab roundtrip through snapshot", () => { - beforeEach(resetStores); - - it("BrowserTab is present in the snapshot and passes zod parse", () => { - // Create a layout root first (openTerminalTab would do, but we can inject - // the tab directly and manually build a minimal layout). - const props = { - initialUrl: "https://example.com", - lastUrl: "https://example.com/docs", - partition: `persist:browser-${WS}`, - }; - const tab = useTabsStore.getState().createTab(WS, { type: "browser", props }); - - const leafId = "11111111-1111-4111-b111-111111111111"; - // Inject a minimal layout so buildSnapshot can find it. - useLayoutStore.setState({ - byWorkspace: { - [WS]: { - root: { - kind: "leaf", - id: leafId, - tabIds: [tab.id], - activeTabId: tab.id, - }, - activeGroupId: leafId, - }, - }, - }); - - const snapshot = buildSnapshot(WS); - expect(snapshot).not.toBeNull(); - - // BrowserTab must be present - expect(snapshot!.tabs).toHaveLength(1); - expect(snapshot!.tabs[0]!.type).toBe("browser"); - - // Full zod parse must succeed - const result = WorkspaceLayoutSnapshotSchema.safeParse(snapshot); - expect(result.success).toBe(true); - - if (result.success) { - const parsed = result.data.tabs[0]; - expect(parsed?.type).toBe("browser"); - if (parsed?.type === "browser") { - expect(parsed.props.initialUrl).toBe(props.initialUrl); - expect(parsed.props.lastUrl).toBe(props.lastUrl); - expect(parsed.props.partition).toBe(props.partition); - } - } - }); - - it("BrowserTab fields survive JSON.stringify → JSON.parse → zod parse", () => { - const props = { - initialUrl: "https://roundtrip.test", - lastUrl: "https://roundtrip.test/end", - partition: "persist:browser-rt", - }; - const tab = useTabsStore.getState().createTab(WS, { type: "browser", props }); - - const leafId = "22222222-2222-4222-b222-222222222222"; - useLayoutStore.setState({ - byWorkspace: { - [WS]: { - root: { - kind: "leaf", - id: leafId, - tabIds: [tab.id], - activeTabId: tab.id, - }, - activeGroupId: leafId, - }, - }, - }); +/** Add a tab through the same stores used by the workbench. */ +function addTab(args: Parameters["createTab"]>[1]) { + const layout = useLayoutStore.getState(); + layout.ensureLayout(workspaceId); + const tab = useTabsStore.getState().createTab(workspaceId, args); + layout.attachTab( + workspaceId, + useLayoutStore.getState().byWorkspace[workspaceId].activeGroupId, + tab.id, + ); + return tab.id; +} - const snapshot = buildSnapshot(WS); - const result = WorkspaceLayoutSnapshotSchema.safeParse(JSON.parse(JSON.stringify(snapshot))); - expect(result.success).toBe(true); - - if (result.success) { - const parsed = result.data.tabs[0]; - if (parsed?.type === "browser") { - expect(parsed.props.initialUrl).toBe(props.initialUrl); - expect(parsed.props.lastUrl).toBe(props.lastUrl); - expect(parsed.props.partition).toBe(props.partition); - } - } - }); +beforeAll(setupRouter); +afterEach(() => { + unregisterStatePersistence(); + resetStores(); + Object.assign(globalThis, { window: originalWindow }); }); -describe("persistence — UntitledTab is stripped from snapshot", () => { - beforeEach(resetStores); - - it("UntitledTab does not appear in toSnapshot output", () => { - const untitled = useTabsStore - .getState() - .createTab(WS, { type: "untitled", props: { untitledIndex: 1 } }); - - const leafId = "33333333-3333-4333-b333-333333333333"; - useLayoutStore.setState({ - byWorkspace: { - [WS]: { - root: { - kind: "leaf", - id: leafId, - tabIds: [untitled.id], - activeTabId: untitled.id, - }, - activeGroupId: leafId, - }, +test("restores external and workspace files beside a browser while excluding Untitled", async () => { + const dir = mkdtempSync(join(tmpdir(), "nx-layout-roundtrip-")); + const stateFile = join(dir, "app-state.json"); + write = Promise.withResolvers(); + connectRenderer(); + registerAppStateChannel(new StateService(stateFile), { listWorkspaces: () => [workspace] }); + + const timer = globalThis.setTimeout; + const cancel = globalThis.clearTimeout; + try { + // Control the real renderer persistence subscriber's debounce without sleeping. + globalThis.setTimeout = ((callback: () => void) => { + schedule = callback; + return 1; + }) as typeof setTimeout; + globalThis.clearTimeout = (() => { + schedule = undefined; + }) as typeof clearTimeout; + + registerStatePersistence(); + const external = addTab({ + type: "editor", + props: { workspaceId, filePath: "/outside/file.txt", origin: "external", readOnly: true }, + }); + const internal = addTab({ + type: "editor", + props: { workspaceId, filePath: "/repo/file.txt" }, + }); + const browser = addTab({ + type: "browser", + props: { + initialUrl: "https://example.com", + lastUrl: "https://example.com/end", + partition: "p", }, }); + const untitled = addTab({ type: "untitled", props: { untitledIndex: 1 } }); + schedule?.(); + await write.promise; + unregisterStatePersistence(); + const reloaded = new StateService(stateFile); + expect(reloaded.getState().layoutByWorkspace?.[workspaceId]?.tabs[0]).toMatchObject({ + props: { origin: "external" }, + }); + registerAppStateChannel(reloaded, { listWorkspaces: () => [workspace] }); + await restore(); - const snapshot = buildSnapshot(WS); - expect(snapshot).not.toBeNull(); - // Untitled tabs must be stripped — tabs array should be empty - expect(snapshot!.tabs).toHaveLength(0); - }); - - it("mixing BrowserTab and UntitledTab: only BrowserTab survives snapshot", () => { - const untitled = useTabsStore - .getState() - .createTab(WS, { type: "untitled", props: { untitledIndex: 2 } }); - const browser = useTabsStore.getState().createTab(WS, { + const tabs = useTabsStore.getState().byWorkspace[workspaceId]; + expect(tabs[external]).toMatchObject({ type: "editor", props: { origin: "external" } }); + expect(tabs[internal]).toMatchObject({ type: "editor", props: { filePath: "/repo/file.txt" } }); + expect(tabs[browser]).toMatchObject({ type: "browser", - props: { initialUrl: "https://keep.me", lastUrl: "", partition: "p" }, + props: { lastUrl: "https://example.com/end" }, }); - - const leafId = "44444444-4444-4444-b444-444444444444"; - useLayoutStore.setState({ - byWorkspace: { - [WS]: { - root: { - kind: "leaf", - id: leafId, - tabIds: [untitled.id, browser.id], - activeTabId: browser.id, - }, - activeGroupId: leafId, - }, - }, + expect(tabs[untitled]).toBeUndefined(); + expect(useLayoutStore.getState().byWorkspace[workspaceId].root).toMatchObject({ + tabIds: [external, internal, browser], }); + } finally { + globalThis.setTimeout = timer; + globalThis.clearTimeout = cancel; + rmSync(dir, { recursive: true, force: true }); + } +}); - const snapshot = buildSnapshot(WS); - expect(snapshot!.tabs).toHaveLength(1); - expect(snapshot!.tabs[0]!.type).toBe("browser"); - }); +/** A snapshot written before the editor's origin could be stored. */ +function legacySnapshot(id: string): WorkspaceLayoutSnapshot { + const groupId = crypto.randomUUID(); + const tabs = ["/repo/in.txt", "/outside/out.txt", "relative.txt"].map((filePath) => ({ + id: crypto.randomUUID(), + title: filePath, + type: "editor" as const, + props: { filePath, workspaceId: id }, + })); + return { + root: { kind: "leaf", id: groupId, tabIds: tabs.map((tab) => tab.id), activeTabId: tabs[2].id }, + activeGroupId: groupId, + tabs, + }; +} + +test("recovers only unambiguous legacy local external paths and repairs dropped tab references", async () => { + const dir = mkdtempSync(join(tmpdir(), "nx-layout-legacy-")); + connectRenderer(); + const remote = { + ...workspace, + id: crypto.randomUUID(), + location: { kind: "ssh" as const, host: "example.invalid", remotePath: "/repo" }, + }; + try { + const state = new StateService(join(dir, "app-state.json")); + const local = legacySnapshot(workspaceId); + const ssh = legacySnapshot(remote.id); + state.setState({ layoutByWorkspace: { [workspaceId]: local, [remote.id]: ssh } }); + registerAppStateChannel(state, { listWorkspaces: () => [workspace, remote] }); + await restore(); + + const { byWorkspace } = useTabsStore.getState(); + expect(byWorkspace[workspaceId][local.tabs[0].id]).toMatchObject({ + props: { filePath: "/repo/in.txt" }, + }); + expect(byWorkspace[workspaceId][local.tabs[1].id]).toMatchObject({ + props: { origin: "external" }, + }); + expect(byWorkspace[workspaceId][local.tabs[2].id]).toBeUndefined(); + expect(Object.keys(byWorkspace[remote.id])).toEqual([ssh.tabs[0].id]); + expect(useLayoutStore.getState().byWorkspace[workspaceId].root).toMatchObject({ + tabIds: [local.tabs[0].id, local.tabs[1].id], + }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } }); From 620b1f50fe8bafe2af1d0a1cfc025608637d8c1c Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:38:54 +0900 Subject: [PATCH 026/208] fix(lsp): bound stdin writes and isolate server queues Co-Authored-By: Claude Opus 5.5 --- internal/dispatch/dispatch.go | 25 +++++- internal/lsp/correlation_test.go | 2 +- internal/lsp/server.go | 72 +++++++++++---- internal/lsp/server_lifecycle.go | 32 +++++-- internal/lsp/server_messages.go | 7 +- internal/lsp/service.go | 57 +++++++----- internal/lsp/stall_test.go | 73 +++++++++++++++ internal/lsp/types.go | 1 + internal/lsp/watched_files_router.go | 3 +- internal/stdioserver/host.go | 114 ++++++++++++++---------- internal/stdioserver/host_order_test.go | 88 +++++++++++++++--- 11 files changed, 360 insertions(+), 114 deletions(-) create mode 100644 internal/lsp/stall_test.go diff --git a/internal/dispatch/dispatch.go b/internal/dispatch/dispatch.go index 25fca7833..b789432df 100644 --- a/internal/dispatch/dispatch.go +++ b/internal/dispatch/dispatch.go @@ -25,12 +25,12 @@ type Handler func(ctx context.Context, params json.RawMessage) (any, error) // do not need synchronization. type Dispatcher struct { handlers map[string]Handler - ordered map[string]bool + ordered map[string]func(json.RawMessage) string } // New constructs an empty Dispatcher ready for Register calls. func New() *Dispatcher { - return &Dispatcher{handlers: make(map[string]Handler), ordered: make(map[string]bool)} + return &Dispatcher{handlers: make(map[string]Handler), ordered: make(map[string]func(json.RawMessage) string)} } // Register binds `method` to `handler`. The last registration wins — @@ -45,13 +45,30 @@ func (d *Dispatcher) Register(method string, handler Handler) { // its requests one at a time, in the order they arrived, instead of each // on its own goroutine. The order holds across every ordered method. func (d *Dispatcher) RegisterOrdered(method string, handler Handler) { + d.RegisterOrderedBy(method, handler, nil) +} + +// RegisterOrderedBy runs matching requests in arrival order for each key. +// Methods with the same key share a queue, including consecutive requests +// that use different methods. A nil key function uses the default queue. +func (d *Dispatcher) RegisterOrderedBy(method string, handler Handler, key func(json.RawMessage) string) { d.handlers[method] = handler - d.ordered[method] = true + d.ordered[method] = key } // Ordered reports whether `method` was registered with RegisterOrdered. func (d *Dispatcher) Ordered(method string) bool { - return d.ordered[method] + _, ok := d.ordered[method] + return ok +} + +// OrderKey returns the queue for a request registered as ordered. +func (d *Dispatcher) OrderKey(req proto.Request) (string, bool) { + key, ordered := d.ordered[req.Method] + if key == nil { + return "", ordered + } + return key(req.Params), true } // Methods returns a sorted slice of all registered method names. diff --git a/internal/lsp/correlation_test.go b/internal/lsp/correlation_test.go index f388b0330..443c51ade 100644 --- a/internal/lsp/correlation_test.go +++ b/internal/lsp/correlation_test.go @@ -27,7 +27,7 @@ func TestServerRequestCorrelationCleansThousandRequests(t *testing.T) { var writes bytes.Buffer server := newServerProcess(service, "lsp-test", SpawnParams{}, 0) server.stdin = bufferWriteCloser{Buffer: &writes} - service.storeServer(server) + service.servers[server.id] = server const requestCount = 1000 for i := 0; i < requestCount; i++ { diff --git a/internal/lsp/server.go b/internal/lsp/server.go index beb966464..b38854a35 100644 --- a/internal/lsp/server.go +++ b/internal/lsp/server.go @@ -31,7 +31,9 @@ type serverProcess struct { stdout io.ReadCloser stderr io.ReadCloser - writeMu sync.Mutex + writeSlot chan struct{} + inputDone chan struct{} + abortOnce sync.Once mu sync.Mutex internalSeq uint64 @@ -76,6 +78,8 @@ func newServerProcess(service *Service, id string, p SpawnParams, idleTimeout ti pendingServerRequests: make(map[string]json.RawMessage), pendingWatchedFileRegistrations: make(map[string][]watchedFileRegistration), done: make(chan struct{}), + writeSlot: make(chan struct{}, 1), + inputDone: make(chan struct{}), } } @@ -192,7 +196,7 @@ func (p *serverProcess) initialize(ctx context.Context) (json.RawMessage, *Serve } } - if err := p.notify("initialized", map[string]any{}); err != nil { + if err := p.notify(ctx, "initialized", map[string]any{}); err != nil { return nil, nil, err } return capabilities, serverInfo, nil @@ -267,7 +271,7 @@ func (p *serverProcess) request(ctx context.Context, method string, params any) p.deleteInternal(key) return nil, err } - if err := p.sendRaw(raw); err != nil { + if err := p.sendRaw(ctx, raw); err != nil { p.deleteInternal(key) return nil, err } @@ -293,7 +297,7 @@ func (p *serverProcess) request(ctx context.Context, method string, params any) } } -func (p *serverProcess) notify(method string, params any) error { +func (p *serverProcess) notify(ctx context.Context, method string, params any) error { message := struct { JSONRPC string `json:"jsonrpc"` Method string `json:"method"` @@ -307,10 +311,10 @@ func (p *serverProcess) notify(method string, params any) error { if err != nil { return err } - return p.sendRaw(raw) + return p.sendRaw(ctx, raw) } -func (p *serverProcess) cancel(requestID json.RawMessage) error { +func (p *serverProcess) cancel(ctx context.Context, requestID json.RawMessage) error { message := struct { JSONRPC string `json:"jsonrpc"` Method string `json:"method"` @@ -326,27 +330,59 @@ func (p *serverProcess) cancel(requestID json.RawMessage) error { if err != nil { return err } - return p.sendRaw(raw) + return p.sendRaw(ctx, raw) } -func (p *serverProcess) sendRaw(message json.RawMessage) error { +// sendRaw bounds both writer acquisition and the pipe write. An interrupted +// write may leave a partial frame, so that server's input is closed permanently. +func (p *serverProcess) sendRaw(ctx context.Context, message json.RawMessage) error { frame, err := EncodeRawMessage(message) if err != nil { return protocolError(err.Error()) } - p.mu.Lock() - exited := p.exited - p.mu.Unlock() - if exited { + writeCtx, cancel := context.WithTimeout(ctx, stdinWriteTimeout) + defer cancel() + select { + case p.writeSlot <- struct{}{}: + defer func() { <-p.writeSlot }() + case <-writeCtx.Done(): + return writeCtx.Err() + case <-p.inputDone: + return requestFailed("lsp server input closed") + case <-p.done: + return requestFailed("lsp server exited") + } + if err := writeCtx.Err(); err != nil { + return err + } + select { + case <-p.inputDone: + return requestFailed("lsp server input closed") + case <-p.done: return requestFailed("lsp server exited") + default: } - p.writeMu.Lock() - defer p.writeMu.Unlock() - _, err = p.stdin.Write(frame) - if err != nil { - return requestFailed("lsp write failed: %s", err) + // A write deadline is unavailable on some child pipes. Keep the waiter + // cancellable independently of the OS write and abort the pipe on timeout. + written := make(chan error, 1) + go func() { + _, err := p.stdin.Write(frame) + written <- err + }() + select { + case err := <-written: + if err != nil { + return requestFailed("lsp write failed: %s", err) + } + return nil + case <-writeCtx.Done(): + p.abortInput() + return writeCtx.Err() + case <-p.inputDone: + return requestFailed("lsp server input closed") + case <-p.done: + return requestFailed("lsp server exited") } - return nil } diff --git a/internal/lsp/server_lifecycle.go b/internal/lsp/server_lifecycle.go index d31d634ef..fd5d3bf45 100644 --- a/internal/lsp/server_lifecycle.go +++ b/internal/lsp/server_lifecycle.go @@ -26,12 +26,22 @@ func (p *serverProcess) doShutdown(ctx context.Context) error { _, requestErr := p.request(requestCtx, "shutdown", nil) cancel() - _ = p.notify("exit", nil) - if p.waitForExit(shutdownExitGrace) { - return requestErr + // A server may ignore shutdown yet still honor exit. Give the exit frame + // and process a shared grace period, including any wait for its writer. + if ctx.Err() == nil { + exitCtx, cancelExit := context.WithTimeout(ctx, shutdownExitGrace) + if err := p.notify(exitCtx, "exit", nil); err == nil { + select { + case <-p.done: + cancelExit() + return requestErr + case <-exitCtx.Done(): + } + } + cancelExit() } - p.kill() + p.abortInput() if p.waitForExit(shutdownExitGrace) { return requestErr } @@ -41,10 +51,20 @@ func (p *serverProcess) doShutdown(ctx context.Context) error { func (p *serverProcess) forceClose() { p.stopIdleTimer() p.markShuttingDown() - p.kill() + p.abortInput() p.waitForExit(shutdownExitGrace) } +// abortInput rejects future writes immediately and unblocks the current one. +// Kill the reader before closing the pipe, which can wait for OS I/O. +func (p *serverProcess) abortInput() { + p.abortOnce.Do(func() { + close(p.inputDone) + p.kill() + go func() { _ = p.stdin.Close() }() + }) +} + // markShuttingDown has serverExited say the agent stopped the server. func (p *serverProcess) markShuttingDown() { p.mu.Lock() @@ -58,7 +78,7 @@ func (p *serverProcess) resetIdleTimer() { } p.mu.Lock() defer p.mu.Unlock() - if p.exited { + if p.exited || p.shuttingDown { return } if p.idleTimer == nil { diff --git a/internal/lsp/server_messages.go b/internal/lsp/server_messages.go index f3d7ed845..defeea458 100644 --- a/internal/lsp/server_messages.go +++ b/internal/lsp/server_messages.go @@ -1,6 +1,7 @@ package lsp import ( + "context" "encoding/json" "io" ) @@ -122,7 +123,7 @@ func (p *serverProcess) handleServerRequest(id json.RawMessage, method string, p } } -func (p *serverProcess) respondServerRequest(params RespondServerRequestParams) error { +func (p *serverProcess) respondServerRequest(ctx context.Context, params RespondServerRequestParams) error { p.mu.Lock() id := p.pendingServerRequests[params.AgentRequestID] watchedFileRegistrations := p.pendingWatchedFileRegistrations[params.AgentRequestID] @@ -151,7 +152,7 @@ func (p *serverProcess) respondServerRequest(params RespondServerRequestParams) if err != nil { return err } - if err := p.sendRaw(raw); err != nil { + if err := p.sendRaw(ctx, raw); err != nil { return err } if len(params.Error) == 0 { @@ -173,5 +174,5 @@ func (p *serverProcess) sendErrorResponse(id json.RawMessage, code int, message if err != nil { return } - _ = p.sendRaw(raw) + _ = p.sendRaw(context.Background(), raw) } diff --git a/internal/lsp/service.go b/internal/lsp/service.go index 9cb4a5885..31a0f35cd 100644 --- a/internal/lsp/service.go +++ b/internal/lsp/service.go @@ -53,15 +53,25 @@ func newServerIDPrefix() string { // document wrong until it is reopened. func Register(d *dispatch.Dispatcher, service *Service) { d.Register("lsp.spawn", service.Spawn) - d.RegisterOrdered("lsp.send", service.Send) - d.RegisterOrdered("lsp.notify", service.Notify) - d.RegisterOrdered("lsp.cancel", service.Cancel) + d.RegisterOrderedBy("lsp.send", service.Send, serverQueueKey) + d.RegisterOrderedBy("lsp.notify", service.Notify, serverQueueKey) + d.RegisterOrderedBy("lsp.cancel", service.Cancel, serverQueueKey) d.Register("lsp.shutdown", service.Shutdown) - d.RegisterOrdered("lsp.respondServerRequest", service.RespondServerRequest) + d.RegisterOrderedBy("lsp.respondServerRequest", service.RespondServerRequest, serverQueueKey) d.Register("lsp.stats", service.Stats) d.Register("lsp.findBinary", service.FindBinary) } +// serverQueueKey keeps document updates, requests and cancellations for one +// server in the same arrival queue. +func serverQueueKey(raw json.RawMessage) string { + var params struct { + ServerID string `json:"serverId"` + } + _ = json.Unmarshal(raw, ¶ms) + return "lsp:" + params.ServerID +} + // SetEventSink wires the service to the stdio host after both are constructed. func (s *Service) SetEventSink(sink EventSink) { s.mu.Lock() @@ -133,10 +143,7 @@ func (s *Service) Spawn(ctx context.Context, raw json.RawMessage) (any, error) { InitializationOptions: p.InitializationOptions, }, idleTimeout) - s.storeServer(server) - - if err := server.start(ctx); err != nil { - s.removeServer(serverID, server) + if err := s.startServer(ctx, server); err != nil { return nil, err } @@ -162,6 +169,18 @@ func (s *Service) Spawn(ctx context.Context, raw json.RawMessage) (any, error) { return SpawnResult{ServerID: serverID, Capabilities: capabilities, ServerInfo: serverInfo}, nil } +// startServer publishes the child and its pipes together. A concurrent close +// or early process exit can only see the fully started process. +func (s *Service) startServer(ctx context.Context, server *serverProcess) error { + s.mu.Lock() + defer s.mu.Unlock() + if err := server.start(ctx); err != nil { + return err + } + s.servers[server.id] = server + return nil +} + // Stats reports the memory each server takes, with the processes it // started. func (s *Service) Stats(_ context.Context, _ json.RawMessage) (any, error) { @@ -192,7 +211,7 @@ func (s *Service) Stats(_ context.Context, _ json.RawMessage) (any, error) { return result, nil } -func (s *Service) Send(_ context.Context, raw json.RawMessage) (any, error) { +func (s *Service) Send(ctx context.Context, raw json.RawMessage) (any, error) { var p SendParams if err := decodeParams(raw, &p, "lsp.send params must include serverId and message"); err != nil { return nil, err @@ -202,7 +221,7 @@ func (s *Service) Send(_ context.Context, raw json.RawMessage) (any, error) { return nil, err } server.resetIdleTimer() - if err := server.sendRaw(p.Message); err != nil { + if err := server.sendRaw(ctx, p.Message); err != nil { return nil, err } return struct{}{}, nil @@ -214,7 +233,7 @@ func (s *Service) Send(_ context.Context, raw json.RawMessage) (any, error) { // a semantically-empty round-trip on every keystroke. The handler forwards // the message to the LSP child process and returns a void ack just like Send, // but having a dedicated method name keeps the intent unambiguous on both sides. -func (s *Service) Notify(_ context.Context, raw json.RawMessage) (any, error) { +func (s *Service) Notify(ctx context.Context, raw json.RawMessage) (any, error) { var p NotifyParams if err := decodeParams(raw, &p, "lsp.notify params must include serverId and message"); err != nil { return nil, err @@ -224,13 +243,13 @@ func (s *Service) Notify(_ context.Context, raw json.RawMessage) (any, error) { return nil, err } server.resetIdleTimer() - if err := server.sendRaw(p.Message); err != nil { + if err := server.sendRaw(ctx, p.Message); err != nil { return nil, err } return struct{}{}, nil } -func (s *Service) Cancel(_ context.Context, raw json.RawMessage) (any, error) { +func (s *Service) Cancel(ctx context.Context, raw json.RawMessage) (any, error) { var p CancelParams if err := decodeParams(raw, &p, "lsp.cancel params must include serverId and requestId"); err != nil { return nil, err @@ -243,7 +262,7 @@ func (s *Service) Cancel(_ context.Context, raw json.RawMessage) (any, error) { return nil, err } server.resetIdleTimer() - if err := server.cancel(p.RequestID); err != nil { + if err := server.cancel(ctx, p.RequestID); err != nil { return nil, err } return struct{}{}, nil @@ -266,7 +285,7 @@ func (s *Service) Shutdown(ctx context.Context, raw json.RawMessage) (any, error return struct{}{}, nil } -func (s *Service) RespondServerRequest(_ context.Context, raw json.RawMessage) (any, error) { +func (s *Service) RespondServerRequest(ctx context.Context, raw json.RawMessage) (any, error) { var p RespondServerRequestParams if err := decodeParams(raw, &p, "lsp.respondServerRequest params must include serverId and agentRequestId"); err != nil { return nil, err @@ -289,7 +308,7 @@ func (s *Service) RespondServerRequest(_ context.Context, raw json.RawMessage) ( return nil, err } server.resetIdleTimer() - if err := server.respondServerRequest(p); err != nil { + if err := server.respondServerRequest(ctx, p); err != nil { return nil, err } return struct{}{}, nil @@ -309,12 +328,6 @@ func (s *Service) nextAgentRequestID(serverID string) string { return fmt.Sprintf("%s-server-request-%d", serverID, s.nextAgentSeq) } -func (s *Service) storeServer(server *serverProcess) { - s.mu.Lock() - defer s.mu.Unlock() - s.servers[server.id] = server -} - func (s *Service) removeServer(id string, expected *serverProcess) { s.mu.Lock() defer s.mu.Unlock() diff --git a/internal/lsp/stall_test.go b/internal/lsp/stall_test.go new file mode 100644 index 000000000..9a597981d --- /dev/null +++ b/internal/lsp/stall_test.go @@ -0,0 +1,73 @@ +package lsp + +import ( + "context" + "encoding/json" + "io" + "sync" + "testing" + "time" +) + +// blockedInput models a pipe whose child stopped reading. +type blockedInput struct { + started chan struct{} + closed chan struct{} + once sync.Once + start sync.Once +} + +// Write blocks until the input is force-closed. +func (p *blockedInput) Write([]byte) (int, error) { + p.start.Do(func() { close(p.started) }) + <-p.closed + return 0, io.ErrClosedPipe +} + +// Close releases the blocked writer. +func (p *blockedInput) Close() error { + p.once.Do(func() { close(p.closed) }) + return nil +} + +// TestShutdownClosesBlockedInput verifies that a canceled shutdown can tear +// down a server even when an earlier LSP frame still owns its stdin writer. +func TestShutdownClosesBlockedInput(t *testing.T) { + svc := New() + server := newServerProcess(svc, "stalled", SpawnParams{}, 0) + input := &blockedInput{started: make(chan struct{}), closed: make(chan struct{})} + server.stdin = input + t.Cleanup(func() { _ = input.Close() }) + svc.servers[server.id] = server + go func() { + <-input.closed + server.markExited(nil) + }() + + notify := make(chan error, 1) + go func() { + _, err := svc.Notify(context.Background(), json.RawMessage(`{"serverId":"stalled","message":{"jsonrpc":"2.0","method":"textDocument/didChange"}}`)) + notify <- err + }() + <-input.started + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + shutdown := make(chan error, 1) + go func() { shutdown <- server.Shutdown(ctx) }() + timer := time.NewTimer(time.Second) + defer timer.Stop() + select { + case <-shutdown: + case <-timer.C: + t.Fatal("shutdown waited on the blocked stdin writer") + } + select { + case err := <-notify: + if err == nil { + t.Fatal("blocked write succeeded after shutdown") + } + case <-timer.C: + t.Fatal("shutdown left the write blocked") + } +} diff --git a/internal/lsp/types.go b/internal/lsp/types.go index 523f7c1de..3121720ae 100644 --- a/internal/lsp/types.go +++ b/internal/lsp/types.go @@ -13,6 +13,7 @@ const ( defaultIdleTimeout = 30 * time.Minute initializeTimeout = 5 * time.Second + stdinWriteTimeout = 2 * time.Second shutdownRequestTimeout = 750 * time.Millisecond shutdownExitGrace = 750 * time.Millisecond diff --git a/internal/lsp/watched_files_router.go b/internal/lsp/watched_files_router.go index bcad2f741..99629e99b 100644 --- a/internal/lsp/watched_files_router.go +++ b/internal/lsp/watched_files_router.go @@ -1,6 +1,7 @@ package lsp import ( + "context" "encoding/json" "errors" "path" @@ -57,7 +58,7 @@ func (s *Service) HandleFSChanged(payload agentfs.FsChangedPayload) error { continue } server.resetIdleTimer() - if err := server.notify(methodDidChangeWatchedFiles, didChangeWatchedFilesParams{Changes: changes}); err != nil { + if err := server.notify(context.Background(), methodDidChangeWatchedFiles, didChangeWatchedFilesParams{Changes: changes}); err != nil { errs = append(errs, err) } } diff --git a/internal/stdioserver/host.go b/internal/stdioserver/host.go index 7f6929d58..b1b287b32 100644 --- a/internal/stdioserver/host.go +++ b/internal/stdioserver/host.go @@ -85,9 +85,9 @@ type Host struct { // Guarded by outMu. outClosed bool - // orderedTail is closed when the last ordered request so far has been - // handled; the next one waits on it. Only Run's goroutine touches it. - orderedTail chan struct{} + // Each queue's tail closes once its last request has been handled. + orderedMu sync.Mutex + orderedTail map[string]chan struct{} ctx context.Context cancel context.CancelFunc @@ -132,15 +132,16 @@ type Host struct { func New(d *dispatch.Dispatcher, in io.Reader, out io.Writer, logger *slog.Logger) *Host { ctx, cancel := context.WithCancel(context.Background()) return &Host{ - dispatcher: d, - in: in, - out: out, - logger: logger, - ctx: ctx, - cancel: cancel, - accepting: true, - exit: os.Exit, - startMono: time.Now(), + dispatcher: d, + in: in, + out: out, + logger: logger, + ctx: ctx, + cancel: cancel, + accepting: true, + orderedTail: make(map[string]chan struct{}), + exit: os.Exit, + startMono: time.Now(), } } @@ -245,36 +246,58 @@ func (h *Host) Run() { } // Any inbound line proves the client is alive — reset the idle watchdog. h.stampInbound() - if !h.isAccepting() { - continue - } if tooLong { - h.rejectOversizedLine(line) + if h.isAccepting() { + h.rejectOversizedLine(line) + } continue } - h.wg.Add(1) - if h.dispatcher.Ordered(methodAtStart(line)) { - prev := h.orderedTail - done := make(chan struct{}) - h.orderedTail = done - go func() { - defer h.wg.Done() - defer close(done) - if prev != nil { - <-prev - } - h.handleLine(line) - }() + req, parseErr := proto.ParseRequest(line) + if !h.beginRequest() { continue } + var prev <-chan struct{} + var finish func() + if key, ordered := h.dispatcher.OrderKey(req); parseErr == nil && ordered { + prev, finish = h.enqueueOrdered(key) + } go func() { defer h.wg.Done() - h.handleLine(line) + if finish != nil { + defer finish() + if prev != nil { + select { + case <-prev: + case <-h.ctx.Done(): + return + } + } + } + if h.ctx.Err() == nil { + h.handleRequest(line, req, parseErr) + } }() } h.drainAndExit(0) } +// enqueueOrdered appends a request in input order and removes idle queues. +func (h *Host) enqueueOrdered(key string) (<-chan struct{}, func()) { + h.orderedMu.Lock() + defer h.orderedMu.Unlock() + prev := h.orderedTail[key] + done := make(chan struct{}) + h.orderedTail[key] = done + return prev, func() { + h.orderedMu.Lock() + defer h.orderedMu.Unlock() + close(done) + if h.orderedTail[key] == done { + delete(h.orderedTail, key) + } + } +} + // maxLineBytes caps one inbound request line. It matches the largest request // shape we expect: a writeFile whose content is up to MaxReadableFileSize // (50 MiB), JSON-escaped, plus envelope overhead. 64 MiB leaves headroom for @@ -341,21 +364,6 @@ func dropCR(line []byte) []byte { // Anchoring keeps an "id" inside params from being mistaken for it. var requestIDAtStart = regexp.MustCompile(`^\s*\{\s*"id"\s*:\s*"((?:[^"\\]|\\.)*)"`) -// requestMethodAtStart matches the method of a request line serialized as -// {id, method, params}. -var requestMethodAtStart = regexp.MustCompile(`^\s*\{\s*"id"\s*:\s*"(?:[^"\\]|\\.)*"\s*,\s*"method"\s*:\s*"([^"\\]*)"`) - -// methodAtStart returns the method of a request line without parsing the -// rest of it, which can be megabytes of params, or "" when the line is not -// laid out as the client writes requests. Such a line is not ordered. -func methodAtStart(line []byte) string { - head := line[:min(len(line), lineHeadBytes)] - if match := requestMethodAtStart.FindSubmatch(head); match != nil { - return string(match[1]) - } - return "" -} - // rejectOversizedLine answers a request line that exceeded maxLineBytes // with a protocol error when its id can be read from the line's head, so the // caller fails fast instead of waiting for its timeout; otherwise it is only @@ -508,11 +516,10 @@ func (h *Host) InstallSigtermHandler() { }() } -// handleLine parses one NDJSON line, dispatches the request, and writes +// handleRequest dispatches a parsed request and writes // the resulting response. Parse failures are reported with the best id // recoverable from the raw bytes so the client can still correlate. -func (h *Host) handleLine(line []byte) { - req, err := proto.ParseRequest(line) +func (h *Host) handleRequest(line []byte, req proto.Request, err error) { if err != nil { id := proto.IDFromParsedFrame(line) if id == "" { @@ -528,6 +535,17 @@ func (h *Host) handleLine(line []byte) { _ = h.WriteFrame(h.dispatcher.Dispatch(h.ctx, req)) } +// beginRequest reserves a drain slot before shutdown can begin waiting. +func (h *Host) beginRequest() bool { + h.acceptMu.Lock() + defer h.acceptMu.Unlock() + if !h.accepting { + return false + } + h.wg.Add(1) + return true +} + // isAccepting reports whether the loop should still spawn handlers. // Flipped to false during drainAndExit so requests arriving after // SIGTERM are ignored rather than queued behind in-flight work. diff --git a/internal/stdioserver/host_order_test.go b/internal/stdioserver/host_order_test.go index e3eb85183..b1ce97915 100644 --- a/internal/stdioserver/host_order_test.go +++ b/internal/stdioserver/host_order_test.go @@ -81,18 +81,84 @@ func TestRunKeepsOrderedMethodsInArrivalOrder(t *testing.T) { } } -func TestMethodAtStart(t *testing.T) { - cases := map[string]string{ - `{"id":"r-1","method":"lsp.notify","params":{"serverId":"lsp-1"}}`: "lsp.notify", - ` { "id" : "r-\"2" , "method" : "lsp.send" }`: "lsp.send", - // The method must follow the id: one inside params is not it. - `{"params":{"id":"x","method":"lsp.send"},"id":"r-3","method":"fs.readFile"}`: "", - `{"method":"lsp.send","id":"r-4"}`: "", - `not json`: "", +// TestOrderedRequestsStayWithTheirServer verifies that LSP document updates, +// requests and cancellations for one server can pass a stalled peer's queue. +// The stalled queue's next request is discarded when the host cancels. +func TestOrderedRequestsStayWithTheirServer(t *testing.T) { + type params struct { + ServerID string `json:"serverId"` + Step string `json:"step"` } - for line, want := range cases { - if got := methodAtStart([]byte(line)); got != want { - t.Errorf("methodAtStart(%s) = %q, want %q", line, got, want) + started, release := make(chan struct{}), make(chan struct{}) + steps := make(chan string, 4) + d := dispatch.New() + for _, method := range []string{"lsp.notify", "lsp.send", "lsp.cancel"} { + d.RegisterOrderedBy(method, func(_ context.Context, raw json.RawMessage) (any, error) { + var p params + if err := json.Unmarshal(raw, &p); err != nil { + return nil, err + } + if p.Step == "stall" { + close(started) + <-release + } else { + steps <- p.Step + } + return struct{}{}, nil + }, func(raw json.RawMessage) string { + var p params + _ = json.Unmarshal(raw, &p) + return p.ServerID + }) + } + in, feed := io.Pipe() + defer feed.Close() + host := New(d, in, io.Discard, slog.New(slog.NewTextHandler(io.Discard, nil))) + ended := make(chan struct{}) + host.exit = func(int) { close(ended) } + go host.Run() + releaseStall := sync.OnceFunc(func() { close(release) }) + defer releaseStall() + timeout := time.NewTimer(2 * time.Second) + defer timeout.Stop() + write := func(method, server, step string) { + t.Helper() + // Parsing the full envelope keeps the order independent of key layout. + if _, err := fmt.Fprintf(feed, `{"method":%q,"id":%q,"params":{"serverId":%q,"step":%q}}`+"\n", method, step, server, step); err != nil { + t.Fatal(err) } } + write("lsp.notify", "stalled", "stall") + select { + case <-started: + case <-timeout.C: + t.Fatal("first request did not start") + } + write("lsp.send", "stalled", "obsolete") + write("lsp.notify", "healthy", "change") + write("lsp.send", "healthy", "request") + write("lsp.cancel", "healthy", "cancel") + for _, want := range []string{"change", "request", "cancel"} { + select { + case got := <-steps: + if got != want { + t.Fatalf("request %q ran before %q", got, want) + } + case <-timeout.C: + t.Fatalf("healthy server never handled %q", want) + } + } + host.cancel() + releaseStall() + _ = feed.Close() + select { + case <-ended: + case <-timeout.C: + t.Fatal("canceled host did not end") + } + select { + case got := <-steps: + t.Fatalf("canceled request ran: %q", got) + default: + } } From 80b831c7e815f7fc572dbbeb5735f39cbab24568 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:44:14 +0900 Subject: [PATCH 027/208] fix(agent): wait for local shutdown before quitting Co-Authored-By: Claude Opus 5.5 --- cmd/agent/local_shutdown_test.go | 149 ++++++++++++++++++ cmd/agent/main.go | 26 +-- internal/lsp/service.go | 13 +- src/main/features/lsp/agent-host.ts | 8 +- src/main/features/lsp/agent-lsp-server.ts | 5 +- src/main/features/lsp/host.ts | 2 +- src/main/index.ts | 76 ++++++--- src/main/infra/agent/channel/local-channel.ts | 39 ++++- .../channel/reconnecting-process-channel.ts | 7 +- .../unit/main/agent/reconnect-channel.test.ts | 35 +++- tests/unit/main/lsp/agent-host.test.ts | 30 ++++ 11 files changed, 341 insertions(+), 49 deletions(-) create mode 100644 cmd/agent/local_shutdown_test.go diff --git a/cmd/agent/local_shutdown_test.go b/cmd/agent/local_shutdown_test.go new file mode 100644 index 000000000..d14d9c984 --- /dev/null +++ b/cmd/agent/local_shutdown_test.go @@ -0,0 +1,149 @@ +//go:build !windows + +package main + +import ( + "context" + "encoding/json" + "errors" + "io" + "os" + "os/exec" + "syscall" + "testing" + "time" + + "github.com/nexus-code/nexus-code/internal/lsp" + "github.com/nexus-code/nexus-code/internal/proto" +) + +// TestLocalEOFKillsLanguageServer verifies that the local agent reaps an LSP +// child that stays alive after stdin closes before exiting itself. +func TestLocalEOFKillsLanguageServer(t *testing.T) { + root := t.TempDir() + bin := agentBinary(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, bin, root) + cmd.Env = append(os.Environ(), "HOME="+shortHome(t)) + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + + frames := json.NewDecoder(stdout) + var ready proto.ReadyFrame + if err := frames.Decode(&ready); err != nil || ready.Type != "ready" { + t.Fatalf("ready frame = %+v, %v", ready, err) + } + params, err := json.Marshal(lsp.SpawnParams{ + WorkspaceID: "test", LanguageID: "fake", BinaryPath: os.Args[0], WorkspaceRoot: root, + Args: []string{"-test.run=^TestLocalShutdownLanguageServerHelper$"}, + Env: map[string]string{"NEXUS_TEST_LOCAL_SHUTDOWN_LSP": "1"}, + }) + if err != nil { + t.Fatal(err) + } + if err := json.NewEncoder(stdin).Encode(proto.Request{ID: "spawn", Method: "lsp.spawn", Params: params}); err != nil { + t.Fatal(err) + } + pid := 0 + for pid == 0 { + var frame struct { + ID string `json:"id"` + Error *proto.ErrorFrame `json:"error"` + Result struct { + Capabilities struct { + PID int `json:"testPid"` + } `json:"capabilities"` + } `json:"result"` + } + if err := frames.Decode(&frame); err != nil { + t.Fatal(err) + } + if frame.ID == "spawn" { + pid = frame.Result.Capabilities.PID + if frame.Error != nil || pid == 0 { + t.Fatalf("spawn result = %+v", frame) + } + } + } + childReaped := false + defer func() { + if !childReaped { + _ = syscall.Kill(pid, syscall.SIGKILL) + } + }() + if err := stdin.Close(); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + select { + case err := <-done: + if err != nil { + t.Fatalf("agent exit: %v", err) + } + case <-time.After(5 * time.Second): + _ = cmd.Process.Kill() + <-done + t.Fatal("agent failed to exit") + } + if err := syscall.Kill(pid, 0); !errors.Is(err, syscall.ESRCH) { + t.Fatalf("LSP child %d survived the agent: %v", pid, err) + } + childReaped = true +} + +// TestLocalShutdownLanguageServerHelper runs a child that initializes normally +// and deliberately survives closed stdin. +func TestLocalShutdownLanguageServerHelper(t *testing.T) { + if os.Getenv("NEXUS_TEST_LOCAL_SHUTDOWN_LSP") != "1" { + return + } + decoder := lsp.NewDecoder() + buf := make([]byte, 4*1024) + for { + n, err := os.Stdin.Read(buf) + if errors.Is(err, io.EOF) { + <-time.After(time.Minute) + os.Exit(0) + } + if err != nil { + t.Fatal(err) + } + messages, err := decoder.Append(buf[:n]) + if err != nil { + t.Fatal(err) + } + for _, message := range messages { + var req struct { + ID string `json:"id"` + Method string `json:"method"` + } + if err := json.Unmarshal(message, &req); err != nil { + t.Fatal(err) + } + if req.Method == "initialize" { + response, err := lsp.EncodeMessage(map[string]any{ + "jsonrpc": "2.0", "id": req.ID, + "result": map[string]any{"capabilities": map[string]int{"testPid": os.Getpid()}}, + }) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stdout.Write(response); err != nil { + t.Fatal(err) + } + } + } + } +} diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 6a2c800ee..1c4989cd3 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -14,6 +14,7 @@ import ( "encoding/json" "log/slog" "os" + "sync" "time" agentchat "github.com/nexus-code/nexus-code/internal/chat" @@ -182,18 +183,19 @@ func main() { // 다른 서비스(fs/git/pty)의 SetEventSink와 같은 패턴. hooksrv.SetEventSink(host.EmitEvent) } - defer fsys.Close() - defer git.Close() - defer lsp.Close() - // PTY cleanup runs as a shutdown hook, not a defer: every termination path - // (EOF, SIGTERM, idle watchdog) ends in drainAndExit → os.Exit, which skips - // defers. Pdeathsig (Linux only) and the master-fd-close SIGHUP are not - // enough on their own — a non-Linux remote has no Pdeathsig, and a shell - // that ignores SIGHUP would orphan. The hook hangs up each shell and kills - // what is left of its session if it does not end (pty.Service.Close). - host.RegisterShutdownHook(pty.Close) - // The Claude tabs' programs end with the agent the same way. - host.RegisterShutdownHook(chat.Close) + // Every stdio exit path ends at os.Exit. Start independent cleanup in + // parallel so a slow watcher or shell cannot keep other children alive. + host.RegisterShutdownHook(func() { + var cleanup sync.WaitGroup + for _, closeService := range []func(){pty.Close, chat.Close, lsp.Close, fsys.Close, git.Close} { + cleanup.Add(1) + go func() { + defer cleanup.Done() + closeService() + }() + } + cleanup.Wait() + }) if hooksrv != nil { // SIGTERM 경로는 os.Exit가 defer를 우회하므로 shutdown hook으로 등록한다. // hookserver는 /tmp/nexus-h-*.sock 파일을 생성하므로 정리하지 않으면 diff --git a/internal/lsp/service.go b/internal/lsp/service.go index 31a0f35cd..e12b98407 100644 --- a/internal/lsp/service.go +++ b/internal/lsp/service.go @@ -23,6 +23,7 @@ type Service struct { mu sync.Mutex sink EventSink servers map[string]*serverProcess + closed bool // serverIDPrefix sets this agent's server ids apart from those of the // agent it replaced: when a local agent restarts, calls queued for the @@ -82,6 +83,7 @@ func (s *Service) SetEventSink(sink EventSink) { // Close terminates all active language server processes. func (s *Service) Close() { s.mu.Lock() + s.closed = true servers := make([]*serverProcess, 0, len(s.servers)) for id, server := range s.servers { servers = append(servers, server) @@ -89,9 +91,15 @@ func (s *Service) Close() { } s.mu.Unlock() + var cleanup sync.WaitGroup for _, server := range servers { - server.forceClose() + cleanup.Add(1) + go func() { + defer cleanup.Done() + server.forceClose() + }() } + cleanup.Wait() } func (s *Service) Spawn(ctx context.Context, raw json.RawMessage) (any, error) { @@ -174,6 +182,9 @@ func (s *Service) Spawn(ctx context.Context, raw json.RawMessage) (any, error) { func (s *Service) startServer(ctx context.Context, server *serverProcess) error { s.mu.Lock() defer s.mu.Unlock() + if s.closed { + return requestFailed("lsp service closed") + } if err := server.start(ctx); err != nil { return err } diff --git a/src/main/features/lsp/agent-host.ts b/src/main/features/lsp/agent-host.ts index d52779186..2fd53e3c6 100644 --- a/src/main/features/lsp/agent-host.ts +++ b/src/main/features/lsp/agent-host.ts @@ -559,13 +559,12 @@ class AgentLspHostHandleImpl implements LspHostHandle { return !this.disposed; } - dispose(): void { + /** Drops editor state and waits for the running servers' shutdown replies. */ + async dispose(): Promise { if (this.disposed) return; this.disposed = true; this.diagnosticsDebouncer.clearAll(); - for (const [, server] of this.serversById) { - server.dispose(); - } + const shutdowns = Array.from(this.serversById.values(), (server) => server.dispose()); this.serversById.clear(); this.workspaceServers.clear(); this.serverPromises.clear(); @@ -581,6 +580,7 @@ class AgentLspHostHandleImpl implements LspHostHandle { } this.channelDisposers.clear(); this.listeners.clear(); + await Promise.all(shutdowns); } /** diff --git a/src/main/features/lsp/agent-lsp-server.ts b/src/main/features/lsp/agent-lsp-server.ts index 4010eeaca..8c6a466ae 100644 --- a/src/main/features/lsp/agent-lsp-server.ts +++ b/src/main/features/lsp/agent-lsp-server.ts @@ -192,7 +192,8 @@ export class AgentLspServer { return true; } - dispose(): void { + /** Fails pending editor calls and waits for the server's shutdown reply. */ + async dispose(): Promise { if (this.disposed) return; this.disposed = true; this.textDocumentCache.clear(); @@ -201,7 +202,7 @@ export class AgentLspServer { pending.reject(new Error("server disposed")); } this.pending.clear(); - void this.channel.call("lsp.shutdown", { serverId: this.serverId }).catch(() => {}); + await this.channel.call("lsp.shutdown", { serverId: this.serverId }).catch(() => {}); } // disposePending mirrors dispose() but does not call lsp.shutdown — the diff --git a/src/main/features/lsp/host.ts b/src/main/features/lsp/host.ts index 26ecdeb11..e5a9ca8cf 100644 --- a/src/main/features/lsp/host.ts +++ b/src/main/features/lsp/host.ts @@ -31,7 +31,7 @@ export interface LspHostHandle { rejectServerRequest: (id: string | number, message: string) => void; on: (event: string, cb: EventCallback) => () => void; isAlive: () => boolean; - dispose: () => void; + dispose: () => Promise | void; /** * Dispose the LSP server for a single language within a workspace and * broadcast a workspaceLspReset event for that (workspace, language) pair. diff --git a/src/main/index.ts b/src/main/index.ts index a31cafff8..c7e7bd463 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -97,6 +97,7 @@ import { registerWorkspaceChannel } from "./features/workspace/ipc"; import { WorkspaceManager } from "./features/workspace/manager"; import { registerWslChannel } from "./features/wsl/ipc"; import { getMainI18n, getMainT, initMainI18n } from "./i18n"; +import { waitForLocalAgentShutdowns } from "./infra/agent/channel/local-channel"; import { NEXUS_AGENT_MODE_ENV } from "./infra/agent/local-agent-resolver"; import { registerSshAuthPromptIpcChannels, SshAuthPromptHub } from "./infra/agent/ssh/auth-prompt"; import { createSshChannel } from "./infra/agent/ssh/channel"; @@ -128,7 +129,9 @@ if (!app.requestSingleInstanceLock()) { } /** Opens the app window again after every one was closed; set once the app is ready. */ let reopenAppWindow: (() => void) | null = null; +let quitStarted = false; app.on("second-instance", () => { + if (quitStarted) return; if (hasAppWindow()) showAppWindow(); else reopenAppWindow?.(); }); @@ -831,7 +834,7 @@ app.whenReady().then(async () => { // With every window closed, as macOS keeps the app running: a click on its // Dock icon, or a second launch, opens one again. reopenAppWindow = () => { - if (hasAppWindow()) return; + if (quitStarted || hasAppWindow()) return; const newWin = createMainWindow(stateService.getState()); wireAutofetchWindowFocus(newWin); // Reuse the existing permission manager with the new window. @@ -864,35 +867,60 @@ app.on("window-all-closed", () => { } }); -// Single dispose path on quit. Order: process hosts first (kill children), -// then process-local watchers/coalescers, then the registry that owns repo -// queues, then storage close. Each disposer must be idempotent so this stays -// safe regardless of how far whenReady() progressed. -// // `will-quit`, not `before-quit`: a window can still cancel the quit after // before-quit (unsaved buffers), which would leave the app running with its // agents, terminals and storage already torn down. will-quit fires only // once every window has closed. -app.on("will-quit", () => { - sshBrowseRegistry.dispose(); - cliFeature?.dispose(); - disposeClaudeFeature?.(); - portWatcher?.dispose(); - portForwards?.dispose(); - agentPtyHost?.dispose(); - chatHost?.dispose(); - agentProfiles?.dispose(); - remote?.dispose(); - lspHost?.dispose(); - agentFsWatcher?.dispose(); - gitStatusCoalescer?.clearAll(); - gitWatcher?.dispose(); - gitAutofetch?.dispose(); - void gitHelpersIpc?.dispose(); - gitRegistry?.disposeAll(); - workspaceManager.close(); +let quitReady = false; +app.on("will-quit", (event) => { + if (quitReady) return; + event.preventDefault(); + if (quitStarted) return; + quitStarted = true; + void shutDownMain() + .catch((error) => logger.error("App shutdown failed", error)) + .finally(() => { + quitReady = true; + app.quit(); + }); }); +// Match the Go LSP request, exit and forced-exit grace periods. +const LSP_QUIT_GRACE_MS = 2_250; + +/** Lets LSP servers shut down over the live channels before disposing agents. */ +async function shutDownMain(): Promise { + let lspDeadline: ReturnType | undefined; + try { + sshBrowseRegistry.dispose(); + cliFeature?.dispose(); + disposeClaudeFeature?.(); + portWatcher?.dispose(); + portForwards?.dispose(); + agentPtyHost?.dispose(); + chatHost?.dispose(); + agentProfiles?.dispose(); + remote?.dispose(); + const lspShutdown = lspHost?.dispose(); + agentFsWatcher?.dispose(); + gitStatusCoalescer?.clearAll(); + gitWatcher?.dispose(); + gitAutofetch?.dispose(); + void gitHelpersIpc?.dispose(); + gitRegistry?.disposeAll(); + if (lspShutdown) { + const deadline = new Promise((resolve) => { + lspDeadline = setTimeout(resolve, LSP_QUIT_GRACE_MS); + }); + await Promise.race([lspShutdown, deadline]); + } + } finally { + clearTimeout(lspDeadline); + workspaceManager.close(); + await waitForLocalAgentShutdowns(); + } +} + /** * BrowserWindow focus/blur globally pauses only scheduler due checks. Any * in-flight fetch continues through the repository queue; focus recomputes diff --git a/src/main/infra/agent/channel/local-channel.ts b/src/main/infra/agent/channel/local-channel.ts index 0b7bd1b63..424e3cabc 100644 --- a/src/main/infra/agent/channel/local-channel.ts +++ b/src/main/infra/agent/channel/local-channel.ts @@ -10,9 +10,9 @@ * and tests (ad-hoc). Keeping path resolution outside this module also makes * the channel a thin glue layer that is straightforward to fake in unit tests. * - * Lifecycle mirrors `ssh-channel`: a SIGTERM-then-SIGKILL dispose path, a - * `failure` lifecycle event on spawn or terminal pipe errors, and an `exit` - * event for clean closes that happened after `ready` settled. + * Disposal lets stdin EOF run the local agent's shutdown hooks before the + * hard-kill fallback. Transport failures and clean closes surface through the + * shared channel lifecycle. */ import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; import fs from "node:fs"; @@ -25,6 +25,38 @@ import { createReconnectingProcessChannel, } from "./reconnecting-process-channel"; +// Allow the Go host's 75 ms request drain and 3 s of shutdown hooks to finish. +const LOCAL_AGENT_SHUTDOWN_MS = 3_500; +const pendingLocalShutdowns = new Set>(); + +/** Waits for local agents already being disposed, including removed workspaces. */ +export async function waitForLocalAgentShutdowns(): Promise { + await Promise.all(pendingLocalShutdowns); +} + +/** Tracks EOF-driven shutdown until the agent closes or the kill deadline. */ +function finishLocalAgentShutdown(child: ChildProcessWithoutNullStreams): void { + if (child.pid === undefined || child.exitCode !== null || child.signalCode !== null) return; + const shutdown = new Promise((resolve) => { + const finish = () => { + clearTimeout(timer); + child.off("close", finish); + resolve(); + }; + const timer = setTimeout(() => { + try { + child.kill("SIGKILL"); + } finally { + finish(); + } + }, LOCAL_AGENT_SHUTDOWN_MS); + timer.unref?.(); + child.once("close", finish); + }); + pendingLocalShutdowns.add(shutdown); + void shutdown.then(() => pendingLocalShutdowns.delete(shutdown)); +} + export interface CreateLocalChannelOptions { /** Absolute path to the `agent` binary. Caller resolves dev/prod. */ readonly binaryPath: string; @@ -73,6 +105,7 @@ export function createLocalChannel( cwd: options.cwd, env, }), + disposeChild: finishLocalAgentShutdown, // Local stderr is not classified — the binary writes only human-readable // hints (e.g. usage), and terminal failures surface via exit code below. classifyStderr: () => null, diff --git a/src/main/infra/agent/channel/reconnecting-process-channel.ts b/src/main/infra/agent/channel/reconnecting-process-channel.ts index a29ea1733..8d8ac16a6 100644 --- a/src/main/infra/agent/channel/reconnecting-process-channel.ts +++ b/src/main/infra/agent/channel/reconnecting-process-channel.ts @@ -78,6 +78,8 @@ export interface ChannelCloseContext { export interface ReconnectingProcessChannelOptions { readonly spawn: () => ChildProcessWithoutNullStreams; + /** Starts transport-specific cleanup after stdin has been ended. */ + readonly disposeChild?: (child: ChildProcessWithoutNullStreams) => void; readonly classifyStderr: StderrClassifier; readonly closeError: (wasReady: boolean, context?: ChannelCloseContext) => Error; /** @@ -192,7 +194,10 @@ export function createReconnectingProcessChannel( active?.pipe.dispose(); if (active && !active.child.stdin.destroyed) active.child.stdin.end(); if (!terminalError) emitLifecycle({ type: "disposed" }); - if (active) terminateChild(active); + if (active && !active.closed) { + if (options.disposeChild) options.disposeChild(active.child); + else terminateChild(active); + } }, }; diff --git a/tests/unit/main/agent/reconnect-channel.test.ts b/tests/unit/main/agent/reconnect-channel.test.ts index 8129d42e8..6f8d36d67 100644 --- a/tests/unit/main/agent/reconnect-channel.test.ts +++ b/tests/unit/main/agent/reconnect-channel.test.ts @@ -2,7 +2,10 @@ import { describe, expect, it, jest } from "bun:test"; import type { ChildProcessWithoutNullStreams, SpawnOptionsWithoutStdio } from "node:child_process"; import { EventEmitter } from "node:events"; import type { ChannelLifecycleEvent } from "../../../../src/main/infra/agent/channel/index"; -import { createLocalChannel } from "../../../../src/main/infra/agent/channel/local-channel"; +import { + createLocalChannel, + waitForLocalAgentShutdowns, +} from "../../../../src/main/infra/agent/channel/local-channel"; import { createSshChannel } from "../../../../src/main/infra/agent/ssh/channel"; class FakeStream extends EventEmitter { @@ -34,6 +37,9 @@ class FakeAgentChild extends EventEmitter { readonly stderr = new FakeStream(); readonly stdin = new FakeStdin(); readonly killSignals: string[] = []; + pid: number | undefined; + exitCode = null; + signalCode = null; killed = false; kill(signal?: NodeJS.Signals | number): boolean { @@ -107,6 +113,33 @@ function makeSshHarness( } describe("agent channel reconnect queue", () => { + it("lets a local agent finish its shutdown hooks before forced disposal", async () => { + jest.useFakeTimers(); + try { + const { channel, children } = makeLocalHarness(); + const child = children[0]!; + child.pid = 123; + child.stdout.emitData(`${JSON.stringify({ type: "ready" })}\n`); + await channel.ready; + + channel.dispose(); + expect(child.stdin.ended).toBe(true); + let finished = false; + const shutdown = waitForLocalAgentShutdowns().then(() => { + finished = true; + }); + jest.advanceTimersByTime(3_075); + expect(child.killSignals).toEqual([]); + await flushMicrotasks(); + expect(finished).toBe(false); + jest.advanceTimersByTime(500); + await shutdown; + expect(child.killSignals).toEqual(["SIGKILL"]); + } finally { + jest.useRealTimers(); + } + }); + it("queues local calls during reconnect and flushes them after the new agent is ready", async () => { jest.useFakeTimers(); try { diff --git a/tests/unit/main/lsp/agent-host.test.ts b/tests/unit/main/lsp/agent-host.test.ts index 16cdfd2df..80ad9529d 100644 --- a/tests/unit/main/lsp/agent-host.test.ts +++ b/tests/unit/main/lsp/agent-host.test.ts @@ -49,6 +49,7 @@ class FakeAgentChannel implements AgentChannel { // The id the next lsp.spawn assigns. serverId = "srv-1"; emitConfigurationRequest = false; + shutdownReply?: Promise; constructor( private readonly capabilities: Record = { @@ -63,6 +64,8 @@ class FakeAgentChannel implements AgentChannel { async call(method: string, params?: unknown): Promise { this.calls.push({ method, params }); + if (method === "lsp.shutdown") await this.shutdownReply; + if (method === "lsp.spawn") { // Mirror the real agent: serverAssigned is emitted before any // server-pushed request so the host can resolve serverId context @@ -274,6 +277,33 @@ class SharedAgentChannel implements AgentChannel { } describe("AgentLspHostHandle", () => { + test("keeps host shutdown pending until the agent finishes stopping its server", async () => { + const channel = new FakeAgentChannel(); + let reply!: () => void; + channel.shutdownReply = new Promise((resolve) => { + reply = resolve; + }); + const host = startAgentLspHost({ getAgentChannel: async () => channel }); + await host.call("didOpen", { + workspaceId: WORKSPACE_ID, + workspaceRoot: "/tmp/ws", + uri: URI, + languageId: "python", + version: 1, + text: "print(1)\n", + }); + + let finished = false; + const shutdown = Promise.resolve(host.dispose()).then(() => { + finished = true; + }); + await Promise.resolve(); + expect(channel.calls.at(-1)?.method).toBe("lsp.shutdown"); + expect(finished).toBe(false); + reply(); + await shutdown; + }); + test("spawns through the workspace agent and resolves LSP responses", async () => { const channel = new FakeAgentChannel(); channel.emitConfigurationRequest = true; From ca231a307421db72016cdeeb7a41c5ccf1820f7d Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:44:09 +0900 Subject: [PATCH 028/208] fix(layout): flush pending snapshots before window close Co-Authored-By: Claude Opus 5.5 --- src/main/features/app-state/index.ts | 22 +- src/main/features/app-state/layout-origins.ts | 8 +- src/main/features/window/close-persistence.ts | 114 +++++++++ src/main/features/window/index.ts | 5 + src/main/features/window/ipc.ts | 33 ++- src/main/index.ts | 18 +- src/main/infra/storage/state-service.ts | 11 +- src/renderer/bootstrap.ts | 10 +- src/renderer/index.tsx | 2 + src/renderer/state/operations/browser.ts | 71 +----- src/renderer/state/persistence.ts | 159 ++++++++----- src/renderer/state/stores/tabs.ts | 4 +- src/shared/ipc/contract.ts | 6 + src/shared/util/timing-constants.ts | 12 - .../features/window/close-persistence.test.ts | 99 ++++++++ .../state/stores/tabs/new-tab-types.test.ts | 217 ++++++++++++++++-- 16 files changed, 588 insertions(+), 203 deletions(-) create mode 100644 src/main/features/window/close-persistence.ts create mode 100644 tests/unit/main/features/window/close-persistence.test.ts diff --git a/src/main/features/app-state/index.ts b/src/main/features/app-state/index.ts index 437bce126..690c055ee 100644 --- a/src/main/features/app-state/index.ts +++ b/src/main/features/app-state/index.ts @@ -1,4 +1,5 @@ import { ipcContract } from "../../../shared/ipc/contract"; +import { ipcErr, ipcOk } from "../../../shared/ipc/result"; import type { AppState } from "../../../shared/types/app-state"; import type { WorkspaceMeta } from "../../../shared/types/workspace"; import { register, validateArgs } from "../../infra/ipc-router"; @@ -72,7 +73,25 @@ export function registerAppStateChannel( }, set: (args: unknown) => { const patch = validateArgs(c.set.args, args); - stateService.setState(patch); + if (patch.layoutByWorkspace) { + // A window sends only changed workspaces. Merge into the latest state + // so closing it cannot replace another window's unrelated layouts. + const latest = { + ...stateService.getState().layoutByWorkspace, + ...patch.layoutByWorkspace, + }; + const workspaceIds = opts.listWorkspaces?.().map(({ id }) => id); + patch.layoutByWorkspace = workspaceIds + ? Object.fromEntries( + workspaceIds.flatMap((id) => (latest[id] ? [[id, latest[id]]] : [])), + ) + : latest; + } + try { + stateService.setState(patch); + } catch (error) { + return ipcErr("state-write-failed", String(error), { category: "failed" }); + } // Detect a language change and invoke the injected callback so the // caller can update the main-process i18n instance, rebuild the menu, @@ -106,6 +125,7 @@ export function registerAppStateChannel( if (patch.themePreference !== undefined) { opts.onThemeChanged?.(patch.themePreference); } + return ipcOk(undefined); }, }, listen: {}, diff --git a/src/main/features/app-state/layout-origins.ts b/src/main/features/app-state/layout-origins.ts index 4bc24e280..b28bfbf59 100644 --- a/src/main/features/app-state/layout-origins.ts +++ b/src/main/features/app-state/layout-origins.ts @@ -32,7 +32,7 @@ function restoreTabOrigin(tab: SerializedTab, workspace: WorkspaceMeta): Seriali return { ...tab, props: { ...tab.props, filePath, origin: "external" } }; } -/** Upgrade origin-less records on read, once workspace metadata is available. */ +/** Restore layouts for surviving workspaces and upgrade origin-less records. */ export function restoreLayoutOrigins( state: Readonly, workspaces: WorkspaceMeta[], @@ -42,11 +42,11 @@ export function restoreLayoutOrigins( return { ...state, layoutByWorkspace: Object.fromEntries( - Object.entries(state.layoutByWorkspace).map(([id, snapshot]) => { + Object.entries(state.layoutByWorkspace).flatMap(([id, snapshot]) => { const workspace = byId.get(id); - if (!workspace) return [id, snapshot]; + if (!workspace) return []; const tabs = snapshot.tabs.flatMap((tab) => restoreTabOrigin(tab, workspace) ?? []); - return [id, { ...snapshot, tabs }]; + return [[id, { ...snapshot, tabs }]]; }), ), }; diff --git a/src/main/features/window/close-persistence.ts b/src/main/features/window/close-persistence.ts new file mode 100644 index 000000000..3b21ba8ad --- /dev/null +++ b/src/main/features/window/close-persistence.ts @@ -0,0 +1,114 @@ +import { PendingRequestMap } from "../../../shared/ipc/pending-request-map"; +import type { TimerScheduler } from "../../../shared/util/timer-scheduler"; + +/** How long close waits for a renderer to finish its durable layout write. */ +const CLOSE_FLUSH_TIMEOUT_MS = 1_000; + +interface CloseWindow { + readonly webContents: { + readonly id: number; + send(channel: string, ...args: unknown[]): void; + }; + isDestroyed(): boolean; + close(): void; +} + +interface CloseEvent { + preventDefault(): void; +} + +/** Coordinates a bounded layout flush before Electron runs its unload guards. */ +export class ClosePersistence { + private readonly answers: PendingRequestMap; + private readonly windowFlushes = new Map>(); + private readonly requestedCloses = new Set(); + private replayingClose: CloseWindow | null = null; + private quitPhase: "idle" | "flushing" | "closing" = "idle"; + private nextAttempt = 1; + + constructor( + private readonly warn: (message: string) => void, + scheduler?: TimerScheduler, + ) { + this.answers = new PendingRequestMap(scheduler); + } + + /** Only the window that received this attempt can complete it. */ + acknowledge(senderId: number, attempt: number, saved: boolean): void { + this.answers.resolve(`${senderId}:${attempt}`, saved); + } + + /** Pause an individual close, then replay it through the native unload guard. */ + interceptClose(event: CloseEvent, win: CloseWindow): void { + if (this.replayingClose === win || this.quitPhase === "closing") return; + event.preventDefault(); + if (this.quitPhase === "flushing" || this.requestedCloses.has(win)) return; + + this.requestedCloses.add(win); + void this.flushWindow(win).then(() => { + this.requestedCloses.delete(win); + if (win.isDestroyed() || this.quitPhase !== "idle") return; + this.replayingClose = win; + try { + win.close(); + } finally { + this.replayingClose = null; + } + }); + } + + /** + * A prevented BrowserWindow close also cancels app.quit(). Flush all app + * windows first, then let one normal Electron quit run its close events. + */ + interceptQuit(event: CloseEvent, windows: CloseWindow[], quit: () => void): void { + if (this.quitPhase === "closing" || windows.length === 0) return; + event.preventDefault(); + if (this.quitPhase === "flushing") return; + + this.quitPhase = "flushing"; + void Promise.all(windows.map((win) => this.flushWindow(win))).then(() => { + this.quitPhase = "closing"; + quit(); + }); + } + + /** The native updater owns its window close sequence. */ + allowUpdaterClose(): void { + this.quitPhase = "closing"; + } + + /** A cancelled unload leaves subsequent close attempts eligible to flush again. */ + cancelQuit(): void { + if (this.quitPhase === "closing") this.quitPhase = "idle"; + } + + /** Request at most one flush per window while a close or quit is pending. */ + private flushWindow(win: CloseWindow): Promise { + const senderId = win.webContents.id; + const current = this.windowFlushes.get(senderId); + if (current) return current; + + const attempt = this.nextAttempt++; + const key = `${senderId}:${attempt}`; + const answer = this.answers.register({ key, timeoutMs: CLOSE_FLUSH_TIMEOUT_MS }); + try { + win.webContents.send("ipc:event", "window", "prepareClose", { attempt }); + } catch (error) { + this.answers.reject(key, new Error(String(error))); + } + + const flush = answer + .then( + (saved) => { + if (!saved) this.warn(`Layout save failed before closing window ${senderId}`); + }, + (error: unknown) => { + this.warn(`Layout flush did not complete for window ${senderId}: ${String(error)}`); + }, + ) + .finally(() => this.windowFlushes.delete(senderId)); + this.windowFlushes.set(senderId, flush); + return flush; + } +} diff --git a/src/main/features/window/index.ts b/src/main/features/window/index.ts index 8bab94862..381ea1626 100644 --- a/src/main/features/window/index.ts +++ b/src/main/features/window/index.ts @@ -20,6 +20,7 @@ import { } from "./activation"; import type { AppPage } from "./app-csp"; import { getAppWindows, trackAppWindow } from "./app-windows"; +import { ClosePersistence } from "./close-persistence"; import { opensTransparentOnLinux } from "./linux-transparency"; import { isAllowedMainWindowNavigation } from "./navigation"; import { DEATH_WINDOW_MS, pageDiedQuestion, reloadsPage, watchPageHealth } from "./page-health"; @@ -30,6 +31,8 @@ const TITLEBAR_HEIGHT = 36; const logger = createLogger("window-open-handler"); +export const closePersistence = new ClosePersistence((message) => logger.warn(message)); + // --------------------------------------------------------------------------- // titleBarOverlay color helpers // @@ -230,6 +233,7 @@ export function createMainWindow(appState?: Readonly): BrowserWindow { // The renderer cancels unload (quit, window close, reload) while buffers // are unsaved. Electron cancels silently, so ask here; preventDefault lets // the unload go ahead when the user chooses to discard. + win.on("close", (event) => closePersistence.interceptClose(event, win)); win.webContents.on("will-prevent-unload", (event) => { const t = getMainT(); const choice = dialog.showMessageBoxSync(win, { @@ -241,6 +245,7 @@ export function createMainWindow(appState?: Readonly): BrowserWindow { cancelId: 1, }); if (choice === 0) event.preventDefault(); + else closePersistence.cancelQuit(); }); // Popups need fresh user input, like Chrome's popup blocker: a previewed diff --git a/src/main/features/window/ipc.ts b/src/main/features/window/ipc.ts index c51b77913..e90bf2e4b 100644 --- a/src/main/features/window/ipc.ts +++ b/src/main/features/window/ipc.ts @@ -4,7 +4,9 @@ import { BrowserWindow, Menu, type WebContents } from "electron"; import { ipcContract } from "../../../shared/ipc/contract"; +import { ipcOk } from "../../../shared/ipc/result"; import { type CallContext, register, validateArgs } from "../../infra/ipc-router"; +import type { ClosePersistence } from "./close-persistence"; /** * Builds the handler used by the "Open in new window" action. The callback is @@ -69,20 +71,27 @@ export function windowControlHandlers( * Registers the window channel: controls for a window whose frame draws none, * and the app menu for a window that shows no menu bar. */ -export function registerWindowChannel(): void { +export function registerWindowChannel(closePersistence: ClosePersistence): void { register("window", { - call: windowControlHandlers( - (sender) => BrowserWindow.fromWebContents(sender), - (win, at) => { - // The page's CSS pixels grow with its zoom; the menu takes the window's. - const zoom = win.webContents.getZoomFactor(); - Menu.getApplicationMenu()?.popup({ - window: win, - x: Math.round(at.x * zoom), - y: Math.round(at.y * zoom), - }); + call: { + ...windowControlHandlers( + (sender) => BrowserWindow.fromWebContents(sender), + (win, at) => { + // The page's CSS pixels grow with its zoom; the menu takes the window's. + const zoom = win.webContents.getZoomFactor(); + Menu.getApplicationMenu()?.popup({ + window: win, + x: Math.round(at.x * zoom), + y: Math.round(at.y * zoom), + }); + }, + ), + closePrepared: (args, ctx) => { + const { attempt, saved } = validateArgs(ipcContract.window.call.closePrepared.args, args); + if (ctx?.sender) closePersistence.acknowledge(ctx.sender.id, attempt, saved); + return ipcOk(undefined); }, - ), + }, listen: {}, }); } diff --git a/src/main/index.ts b/src/main/index.ts index 5a67a0334..e2cbf659b 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,5 +1,5 @@ import path from "node:path"; -import { app, type BrowserWindow, powerMonitor, session } from "electron"; +import { app, autoUpdater, type BrowserWindow, powerMonitor, session } from "electron"; import { EMPTY_AGENT_PROFILES } from "../shared/agent-profiles/profiles"; import { DEFAULT_THEME } from "../shared/design-tokens"; import { createLogger, initMainLogger } from "../shared/log/main"; @@ -82,11 +82,17 @@ import { canUpdateInPlace, createElectronUpdateBackend, } from "./features/updates/electron-update-backend"; -import { appPage, createMainWindow, updateTitleBarOverlays } from "./features/window"; +import { + appPage, + closePersistence, + createMainWindow, + updateTitleBarOverlays, +} from "./features/window"; import { installAppCsp } from "./features/window/app-csp"; import { installAppSessionPermissions } from "./features/window/app-session-permissions"; import { getActiveAppWindow, + getAppWindows, getFocusedAppWindow, hasAppWindow, showAppWindow, @@ -429,7 +435,7 @@ registerSystemChannel({ }, }), }); -registerWindowChannel(); +registerWindowChannel(closePersistence); registerClipboardChannel(); registerPreviewChannel(previewDocuments); @@ -857,6 +863,12 @@ app.whenReady().then(async () => { app.on("activate", reopenAppWindow); }); +app.on("before-quit", (event) => { + closePersistence.interceptQuit(event, getAppWindows(), () => app.quit()); +}); +// Native updates close their windows before before-quit and own the replay. +autoUpdater?.on("before-quit-for-update", () => closePersistence.allowUpdaterClose()); + app.on("window-all-closed", () => { // All renderers are gone — no consumer can use browse sessions any more. sshBrowseRegistry.dispose(); diff --git a/src/main/infra/storage/state-service.ts b/src/main/infra/storage/state-service.ts index 3c6ea8837..3a1aaca22 100644 --- a/src/main/infra/storage/state-service.ts +++ b/src/main/infra/storage/state-service.ts @@ -61,9 +61,10 @@ export class StateService { } setState(partial: Partial): void { - AppStateSchema.parse({ ...this.state, ...partial }); - this.state = { ...this.state, ...partial }; - this.flush(); + const next = { ...this.state, ...partial }; + AppStateSchema.parse(next); + this.flush(next); + this.state = next; } mergeState(partial: Partial): void { @@ -82,10 +83,10 @@ export class StateService { this.flush(); } - private flush(): void { + private flush(state = this.state): void { const dir = path.dirname(this.filePath); fs.mkdirSync(dir, { recursive: true }); - const serialized = JSON.stringify(this.state, null, 2); + const serialized = JSON.stringify(state, null, 2); // fsync before the rename so a crash or power loss cannot leave the // renamed file empty. const fd = fs.openSync(this.tmpPath, "w"); diff --git a/src/renderer/bootstrap.ts b/src/renderer/bootstrap.ts index f19309a98..bfe9e4ef4 100644 --- a/src/renderer/bootstrap.ts +++ b/src/renderer/bootstrap.ts @@ -16,10 +16,7 @@ import { markCliUiReady, startCliUiListener } from "./services/cli/ui-requests"; import { startClaudeActiveContextSync } from "./state/claude-active-context-sync"; import { startNoteRemovalListener } from "./state/note-removal"; import { startNotificationClickListener } from "./state/notification-click"; -import { - initBrowserLastUrlPersistence, - initBrowserRuntimeSubscriptions, -} from "./state/operations/browser"; +import { initBrowserRuntimeSubscriptions } from "./state/operations/browser"; import { initBrowserPermissionSubscriptions } from "./state/operations/browser-permission"; import { initBrowserOverlayAutoSuspend } from "./state/operations/browser-suspend-auto"; import { initFocusResync } from "./state/operations/focus-resync"; @@ -124,11 +121,6 @@ export async function bootstrapAppState(): Promise { // error / titleUpdated) so useBrowserRuntimeStore stays up-to-date. initBrowserRuntimeSubscriptions(); - // Wire last-URL persistence: debounces currentUrl changes from the runtime - // store and flushes them to the tabs store so the URL survives app restarts. - // Must be called after initBrowserRuntimeSubscriptions. - initBrowserLastUrlPersistence(); - // Wire the browser permission prompt subscription so browserPermission:prompt // broadcasts from main are forwarded to the PermissionPromptRoot queue. initBrowserPermissionSubscriptions(); diff --git a/src/renderer/index.tsx b/src/renderer/index.tsx index e98f812dd..109e2beaa 100644 --- a/src/renderer/index.tsx +++ b/src/renderer/index.tsx @@ -6,6 +6,7 @@ import { initRendererI18n } from "./i18n"; import { installCspViolationLogger } from "./services/csp-violation-logger"; import { installUnsavedChangesUnloadGuard } from "./services/editor/save/unsaved-guard"; import { installWindowErrorHandlers } from "./services/window-error-handler"; +import { installLayoutClosePersistence } from "./state/persistence"; // Install the unified window 'error' + 'unhandledrejection' safety net before // mounting React. Cancellation rejections are silenced; all other errors are @@ -19,6 +20,7 @@ import { installWindowErrorHandlers } from "./services/window-error-handler"; installWindowErrorHandlers(); installCspViolationLogger(); installUnsavedChangesUnloadGuard(); +installLayoutClosePersistence(); const log = createLogger("renderer-bootstrap"); diff --git a/src/renderer/state/operations/browser.ts b/src/renderer/state/operations/browser.ts index b02afa16d..765698394 100644 --- a/src/renderer/state/operations/browser.ts +++ b/src/renderer/state/operations/browser.ts @@ -25,25 +25,12 @@ * - browser:loadFailureChanged → set or clear the tab's failure * - browser:titleUpdated → setRuntime(tabId, { title }) * - * LAST-URL PERSISTENCE - * -------------------- - * A `useBrowserRuntimeStore` zustand subscription watches `currentUrl` - * changes for every tracked tab. Changes are debounced 250 ms per tab via - * `createKeyedDebouncer`, then dispatched to `setBrowserLastUrl` in the tabs - * store so the URL survives app restarts. - * - * `initBrowserLastUrlPersistence()` must be called after - * `initBrowserRuntimeSubscriptions()` during bootstrap. It is also - * idempotent — a second call tears down the previous subscription. */ import i18next from "i18next"; import { Grid } from "@/engine"; import { loopbackPort } from "../../../shared/pty/ports"; import { isNavigationSchemeAllowed } from "../../../shared/security/navigation-allowlist"; -import { createKeyedDebouncer } from "../../../shared/util/keyed-debouncer"; -import type { TimerScheduler } from "../../../shared/util/timer-scheduler"; -import { BROWSER_LAST_URL_SAVE_DEBOUNCE_MS } from "../../../shared/util/timing-constants"; import { showToast } from "../../components/ui/toast"; import { ipcListen } from "../../ipc/client"; import { useBrowserRuntimeStore } from "../stores/browser-runtime"; @@ -79,6 +66,9 @@ export function initBrowserRuntimeSubscriptions(): void { canGoBack, canGoForward, }); + // Capture the committed URL before layout persistence takes its snapshot. + const workspaceId = findWorkspaceForTab(tabId); + if (workspaceId) useTabsStore.getState().setBrowserLastUrl(workspaceId, tabId, url); }), ); @@ -203,19 +193,9 @@ export function activateGroupForTab(tabId: string): void { useLayoutStore.getState().setActiveGroup(workspaceId, owner.id); } -// --------------------------------------------------------------------------- -// Last-URL persistence — debounced runtime store → tabs store dispatch -// --------------------------------------------------------------------------- - -/** Unsubscribe handle returned by zustand subscribe. */ -let lastUrlPersistUnsub: (() => void) | null = null; - /** * Resolve the workspaceId that owns `tabId` by scanning the tabs store. * Returns `undefined` when no workspace has an entry for `tabId`. - * - * Linear scan is acceptable here: the number of workspaces × tabs is small - * (tens at most) and this path is debounced to at most 4 calls/sec. */ function findWorkspaceForTab(tabId: string): string | undefined { const byWorkspace = useTabsStore.getState().byWorkspace; @@ -225,51 +205,6 @@ function findWorkspaceForTab(tabId: string): string | undefined { return undefined; } -/** - * Install (or reinstall) the runtime store → tabs store last-URL persistence - * subscription. - * - * Accepts an optional `scheduler` so tests can inject a fake timer without - * touching the global clock. - * - * Safe to call multiple times — the previous subscription is torn down first. - */ -export function initBrowserLastUrlPersistence(scheduler?: TimerScheduler): void { - // Tear down any prior subscription. - if (lastUrlPersistUnsub) { - lastUrlPersistUnsub(); - lastUrlPersistUnsub = null; - } - - const debouncer = createKeyedDebouncer({ - delayMs: BROWSER_LAST_URL_SAVE_DEBOUNCE_MS, - ...(scheduler ? { scheduler } : {}), - }); - - // Track the previous snapshot of runtimes so we can detect per-tab URL - // changes without reacting to unrelated fields (isLoading, title, etc.). - let prevRuntimes = useBrowserRuntimeStore.getState().runtimes; - - lastUrlPersistUnsub = useBrowserRuntimeStore.subscribe((state) => { - const nextRuntimes = state.runtimes; - if (nextRuntimes === prevRuntimes) return; - - for (const [tabId, runtime] of nextRuntimes) { - const prev = prevRuntimes.get(tabId); - if (prev?.currentUrl === runtime.currentUrl) continue; - // currentUrl changed for this tab — schedule a debounced persist. - const url = runtime.currentUrl; - debouncer.schedule(tabId, () => { - const workspaceId = findWorkspaceForTab(tabId); - if (!workspaceId) return; - useTabsStore.getState().setBrowserLastUrl(workspaceId, tabId, url); - }); - } - - prevRuntimes = nextRuntimes; - }); -} - // --------------------------------------------------------------------------- // BrowserTabView helper — restore URL on workspace re-entry // --------------------------------------------------------------------------- diff --git a/src/renderer/state/persistence.ts b/src/renderer/state/persistence.ts index 82381364e..a5a6b9b81 100644 --- a/src/renderer/state/persistence.ts +++ b/src/renderer/state/persistence.ts @@ -12,8 +12,9 @@ import { createLogger } from "../../shared/log/renderer"; import type { AppState } from "../../shared/types/app-state"; +import { defaultTimerScheduler, type TimerScheduler } from "../../shared/util/timer-scheduler"; import { STATE_PERSIST_DEBOUNCE_MS } from "../../shared/util/timing-constants"; -import { ipcCallResult } from "../ipc/client"; +import { ipcCallResult, ipcListen } from "../ipc/client"; import { normalizeWorkspaceTabOrder } from "./operations/tab-order"; import { useLayoutStore } from "./stores/layout"; import { restoredTitles, useTabsStore } from "./stores/tabs"; @@ -87,75 +88,107 @@ export function hydrateLayoutSnapshots(snapshots: AppState["layoutByWorkspace"]) } } -// --------------------------------------------------------------------------- -// Debounce helper -// --------------------------------------------------------------------------- - -function debounce(fn: () => void, ms: number): () => void { - let timer: ReturnType | null = null; - return () => { - if (timer !== null) clearTimeout(timer); - timer = setTimeout(() => { - timer = null; - fn(); - }, ms); - }; -} - -// --------------------------------------------------------------------------- -// Registration -// --------------------------------------------------------------------------- - -let unsubLayout: (() => void) | null = null; -let unsubTabs: (() => void) | null = null; - -export function registerStatePersistence(): void { - // Only register once - if (unsubLayout !== null) return; +let persistence: { flush(): Promise; stop(): void } | undefined; + +/** Watch changed workspace slices and coalesce their durable writes. */ +export function registerStatePersistence(scheduler: TimerScheduler = defaultTimerScheduler): void { + if (persistence) return; + const pending = new Set(); + let timer: unknown; + let stopped = false; + let inFlight: Promise | undefined; + + /** Cancel the scheduled write so an explicit flush can take its place. */ + function cancelTimer(): void { + if (timer === undefined) return; + scheduler.clearTimeout(timer); + timer = undefined; + } - const flush = debounce(() => { - const workspaceIds = Object.keys(useLayoutStore.getState().byWorkspace); + /** Send one batch of current snapshots and retain failed changes for the next flush. */ + async function write(): Promise { + const workspaceIds = [...pending]; + pending.clear(); const layoutByWorkspace: NonNullable = {}; - - for (const wsId of workspaceIds) { - const snap = toSnapshot(wsId); - if (snap) { - layoutByWorkspace[wsId] = snap; - } + for (const id of workspaceIds) { + const snapshot = toSnapshot(id); + if (snapshot) layoutByWorkspace[id] = snapshot; + } + if (Object.keys(layoutByWorkspace).length === 0) return true; + + try { + const result = await ipcCallResult("appState", "set", { layoutByWorkspace }); + if (result.ok) return true; + log.warn(`Layout save failed: ${result.message}`); + } catch (error) { + log.warn(`Layout save failed: ${String(error)}`); } + if (!stopped) for (const id of workspaceIds) pending.add(id); + return false; + } - // Fire-and-forget: layout persistence is best-effort; local state is source of truth. - void ipcCallResult("appState", "set", { layoutByWorkspace }).then((result) => { - if (!result.ok) log.warn(`appState set failed: ${result.message}`); - }); - }, STATE_PERSIST_DEBOUNCE_MS); - - // Slice-scoped subscriptions: only re-flush when `byWorkspace` (the - // serialised slice) actually changes reference. The bare `subscribe(fn)` - // form fires for every store mutation — including non-persisted slots - // a future store might add — and the resulting unconditional flush - // would be wasted work even with the 250ms debounce. Implemented as - // manual diffing so we don't have to drag in `subscribeWithSelector` - // middleware for two callers. - let prevLayout = useLayoutStore.getState().byWorkspace; - let prevTabs = useTabsStore.getState().byWorkspace; - unsubLayout = useLayoutStore.subscribe((state) => { - if (state.byWorkspace !== prevLayout) { - prevLayout = state.byWorkspace; - flush(); + /** Wait for the current write and any changes queued behind it. */ + async function flush(): Promise { + cancelTimer(); + while (!stopped && (inFlight || pending.size > 0)) { + inFlight ??= write().finally(() => { + inFlight = undefined; + }); + if (!(await inFlight)) return false; + cancelTimer(); } - }); - unsubTabs = useTabsStore.subscribe((state) => { - if (state.byWorkspace !== prevTabs) { - prevTabs = state.byWorkspace; - flush(); + return true; + } + + /** Record only the slices changed by this window since hydration. */ + function recordChanges(next: Record, previous: Record): void { + if (next === previous) return; + const ids = new Set([...Object.keys(next), ...Object.keys(previous)]); + for (const id of ids) { + if (next[id] !== previous[id]) pending.add(id); } - }); + if (pending.size === 0) return; + + cancelTimer(); + timer = scheduler.setTimeout(() => { + timer = undefined; + void flush(); + }, STATE_PERSIST_DEBOUNCE_MS); + } + + const unsubLayout = useLayoutStore.subscribe((state, previous) => + recordChanges(state.byWorkspace, previous.byWorkspace), + ); + const unsubTabs = useTabsStore.subscribe((state, previous) => + recordChanges(state.byWorkspace, previous.byWorkspace), + ); + persistence = { + flush, + stop() { + stopped = true; + cancelTimer(); + unsubLayout(); + unsubTabs(); + pending.clear(); + }, + }; } +/** Unsubscribe and discard a scheduled write during teardown. */ export function unregisterStatePersistence(): void { - unsubLayout?.(); - unsubTabs?.(); - unsubLayout = null; - unsubTabs = null; + persistence?.stop(); + persistence = undefined; +} + +/** Acknowledge a close attempt only after the latest dirty layouts were written. */ +export function installLayoutClosePersistence(): () => void { + return ipcListen("window", "prepareClose", ({ attempt }) => { + void (async () => { + const saved = (await persistence?.flush()) ?? true; + const result = await ipcCallResult("window", "closePrepared", { attempt, saved }); + if (!result.ok) log.warn(`Could not acknowledge layout flush: ${result.message}`); + })().catch((error: unknown) => { + log.warn(`Could not complete layout flush: ${String(error)}`); + }); + }); } diff --git a/src/renderer/state/stores/tabs.ts b/src/renderer/state/stores/tabs.ts index bb37179aa..b2f7765db 100644 --- a/src/renderer/state/stores/tabs.ts +++ b/src/renderer/state/stores/tabs.ts @@ -820,7 +820,9 @@ export const useTabsStore = create((set, get) => { setBrowserLastUrl(workspaceId, tabId, lastUrl) { set((state) => withTab(state, workspaceId, tabId, (tab) => - tab.type === "browser" ? { ...tab, props: { ...tab.props, lastUrl } } : tab, + tab.type === "browser" && tab.props.lastUrl !== lastUrl + ? { ...tab, props: { ...tab.props, lastUrl } } + : tab, ), ); }, diff --git a/src/shared/ipc/contract.ts b/src/shared/ipc/contract.ts index 0b6c4107d..c73a43985 100644 --- a/src/shared/ipc/contract.ts +++ b/src/shared/ipc/contract.ts @@ -1702,6 +1702,10 @@ export const ipcContract = { minimize: call(z.void(), z.void()), toggleMaximize: call(z.void(), z.void()), close: call(z.void(), z.void()), + closePrepared: call( + z.object({ attempt: z.number().int().positive(), saved: z.boolean() }), + z.void(), + ), isMaximized: call(z.void(), z.boolean()), /** * Opens the app menu at a point of the page, in its CSS pixels. Windows @@ -1713,6 +1717,8 @@ export const ipcContract = { listen: { /** Sent to one window only, when it is maximized or restored. */ maximizedChanged: listen(z.object({ maximized: z.boolean() })), + /** Sent to the window whose latest layout must be written before closing. */ + prepareClose: listen(z.object({ attempt: z.number().int().positive() })), }, }, diff --git a/src/shared/util/timing-constants.ts b/src/shared/util/timing-constants.ts index f6aa95a79..eb2b27f24 100644 --- a/src/shared/util/timing-constants.ts +++ b/src/shared/util/timing-constants.ts @@ -205,15 +205,3 @@ export const GIT_COMMIT_DRAFT_SAVE_DEBOUNCE_MS = 500; * window collapses save-cascades into one call. */ export const GIT_STATUS_HINT_DEBOUNCE_MS = 150; - -// --------------------------------------------------------------------------- -// Browser tabs -// --------------------------------------------------------------------------- - -/** - * Trailing-edge debounce window for persisting a browser tab's `lastUrl`. - * URL changes can arrive in rapid succession during page redirects and - * client-side navigation; this window coalesces them into a single store - * write per tab so persistence isn't hammered on every navigation step. - */ -export const BROWSER_LAST_URL_SAVE_DEBOUNCE_MS = 250; diff --git a/tests/unit/main/features/window/close-persistence.test.ts b/tests/unit/main/features/window/close-persistence.test.ts new file mode 100644 index 000000000..1116cc157 --- /dev/null +++ b/tests/unit/main/features/window/close-persistence.test.ts @@ -0,0 +1,99 @@ +import { expect, mock, test } from "bun:test"; +import { ClosePersistence } from "../../../../../src/main/features/window/close-persistence"; +import type { TimerScheduler } from "../../../../../src/shared/util/timer-scheduler"; + +/** Drives main's bounded waits without advancing real time. */ +function fakeTimer(): TimerScheduler & { expire(): void } { + const timers = new Set<() => void>(); + return { + setTimeout(callback) { + timers.add(callback); + return callback; + }, + clearTimeout(handle) { + timers.delete(handle as () => void); + }, + expire() { + const pending = [...timers]; + timers.clear(); + for (const callback of pending) callback(); + }, + }; +} + +/** A window with a separate renderer and native close entry point. */ +function fakeWindow(id: number, onClose: () => void = () => {}) { + const attempts: number[] = []; + return { + attempts, + webContents: { + id, + send(_wire: string, _channel: string, _event: string, args: unknown) { + attempts.push((args as { attempt: number }).attempt); + }, + }, + isDestroyed: () => false, + close: mock(onClose), + }; +} + +test("quit waits per window, bounds an absent reply, and flushes anew after unload is cancelled", async () => { + const timer = fakeTimer(); + const warn = mock((_message: string) => {}); + const persistence = new ClosePersistence(warn, timer); + const first = fakeWindow(1); + const second = fakeWindow(2); + const windows = [first, second]; + const event = { preventDefault: mock(() => {}) }; + const replayed = Promise.withResolvers(); + const replay = mock(() => { + const nativeQuit = { preventDefault: mock(() => {}) }; + persistence.interceptQuit(nativeQuit, windows, replay); + expect(nativeQuit.preventDefault).not.toHaveBeenCalled(); + persistence.interceptClose(nativeQuit, first); + expect(nativeQuit.preventDefault).not.toHaveBeenCalled(); + replayed.resolve(); + }); + + persistence.interceptQuit(event, windows, replay); + expect(event.preventDefault).toHaveBeenCalledTimes(1); + persistence.acknowledge(1, first.attempts[0], true); + // The first window cannot acknowledge the second one's attempt. + persistence.acknowledge(1, second.attempts[0], true); + expect(replay).not.toHaveBeenCalled(); + timer.expire(); + await replayed.promise; + expect(warn).toHaveBeenCalledTimes(1); + + // The main window's unsaved-buffers dialog returns Cancel. + persistence.cancelQuit(); + const retry = Promise.withResolvers(); + persistence.interceptQuit(event, windows, retry.resolve); + expect(first.attempts).toHaveLength(2); + expect(second.attempts).toHaveLength(2); + persistence.acknowledge(1, first.attempts[1], true); + persistence.acknowledge(2, second.attempts[1], true); + await retry.promise; + expect(warn).toHaveBeenCalledTimes(1); +}); + +test("a failed layout write still resumes one window close through its native guard", async () => { + const warn = mock((_message: string) => {}); + const persistence = new ClosePersistence(warn, fakeTimer()); + const replayed = Promise.withResolvers(); + const replay = { preventDefault: mock(() => {}) }; + const win = fakeWindow(1, () => { + persistence.interceptClose(replay, win); + replayed.resolve(); + }); + const event = { preventDefault: mock(() => {}) }; + + persistence.interceptClose(event, win); + persistence.interceptClose(event, win); + expect(win.attempts).toHaveLength(1); + persistence.acknowledge(1, win.attempts[0], false); + await replayed.promise; + expect(win.close).toHaveBeenCalledTimes(1); + expect(replay.preventDefault).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledTimes(1); +}); diff --git a/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts b/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts index 834579002..a1bb19fec 100644 --- a/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts +++ b/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts @@ -1,12 +1,14 @@ -import { afterEach, beforeAll, expect, mock, test } from "bun:test"; +import { afterEach, beforeAll, beforeEach, expect, mock, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { registerAppStateChannel } from "../../../../../../src/main/features/app-state"; +import { ClosePersistence } from "../../../../../../src/main/features/window/close-persistence"; import { setupRouter } from "../../../../../../src/main/infra/ipc-router"; import { StateService } from "../../../../../../src/main/infra/storage/state-service"; import type { WorkspaceLayoutSnapshot } from "../../../../../../src/shared/types/layout"; import type { WorkspaceMeta } from "../../../../../../src/shared/types/workspace"; +import type { TimerScheduler } from "../../../../../../src/shared/util/timer-scheduler"; type Invoke = ( event: { sender?: { id: number } }, @@ -26,11 +28,19 @@ mock.module("electron", () => ({ })); const originalWindow = globalThis.window; -let write: ReturnType>; -let schedule: (() => void) | undefined; +let listeners = new Map void>(); +const { registerWindowChannel } = await import("../../../../../../src/main/features/window/ipc"); +const { initBrowserRuntimeSubscriptions } = await import( + "../../../../../../src/renderer/state/operations/browser" +); +const { closeTab } = await import("../../../../../../src/renderer/state/operations/tabs"); -const { hydrateLayoutSnapshots, registerStatePersistence, unregisterStatePersistence } = - await import("../../../../../../src/renderer/state/persistence"); +const { + hydrateLayoutSnapshots, + installLayoutClosePersistence, + registerStatePersistence, + unregisterStatePersistence, +} = await import("../../../../../../src/renderer/state/persistence"); const { useLayoutStore } = await import("../../../../../../src/renderer/state/stores/layout"); const { useTabsStore } = await import("../../../../../../src/renderer/state/stores/tabs"); const { ipcCallResult, mustSucceed } = await import("../../../../../../src/renderer/ipc/client"); @@ -49,20 +59,35 @@ const workspace: WorkspaceMeta = { }; /** Pass renderer calls through the real router, using an in-process transport. */ -function connectRenderer(): void { +function connectRenderer({ + beforeSave, + onSave, +}: { + beforeSave?: () => Promise; + onSave?: (result: unknown) => void; +} = {}): void { + listeners = new Map(); Object.assign(globalThis, { window: { ipc: { call: async (channel: string, method: string, args: unknown) => { + const isSave = channel === "appState" && method === "set"; + if (isSave) await beforeSave?.(); const result = await invoke( { sender: { id: 1 } }, channel, method, structuredClone(args), ); - if (channel === "appState" && method === "set") write.resolve(result); + if (isSave) onSave?.(result); return structuredClone(result); }, + listen: (channel: string, event: string, listener: (args: unknown) => void) => { + const subscribed = listeners; + const key = `${channel}.${event}`; + subscribed.set(key, listener); + return () => subscribed.delete(key); + }, }, }, }); @@ -94,7 +119,25 @@ function addTab(args: Parameters["creat return tab.id; } +/** Advances persistence time under test control. */ +function fakeTimer(): TimerScheduler & { run(): void } { + let scheduled: (() => void) | undefined; + return { + setTimeout(callback) { + scheduled = callback; + return callback; + }, + clearTimeout(handle) { + if (scheduled === handle) scheduled = undefined; + }, + run() { + scheduled?.(); + }, + }; +} + beforeAll(setupRouter); +beforeEach(resetStores); afterEach(() => { unregisterStatePersistence(); resetStores(); @@ -104,23 +147,13 @@ afterEach(() => { test("restores external and workspace files beside a browser while excluding Untitled", async () => { const dir = mkdtempSync(join(tmpdir(), "nx-layout-roundtrip-")); const stateFile = join(dir, "app-state.json"); - write = Promise.withResolvers(); - connectRenderer(); + const write = Promise.withResolvers(); + connectRenderer({ onSave: write.resolve }); registerAppStateChannel(new StateService(stateFile), { listWorkspaces: () => [workspace] }); - const timer = globalThis.setTimeout; - const cancel = globalThis.clearTimeout; + const timer = fakeTimer(); try { - // Control the real renderer persistence subscriber's debounce without sleeping. - globalThis.setTimeout = ((callback: () => void) => { - schedule = callback; - return 1; - }) as typeof setTimeout; - globalThis.clearTimeout = (() => { - schedule = undefined; - }) as typeof clearTimeout; - - registerStatePersistence(); + registerStatePersistence(timer); const external = addTab({ type: "editor", props: { workspaceId, filePath: "/outside/file.txt", origin: "external", readOnly: true }, @@ -138,11 +171,12 @@ test("restores external and workspace files beside a browser while excluding Unt }, }); const untitled = addTab({ type: "untitled", props: { untitledIndex: 1 } }); - schedule?.(); + timer.run(); await write.promise; unregisterStatePersistence(); const reloaded = new StateService(stateFile); - expect(reloaded.getState().layoutByWorkspace?.[workspaceId]?.tabs[0]).toMatchObject({ + const savedTabs = reloaded.getState().layoutByWorkspace?.[workspaceId]?.tabs; + expect(savedTabs?.find((tab) => tab.id === external)).toMatchObject({ props: { origin: "external" }, }); registerAppStateChannel(reloaded, { listWorkspaces: () => [workspace] }); @@ -160,8 +194,6 @@ test("restores external and workspace files beside a browser while excluding Unt tabIds: [external, internal, browser], }); } finally { - globalThis.setTimeout = timer; - globalThis.clearTimeout = cancel; rmSync(dir, { recursive: true, force: true }); } }); @@ -214,3 +246,138 @@ test("recovers only unambiguous legacy local external paths and repairs dropped rmSync(dir, { recursive: true, force: true }); } }); + +test("does not hydrate tabs or layout for a workspace deleted since the last save", async () => { + const dir = mkdtempSync(join(tmpdir(), "nx-layout-deleted-")); + connectRenderer(); + const removed = crypto.randomUUID(); + try { + const state = new StateService(join(dir, "app-state.json")); + state.setState({ + layoutByWorkspace: { + [workspaceId]: legacySnapshot(workspaceId), + [removed]: legacySnapshot(removed), + }, + }); + registerAppStateChannel(state, { listWorkspaces: () => [workspace] }); + await restore(); + + expect(useTabsStore.getState().byWorkspace[removed]).toBeUndefined(); + expect(useLayoutStore.getState().byWorkspace[removed]).toBeUndefined(); + expect(useLayoutStore.getState().byWorkspace[workspaceId]).toBeDefined(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("closing flushes queued tab, split and browser URL changes after an older save without replacing another window's layout", async () => { + const dir = mkdtempSync(join(tmpdir(), "nx-layout-close-")); + const stateFile = join(dir, "app-state.json"); + const inFlight = Promise.withResolvers(); + const finishWrite = Promise.withResolvers(); + const closed = Promise.withResolvers(); + const warnings: string[] = []; + const timer = fakeTimer(); + const otherWorkspace = { ...workspace, id: crypto.randomUUID() }; + const otherSnapshot = legacySnapshot(otherWorkspace.id); + let saves = 0; + connectRenderer({ + beforeSave() { + if (++saves !== 1) return Promise.resolve(); + inFlight.resolve(); + return finishWrite.promise; + }, + }); + const state = new StateService(stateFile); + state.setState({ layoutByWorkspace: { [otherWorkspace.id]: otherSnapshot } }); + registerAppStateChannel(state, { listWorkspaces: () => [workspace, otherWorkspace] }); + const close = new ClosePersistence((warning) => warnings.push(warning), fakeTimer()); + registerWindowChannel(close); + const stopListening = installLayoutClosePersistence(); + initBrowserRuntimeSubscriptions(); + + try { + await restore(); + registerStatePersistence(timer); + const editor = addTab({ type: "editor", props: { workspaceId, filePath: "/repo/closed.txt" } }); + const browser = addTab({ + type: "browser", + props: { initialUrl: "https://example.com", lastUrl: "https://example.com", partition: "p" }, + }); + timer.run(); + await inFlight.promise; + + closeTab(workspaceId, editor); + const layout = useLayoutStore.getState().byWorkspace[workspaceId]; + const secondGroup = useLayoutStore + .getState() + .splitGroup(workspaceId, layout.activeGroupId, "horizontal", "after"); + useLayoutStore.getState().attachTab( + workspaceId, + secondGroup, + useTabsStore.getState().createTab(workspaceId, { + type: "editor", + props: { workspaceId, filePath: "/repo/other.txt" }, + }).id, + ); + const url = "https://example.com/latest"; + listeners.get("browser.navigated")?.({ + tabId: browser, + url, + canGoBack: true, + canGoForward: false, + }); + + const otherWindowSave = { + ...otherSnapshot, + tabs: otherSnapshot.tabs.slice(0, 1).map((tab) => ({ ...tab, title: "new title" })), + }; + await invoke({ sender: { id: 2 } }, "appState", "set", { + layoutByWorkspace: { [otherWorkspace.id]: otherWindowSave }, + }); + + const win = { + webContents: { + id: 1, + send(_wire: string, channel: string, event: string, args: unknown) { + listeners.get(`${channel}.${event}`)?.(args); + }, + }, + isDestroyed: () => false, + close: mock(() => closed.resolve()), + }; + close.interceptClose({ preventDefault() {} }, win); + expect(win.close).not.toHaveBeenCalled(); + finishWrite.resolve(); + await closed.promise; + expect(saves).toBe(2); + expect(warnings).toEqual([]); + + unregisterStatePersistence(); + registerAppStateChannel(new StateService(stateFile), { + listWorkspaces: () => [workspace, otherWorkspace], + }); + await restore(); + const tabs = useTabsStore.getState().byWorkspace; + expect(tabs[workspaceId][editor]).toBeUndefined(); + expect(tabs[workspaceId][browser]).toMatchObject({ props: { lastUrl: url } }); + expect(useLayoutStore.getState().byWorkspace[workspaceId].root.kind).toBe("split"); + expect(tabs[otherWorkspace.id][otherWindowSave.tabs[0].id].title).toBe("new title"); + } finally { + finishWrite.resolve(); + stopListening(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("unregistering layout persistence cancels a scheduled write", () => { + const timer = fakeTimer(); + const beforeSave = mock(() => Promise.resolve()); + connectRenderer({ beforeSave }); + registerStatePersistence(timer); + addTab({ type: "editor", props: { workspaceId, filePath: "/repo/never-saved.txt" } }); + + unregisterStatePersistence(); + timer.run(); + expect(beforeSave).not.toHaveBeenCalled(); +}); From 7f7c525195b1921a48b5fab4c348ee54c52f1a34 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:46:18 +0900 Subject: [PATCH 029/208] fix(remote): keep relay reconnect attempts under one owner Co-Authored-By: Claude Opus 5.5 --- src/main/features/remote/account.ts | 21 +- src/main/features/remote/index.ts | 19 +- src/main/features/remote/relay-connection.ts | 98 ++++-- src/main/features/remote/route.ts | 52 ++-- src/main/features/remote/ticket.ts | 12 +- .../unit/main/features/remote/account.test.ts | 50 +++ .../features/remote/relay-connection.test.ts | 293 +++++++++++++++--- tests/unit/main/features/remote/route.test.ts | 72 ++++- 8 files changed, 517 insertions(+), 100 deletions(-) diff --git a/src/main/features/remote/account.ts b/src/main/features/remote/account.ts index bd8a5f97e..f538a1570 100644 --- a/src/main/features/remote/account.ts +++ b/src/main/features/remote/account.ts @@ -245,17 +245,20 @@ export class RemoteAccount { /** * Asks the server as this device: the JSON it answered, or a ServerError; * a 401 signs the app out and throws SignedOutError. `headers` adds to the - * request's own (the account password's proof, say). + * request's own (the account password's proof, say). An aborted request + * cannot update the route or sign the account out. */ request( method: string, path: string, body?: unknown, headers?: Record, + signal?: AbortSignal, ): Promise { return this.call(method, path, { ...(body !== undefined ? { body } : {}), ...(headers ? { headers } : {}), + signal, }); } @@ -284,8 +287,11 @@ export class RemoteAccount { headers?: Record; signedIn?: boolean; timeoutMs?: number; + signal?: AbortSignal; } = {}, ): Promise { + const { signal } = options; + signal?.throwIfAborted(); const headers: Record = { ...options.raw?.headers, ...options.headers }; if (options.signedIn !== false) { if (!this.saved) throw new SignedOutError(); @@ -298,18 +304,21 @@ export class RemoteAccount { : options.body !== undefined ? JSON.stringify(options.body) : undefined; - const send = (base: string) => - this.fetch(this.route.url(path, { base }), { + const send = (base: string) => { + const timeout = AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS); + return this.fetch(this.route.url(path, { base }), { method, headers, - signal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS), + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, ...(body !== undefined ? { body: body as NonNullable } : {}), }); + }; const base = this.route.base(); let res: Response; try { res = await send(base); } catch (error) { + signal?.throwIfAborted(); // fetch fails with a TypeError when the server cannot be reached, a TimeoutError when it // is slow. The proxy not reached, the server is asked straight, now and for a while; a // request that timed out may have gone through, and is not sent again. @@ -317,14 +326,18 @@ export class RemoteAccount { try { res = await send(this.route.base()); } catch (again) { + signal?.throwIfAborted(); throw new UnreachableError(again); } } + // A stale relay ticket can no longer change the account or its route. + signal?.throwIfAborted(); if (res.status === 401 && options.signedIn !== false) { this.forget(); throw new SignedOutError(); } const text = await res.text(); + signal?.throwIfAborted(); const answer = parseJson(text); if (!res.ok) { const code = isRecord(answer) && typeof answer.error === "string" ? answer.error : undefined; diff --git a/src/main/features/remote/index.ts b/src/main/features/remote/index.ts index 181f34e00..d33eb1e68 100644 --- a/src/main/features/remote/index.ts +++ b/src/main/features/remote/index.ts @@ -201,6 +201,7 @@ export async function registerRemoteChannel(options: { ); // In the account's room while signed in with the account key; out of it otherwise. let room: RemoteRoom | null = null; + let disposed = false; let roomFor = ""; let roomState: RoomState = { status: "off", peers: [] }; /** The room, to ask another device through; Unavailable while out of it. */ @@ -316,22 +317,23 @@ export async function registerRemoteChannel(options: { }); const sessionOf = (id: string) => (noteVoice.has(id) ? noteVoice : voice); - const relayUrl = async () => { - const ticket = await askTicket(account); + /** Gets a ticket for the current attempt and builds its WebSocket URL. */ + const relayUrl = async (signal: AbortSignal) => { + const ticket = await askTicket(account, undefined, signal); + signal.throwIfAborted(); const url = account.route.url("/relay", { socket: true }); url.search = new URLSearchParams({ v: String(RELAY_VERSION), ticket }).toString(); - relayVia = url.origin; return url.toString(); }; - /** Where the relay's socket went, and the socket: one that went straight goes back through the proxy. */ - let relayVia: string | null = null; let relay: RelayConnection | null = null; - returnToProxy({ + const proxyProbe = returnToProxy({ route: account.route, - via: () => (roomState.status === "online" ? relayVia : null), + via: () => relay?.onlineRoute() ?? null, reconnect: () => relay?.reconnect(), }); + /** Keeps the relay in the room for the signed-in account and current key. */ function syncRoom(): void { + if (disposed) return; const signedIn = account.state(); const key = keys?.key() ?? null; const want = signedIn.status === "signed-in" && key ? { signedIn, key } : null; @@ -341,6 +343,7 @@ export async function registerRemoteChannel(options: { if (room && id !== roomFor) { room.stop(); room = null; + relay = null; setRoomState({ status: "off", peers: [] }); } if (room || !want) return; @@ -971,6 +974,8 @@ export async function registerRemoteChannel(options: { inRoom().request(deviceId, method, params, timeoutMs, signal), }, dispose: () => { + disposed = true; + proxyProbe.stop(); account.cancelSignIn(); voice.cancel(); noteVoice.cancel(); diff --git a/src/main/features/remote/relay-connection.ts b/src/main/features/remote/relay-connection.ts index 65aa11fc1..34f74e33f 100644 --- a/src/main/features/remote/relay-connection.ts +++ b/src/main/features/remote/relay-connection.ts @@ -68,8 +68,9 @@ export interface RelayConnectionDeps { /** * The socket's address, with a fresh ticket: ws(s)://server/relay?v=2&ticket=... * SignedOutError and OutdatedError give up; any other failure tries again. + * The signal is aborted if this attempt is replaced or stopped. */ - url(): Promise; + url(signal: AbortSignal): Promise; onOpen(): void; onFrame(frame: ServerFrame): void; onStatus(status: RelayStatus): void; @@ -85,14 +86,23 @@ export interface RelayConnectionDeps { heartbeat?: { every: number; wait: number }; } +/** A socket and the origin it reached, stable for the life of this connection. */ +interface ActiveSocket { + readonly socket: Socket; + readonly origin: string; +} + /** 1 s doubling to 30 s, give or take a fifth, so devices do not come back all at once. */ export function defaultBackoff(attempt: number): number { const base = Math.min(30_000, 1000 * 2 ** attempt); return Math.round(base * (0.8 + Math.random() * 0.4)); } +/** Owns the current relay attempt from ticket acquisition through socket close. */ export class RelayConnection { - private socket: Socket | null = null; + private connection: ActiveSocket | null = null; + /** The controller identifies the current attempt even before a socket exists. */ + private owner: AbortController | null = null; private timer: ReturnType | null = null; private attempt = 0; private running = false; @@ -130,15 +140,22 @@ export class RelayConnection { /** Sends a frame while online; false when it cannot go (offline, or too big). */ send(frame: ClientFrame): boolean { - if (this.status !== "online" || !this.socket) return false; + const socket = this.connection?.socket; + if (this.status !== "online" || !socket) return false; const text = JSON.stringify(frame); if (Buffer.byteLength(text, "utf8") > MAX_FRAME_BYTES) return false; - this.socket.send(text); + socket.send(text); return true; } get bufferedAmount(): number { - return this.socket?.bufferedAmount ?? 0; + return this.connection?.socket.bufferedAmount ?? 0; + } + + /** The route of the actual open socket, with identity stable across probes. */ + onlineRoute(): { readonly origin: string } | null { + const connection = this.connection; + return this.status === "online" && connection?.socket.readyState === 1 ? connection : null; } /** The room answered: the connection is good, and the next loss starts the backoff over. */ @@ -146,32 +163,49 @@ export class RelayConnection { this.attempt = 0; } + /** Gets a ticket and opens a socket only while this attempt owns the relay. */ private async connect(): Promise { + if (!this.running) return; + const owner = new AbortController(); + this.owner = owner; this.set("connecting"); + if (!this.owns(owner)) return; + let url: string; + let connection: ActiveSocket; try { - url = await this.deps.url(); + url = await this.deps.url(owner.signal); + if (!this.owns(owner)) return; + const origin = new URL(url).origin; + const socket = (this.deps.socket ?? ((address) => new WebSocket(address) as Socket))(url); + if (!this.owns(owner)) { + if (socket.readyState <= 1) socket.close(1000, "bye"); + return; + } + connection = { origin, socket }; } catch (error) { + if (!this.owns(owner)) return; if (error instanceof SignedOutError) { this.giveUp("stopped"); this.deps.onSignedOut(); } else if (error instanceof OutdatedError) this.giveUp("outdated"); - else this.retry(); + else this.retry(owner); return; } - if (!this.running) return; - const socket = (this.deps.socket ?? ((u) => new WebSocket(u) as Socket))(url); - this.socket = socket; + + const { socket } = connection; + this.connection = connection; let opened = false; socket.addEventListener("open", () => { - if (this.socket !== socket) return; + if (this.connection !== connection) return; opened = true; this.set("online"); - this.startHeartbeat(socket); + if (this.connection !== connection) return; + this.startHeartbeat(connection, owner); this.deps.onOpen(); }); socket.addEventListener("message", (event: { data: unknown }) => { - if (this.socket !== socket) return; + if (this.connection !== connection) return; // Anything from the relay answers the heartbeat. this.clearPongTimer(); if (typeof event.data !== "string" || event.data === RELAY_PONG) return; @@ -185,8 +219,8 @@ export class RelayConnection { if (parsed.success) this.deps.onFrame(parsed.data); }); socket.addEventListener("close", (event: { code: number }) => { - if (this.socket !== socket) return; - this.socket = null; + if (this.connection !== connection) return; + this.connection = null; this.stopHeartbeat(); if (event.code === CLOSE_REPLACED) this.giveUp("replaced"); else if (event.code === CLOSE_SIGNED_OUT) { @@ -196,7 +230,7 @@ export class RelayConnection { void this.connect(); } else { if (!opened) this.deps.unreachable?.(url); - this.retry(); + this.retry(owner); } }); // An error is followed by a close, which decides what comes next. @@ -208,14 +242,15 @@ export class RelayConnection { * not answered in time lets the socket go and joins the room again, as a * socket that closed does. Its own close may come long after, or never. */ - private startHeartbeat(socket: Socket): void { + private startHeartbeat(connection: ActiveSocket, owner: AbortController): void { + const { socket } = connection; this.stopHeartbeat(); const { every, wait } = this.deps.heartbeat ?? { every: HEARTBEAT_EVERY_MS, wait: PONG_WAIT_MS, }; this.beat = setInterval(() => { - if (this.socket !== socket || this.pongTimer) return; + if (this.connection !== connection || this.pongTimer) return; try { socket.send(RELAY_PING); } catch { @@ -223,8 +258,8 @@ export class RelayConnection { } this.pongTimer = setTimeout(() => { this.pongTimer = null; - if (this.socket !== socket) return; - this.socket = null; + if (this.connection !== connection) return; + this.connection = null; this.stopHeartbeat(); try { socket.close(); @@ -232,7 +267,7 @@ export class RelayConnection { // Closing already. } if (this.quickRetry()) void this.connect(); - else this.retry(); + else this.retry(owner); }, wait); }, every); } @@ -257,15 +292,17 @@ export class RelayConnection { return true; } - private retry(): void { - if (!this.running) return; + /** Schedules backoff only for the attempt that reported the loss. */ + private retry(owner: AbortController): void { + if (!this.owns(owner)) return; this.set("waiting"); + if (!this.owns(owner)) return; const delay = (this.deps.backoff ?? defaultBackoff)(this.attempt); this.attempt += 1; this.clearTimer(); this.timer = setTimeout(() => { this.timer = null; - if (this.running) void this.connect(); + if (this.owns(owner)) void this.connect(); }, delay); } @@ -276,13 +313,22 @@ export class RelayConnection { this.set(status); } + /** Invalidates the attempt and detaches its socket before closing it. */ private drop(): void { - const socket = this.socket; - this.socket = null; + const owner = this.owner; + const socket = this.connection?.socket; + this.owner = null; + this.connection = null; this.stopHeartbeat(); + owner?.abort(); if (socket && socket.readyState <= 1) socket.close(1000, "bye"); } + /** Whether pending work still belongs to the active relay attempt. */ + private owns(owner: AbortController): boolean { + return this.running && this.owner === owner; + } + private clearTimer(): void { if (this.timer) clearTimeout(this.timer); this.timer = null; diff --git a/src/main/features/remote/route.ts b/src/main/features/remote/route.ts index 6499e8cf9..190d21388 100644 --- a/src/main/features/remote/route.ts +++ b/src/main/features/remote/route.ts @@ -54,44 +54,60 @@ export class ServerRoute { } /** - * Brings a socket that went straight back through the proxy, as the relay's - * may stay for days on a desktop left on: once requests go through the - * proxy again while `via()` (the address the socket is open to, null while - * none is) is the server's, the proxy's /info is asked, and when it - * answers the socket is opened anew (`reconnect`), through it. When it - * does not, the proxy is passed by for another while. `check` looks now; - * the returned function stops the looking every RETURN_CHECK_MS. + * Checks whether a socket that went straight can return through the proxy. + * The result belongs to the open socket and route that initiated the probe. */ export function returnToProxy(options: { route: ServerRoute; - via: () => string | null; + via: () => { readonly origin: string } | null; reconnect: () => void; fetch?: typeof fetch; }): { check(): Promise; stop(): void } { const { route } = options; const fetchFn = options.fetch ?? fetch; + const lifetime = new AbortController(); let asking = false; - const check = async () => { + + /** Probes the proxy while the current socket is open to the server directly. */ + async function check(): Promise { const proxy = route.proxy; - const via = options.via(); - if (proxy === null || via === null || sameHost(via, proxy) || route.base() !== proxy) return; - if (asking) return; + if (lifetime.signal.aborted || asking || proxy === null || route.base() !== proxy) return; + const connection = options.via(); + if ( + connection === null || + sameHost(connection.origin, proxy) || + !sameHost(connection.origin, route.server) + ) { + return; + } + asking = true; + let reachable: boolean; try { const res = await fetchFn(new URL("/info", proxy), { - signal: AbortSignal.timeout(RETURN_PROBE_TIMEOUT_MS), + signal: AbortSignal.any([lifetime.signal, AbortSignal.timeout(RETURN_PROBE_TIMEOUT_MS)]), }); - if (res.ok) options.reconnect(); - else route.unreachable(proxy); + reachable = res.ok; } catch { - route.unreachable(proxy); + reachable = false; } finally { asking = false; } - }; + + if (lifetime.signal.aborted || options.via() !== connection || route.base() !== proxy) return; + if (reachable) options.reconnect(); + else route.unreachable(proxy); + } + const timer = setInterval(() => void check(), RETURN_CHECK_MS); timer.unref?.(); - return { check, stop: () => clearInterval(timer) }; + return { + check, + stop() { + clearInterval(timer); + lifetime.abort(); + }, + }; } /** Whether two addresses are of one host, a websocket's (wss:) and its https: alike. */ diff --git a/src/main/features/remote/ticket.ts b/src/main/features/remote/ticket.ts index 42a7791d0..19b94a727 100644 --- a/src/main/features/remote/ticket.ts +++ b/src/main/features/remote/ticket.ts @@ -16,11 +16,21 @@ export const TicketSchema = z.object({ ticket: z.string().min(1) }); export async function askTicket( account: Pick, body?: unknown, + signal?: AbortSignal, ): Promise { try { - const answer = await account.request("POST", `/relay/ticket?v=${RELAY_VERSION}`, body); + signal?.throwIfAborted(); + const answer = await account.request( + "POST", + `/relay/ticket?v=${RELAY_VERSION}`, + body, + undefined, + signal, + ); + signal?.throwIfAborted(); return TicketSchema.parse(answer).ticket; } catch (error) { + signal?.throwIfAborted(); if ( error instanceof ServerError && error.status === 400 && diff --git a/tests/unit/main/features/remote/account.test.ts b/tests/unit/main/features/remote/account.test.ts index d6792091f..f33112939 100644 --- a/tests/unit/main/features/remote/account.test.ts +++ b/tests/unit/main/features/remote/account.test.ts @@ -14,6 +14,8 @@ import { listenForCallback } from "../../../../../src/main/features/remote/loopb import { challengeOf } from "../../../../../src/main/features/remote/pkce"; import { keptInMemory } from "../../../../../src/main/features/remote/sealed-file"; +import { askTicket } from "../../../../../src/main/features/remote/ticket"; + const SERVER = "http://localhost:8787"; const memoryStore = (initial: SavedAccount | null = null) => keptInMemory(initial); @@ -189,6 +191,54 @@ describe("the way to the server", () => { }); describe("the account", () => { + test.each([ + "unauthorized", + "unreachable", + ] as const)("ignores an old relay ticket's %s result after the next ticket succeeded", async (failure) => { + const proxy = "https://proxy.example"; + const store = memoryStore({ server: SERVER, token: "tok", user, device }); + const earlier = Promise.withResolvers(); + let asked = 0; + const account = new RemoteAccount({ + server: SERVER, + proxy, + store, + openExternal: async () => {}, + fetch: (() => + asked++ === 0 + ? earlier.promise + : Promise.resolve(new Response(JSON.stringify({ ticket: "new" })))) as typeof fetch, + }); + await account.restore(); + const attempt = new AbortController(); + const old = askTicket(account, undefined, attempt.signal).catch((error: unknown) => error); + attempt.abort(); + expect(await askTicket(account)).toBe("new"); + if (failure === "unauthorized") earlier.resolve(new Response(null, { status: 401 })); + else earlier.reject(new TypeError("fetch failed")); + + expect(await old).toMatchObject({ name: "AbortError" }); + expect(account.state().status).toBe("signed-in"); + expect(store.value?.token).toBe("tok"); + expect(account.route.base()).toBe(proxy); + expect(asked).toBe(2); + }); + + test("a current relay ticket's unauthorized response still signs out the account", async () => { + const account = new RemoteAccount({ + server: SERVER, + store: memoryStore({ server: SERVER, token: "tok", user, device }), + openExternal: async () => {}, + fetch: (async () => new Response(null, { status: 401 })) as typeof fetch, + }); + await account.restore(); + + await expect( + askTicket(account, undefined, new AbortController().signal), + ).rejects.toBeInstanceOf(SignedOutError); + expect(account.state().status).toBe("signed-out"); + }); + test("signs in through the browser with PKCE and keeps the device's token", async () => { const store = memoryStore(); const server = fakeServer(); diff --git a/tests/unit/main/features/remote/relay-connection.test.ts b/tests/unit/main/features/remote/relay-connection.test.ts index 4e8c09ea5..6c822bbb3 100644 --- a/tests/unit/main/features/remote/relay-connection.test.ts +++ b/tests/unit/main/features/remote/relay-connection.test.ts @@ -1,12 +1,19 @@ /** The relay's socket: a socket that never opened says what it went to was not reached. */ -import { describe, expect, test } from "bun:test"; -import { OutdatedError, UnreachableError } from "../../../../../src/main/features/remote/errors"; +import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test"; import { + OutdatedError, + SignedOutError, + UnreachableError, +} from "../../../../../src/main/features/remote/errors"; +import { + CLOSE_REPLACED, + CLOSE_SIGNED_OUT, RELAY_PING, RELAY_PONG, RelayConnection, type RelayStatus, } from "../../../../../src/main/features/remote/relay-connection"; +import { returnToProxy, ServerRoute } from "../../../../../src/main/features/remote/route"; class FakeSocket { readyState = 0; @@ -16,6 +23,8 @@ class FakeSocket { this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]); } emit(type: string, event: object = {}) { + if (type === "open") this.readyState = 1; + if (type === "close") this.readyState = 3; for (const listener of this.listeners.get(type) ?? []) listener(event as never); } readonly sent: string[] = []; @@ -25,6 +34,7 @@ class FakeSocket { } close() { this.closed = true; + this.readyState = 2; } } @@ -213,9 +223,207 @@ test("a socket that never opened does not try again at once", async () => { relay.stop(); }); +describe("relay ticket ownership", () => { + const firstUrl = "wss://nexus.example/relay?ticket=old"; + const nextUrl = "wss://proxy.example/relay?ticket=new"; + + /** Controls which ticket completes first and records every allocated socket. */ + function harness() { + const first = Promise.withResolvers(); + const next = Promise.withResolvers(); + const tickets = [first, next]; + const sockets: FakeSocket[] = []; + const statuses: RelayStatus[] = []; + const signedOut = jest.fn(); + const url = jest.fn(() => { + const ticket = tickets.shift(); + if (!ticket) throw new Error("unexpected ticket request"); + return ticket.promise; + }); + const relay = new RelayConnection({ + url, + onOpen: () => {}, + onFrame: () => {}, + onStatus: (status) => statuses.push(status), + onSignedOut: signedOut, + socket: (url) => { + const socket = new FakeSocket(url); + sockets.push(socket); + return socket; + }, + backoff: () => 100, + }); + relay.start(); + return { relay, first, next, url, sockets, statuses, signedOut }; + } + + afterEach(() => jest.useRealTimers()); + + test.each([ + "first", + "last", + ] as const)("only opens the current socket when the stale ticket succeeds %s", async (order) => { + jest.useFakeTimers(); + const { relay, first, next, sockets } = harness(); + try { + relay.reconnect(); + if (order === "first") { + first.resolve(firstUrl); + await Promise.resolve(); + expect(sockets).toHaveLength(0); + } + next.resolve(nextUrl); + await Promise.resolve(); + sockets[0]?.emit("open"); + if (order === "last") { + first.resolve(firstUrl); + await Promise.resolve(); + } + expect(sockets.map((socket) => socket.url)).toEqual([nextUrl]); + } finally { + relay.stop(); + } + expect(sockets.every((socket) => socket.closed)).toBe(true); + }); + + test.each([ + ["retry", () => new UnreachableError(new TypeError("unreachable"))], + ["give up", () => new OutdatedError()], + ["sign out", () => new SignedOutError()], + ] as const)("a stale ticket cannot %s after the replacement is online", async (_action, error) => { + jest.useFakeTimers(); + const { relay, first, next, url, sockets, statuses, signedOut } = harness(); + try { + relay.reconnect(); + next.resolve(nextUrl); + await Promise.resolve(); + sockets[0]?.emit("open"); + + first.reject(error()); + await Promise.resolve(); + jest.advanceTimersByTime(100); + + expect(statuses).toEqual(["connecting", "online"]); + expect(sockets.map((socket) => [socket.url, socket.closed])).toEqual([[nextUrl, false]]); + expect(url).toHaveBeenCalledTimes(2); + expect(signedOut).not.toHaveBeenCalled(); + } finally { + relay.stop(); + } + }); + + test.each([ + [CLOSE_REPLACED, "replaced", 0], + [CLOSE_SIGNED_OUT, "stopped", 1], + ] as const)("current socket close %s still ends the relay", async (code, status, called) => { + jest.useFakeTimers(); + const { relay, first, url, sockets, statuses, signedOut } = harness(); + try { + first.resolve(firstUrl); + await Promise.resolve(); + sockets[0]?.emit("open"); + sockets[0]?.emit("close", { code }); + + relay.reconnect(); + jest.advanceTimersByTime(60_000); + expect(statuses).toEqual(["connecting", "online", status]); + expect(url).toHaveBeenCalledTimes(1); + expect(signedOut).toHaveBeenCalledTimes(called); + } finally { + relay.stop(); + } + }); + + test("a ticket from before stop cannot open a socket after start", async () => { + jest.useFakeTimers(); + const { relay, first, next, sockets } = harness(); + try { + relay.stop(); + relay.start(); + first.resolve(firstUrl); + await Promise.resolve(); + expect(sockets).toHaveLength(0); + next.resolve(nextUrl); + await Promise.resolve(); + expect(sockets.map((socket) => socket.url)).toEqual([nextUrl]); + } finally { + relay.stop(); + } + }); + + test("a stop during the connecting notification prevents asking for a ticket", () => { + const url = jest.fn(async () => firstUrl); + const relay = new RelayConnection({ + url, + onOpen: () => {}, + onFrame: () => {}, + onStatus: (status) => { + if (status === "connecting") relay.stop(); + }, + onSignedOut: () => {}, + }); + relay.start(); + expect(url).not.toHaveBeenCalled(); + }); +}); + +test("a proxy probe completing during automatic reconnect leaves the pending ticket in charge", async () => { + const ticket = Promise.withResolvers(); + const response = Promise.withResolvers(); + const sockets: FakeSocket[] = []; + const url = jest.fn(() => + sockets.length === 0 + ? Promise.resolve("wss://nexus.example/relay?ticket=direct") + : ticket.promise, + ); + const relay = new RelayConnection({ + url, + onOpen: () => {}, + onFrame: () => {}, + onStatus: () => {}, + onSignedOut: () => {}, + socket: (url) => { + const socket = new FakeSocket(url); + sockets.push(socket); + return socket; + }, + }); + const probe = returnToProxy({ + route: new ServerRoute("https://nexus.example", "https://proxy.example", () => 0), + via: () => relay.onlineRoute(), + reconnect: () => relay.reconnect(), + fetch: (() => response.promise) as typeof fetch, + }); + try { + relay.start(); + await Promise.resolve(); + sockets[0]?.emit("open"); + const pending = probe.check(); + sockets[0]?.emit("close", { code: 1006 }); + expect(url).toHaveBeenCalledTimes(2); + + response.resolve(new Response("{}")); + await pending; + expect(url).toHaveBeenCalledTimes(2); + ticket.resolve("wss://proxy.example/relay?ticket=recovered"); + await Promise.resolve(); + sockets[1]?.emit("open"); + expect(relay.onlineRoute()?.origin).toBe("wss://proxy.example"); + expect(sockets).toHaveLength(2); + } finally { + probe.stop(); + relay.stop(); + } + expect(sockets[1]?.closed).toBe(true); +}); + describe("the heartbeat", () => { const heartbeat = { every: 10, wait: 15 }; - const open = () => { + beforeEach(() => jest.useFakeTimers()); + afterEach(() => jest.useRealTimers()); + + /** Opens the connection before advancing the heartbeat clock. */ + async function open() { const sockets: FakeSocket[] = []; const frames: unknown[] = []; const statuses: RelayStatus[] = []; @@ -228,56 +436,61 @@ describe("the heartbeat", () => { socket: (url) => { const socket = new FakeSocket(url); sockets.push(socket); - return socket as never; + return socket; }, backoff: () => 60_000, heartbeat, }); - const next = async (count: number) => { - for (let i = 0; i < 100 && sockets.length < count; i++) await Bun.sleep(1); - return sockets[count - 1]; - }; - return { relay, sockets, frames, statuses, next }; - }; + relay.start(); + await Promise.resolve(); + const socket = sockets[0]; + if (!socket) throw new Error("no socket"); + socket.emit("open"); + return { relay, sockets, frames, statuses, socket }; + } test("an answered heartbeat keeps the socket, and the answer is no frame", async () => { - const { relay, sockets, frames, next } = open(); - relay.start(); - const socket = await next(1); - socket?.emit("open"); - for (let beats = 0; beats < 3; beats++) { - for (let i = 0; i < 100 && (socket?.sent.length ?? 0) <= beats; i++) await Bun.sleep(1); - expect(socket?.sent[beats]).toBe(RELAY_PING); - socket?.emit("message", { data: RELAY_PONG }); + const { relay, sockets, frames, socket } = await open(); + try { + for (let beat = 0; beat < 3; beat++) { + jest.advanceTimersByTime(heartbeat.every); + expect(socket.sent[beat]).toBe(RELAY_PING); + socket.emit("message", { data: RELAY_PONG }); + } + expect([sockets.length, socket.closed, frames]).toEqual([1, false, []]); + } finally { + relay.stop(); } - expect([sockets.length, socket?.closed, frames]).toEqual([1, false, []]); - relay.stop(); }); test("one not answered lets the socket go and joins the room again at once", async () => { - const { relay, sockets, statuses, next } = open(); - relay.start(); - const first = await next(1); - first?.emit("open"); - const second = await next(2); - expect(first?.sent).toEqual([RELAY_PING]); - expect(first?.closed).toBe(true); - expect(second).toBeDefined(); - expect(statuses).not.toContain("waiting"); - // Its own close, when it comes at last, is not taken for another loss. - first?.emit("close", { code: 1006 }); - await Bun.sleep(5); - expect(sockets).toHaveLength(2); - relay.stop(); + const { relay, sockets, statuses, socket } = await open(); + try { + jest.advanceTimersByTime(heartbeat.every); + expect(socket.sent).toEqual([RELAY_PING]); + jest.advanceTimersByTime(heartbeat.wait - 1); + expect(socket.closed).toBe(false); + + jest.advanceTimersByTime(1); + await Promise.resolve(); + expect(socket.closed).toBe(true); + expect(sockets).toHaveLength(2); + expect(statuses).not.toContain("waiting"); + + // Its close may arrive after the next socket starts connecting. + socket.emit("close", { code: 1006 }); + jest.advanceTimersByTime(60_000); + await Promise.resolve(); + expect(sockets).toHaveLength(2); + } finally { + relay.stop(); + } }); test("none is sent once the socket is let go", async () => { - const { relay, next } = open(); - relay.start(); - const socket = await next(1); - socket?.emit("open"); + const { relay, socket } = await open(); relay.stop(); - await Bun.sleep(30); - expect(socket?.sent).toEqual([]); + jest.advanceTimersByTime(3 * heartbeat.every); + expect(socket.sent).toEqual([]); }); }); diff --git a/tests/unit/main/features/remote/route.test.ts b/tests/unit/main/features/remote/route.test.ts index 4fef4ef6a..22b67cfe0 100644 --- a/tests/unit/main/features/remote/route.test.ts +++ b/tests/unit/main/features/remote/route.test.ts @@ -1,5 +1,5 @@ /** How requests reach the server: through the proxy, straight for a while when it fails. */ -import { describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, test } from "bun:test"; import { PROXY_DOWN_MS, returnToProxy, @@ -48,10 +48,16 @@ describe("the route to the server", () => { }); describe("a socket that went straight", () => { + const probes: ReturnType[] = []; + afterEach(() => { + for (const probe of probes.splice(0)) probe.stop(); + }); + + /** Controls the socket and the route independently of the probe response. */ function setup(answer: () => Response | Error) { let now = 0; const route = new ServerRoute(SERVER, PROXY, () => now); - let via: string | null = "wss://nexus.example"; + let via: { origin: string } | null = { origin: "wss://nexus.example" }; const asked: string[] = []; let reconnects = 0; const back = returnToProxy({ @@ -67,7 +73,7 @@ describe("a socket that went straight", () => { return result; }) as typeof fetch, }); - back.stop(); + probes.push(back); return { route, back, @@ -77,7 +83,7 @@ describe("a socket that went straight", () => { now = ms; }, goes: (to: string | null) => { - via = to; + via = to ? { origin: to } : null; }, }; } @@ -103,6 +109,64 @@ describe("a socket that went straight", () => { expect([t.asked, t.reconnects()]).toEqual([[], 0]); }); + test.each([ + "disconnected", + "replaced at the same origin", + "on another route", + "disposed", + ] as const)("ignores a late probe success after the original connection is %s", async (change) => { + const route = new ServerRoute(SERVER, PROXY, () => 0); + const response = Promise.withResolvers(); + let via: { origin: string } | null = { origin: "wss://nexus.example" }; + let reconnects = 0; + let probeSignal: AbortSignal | null | undefined; + const probe = returnToProxy({ + route, + via: () => via, + reconnect: () => { + reconnects += 1; + }, + fetch: ((_input, init) => { + probeSignal = init?.signal; + return response.promise; + }) as typeof fetch, + }); + try { + const pending = probe.check(); + if (change === "disconnected") via = null; + else if (change === "replaced at the same origin") via = { origin: "wss://nexus.example" }; + else if (change === "on another route") route.unreachable(PROXY); + else { + probe.stop(); + expect(probeSignal?.aborted).toBe(true); + } + response.resolve(new Response("{}")); + await pending; + expect(reconnects).toBe(0); + } finally { + probe.stop(); + } + }); + + test("a late probe failure cannot put the proxy in cooldown for a new socket", async () => { + const route = new ServerRoute(SERVER, PROXY, () => 0); + const response = Promise.withResolvers(); + let connection = { origin: "wss://nexus.example" }; + const probe = returnToProxy({ + route, + via: () => connection, + reconnect: () => {}, + fetch: (() => response.promise) as typeof fetch, + }); + probes.push(probe); + const pending = probe.check(); + connection = { origin: "wss://nexus.example" }; + response.reject(new TypeError("old probe failed")); + await pending; + + expect(route.base()).toBe(PROXY); + }); + test("a proxy that does not answer, or answers with an error, is passed by again", async () => { for (const answer of [ () => new TypeError("fetch failed"), From c09735dea06bdc9644c3f14c95565c5c96c0cbd7 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:48:19 +0900 Subject: [PATCH 030/208] test(workspace): isolate reconnect hook checks from Windows launchers Co-Authored-By: Claude Opus 5.5 --- .../main/workspace/manager-local-lifecycle-degraded.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts b/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts index dfedcd0b1..0270a0e23 100644 --- a/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts +++ b/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts @@ -18,7 +18,7 @@ */ import { Database } from "bun:sqlite"; -import { describe, expect, mock, test } from "bun:test"; +import { describe, expect, mock, spyOn, test } from "bun:test"; import os from "node:os"; import path from "node:path"; @@ -155,6 +155,9 @@ for (const available of [true, false]) { test(`local reconnect waits for refreshed hooks before resync and spawn (${available ? "available" : "unavailable"})`, async () => { const harness = makeHarness(); const { manager, channels, globalDb } = harness; + // Windows CI has no packaged nexus.exe to install. The launched chat + // needs a wrapper directory here so this test exercises hook refresh. + const wrapperDir = spyOn(manager, "getWrapperBinDir").mockReturnValue("/stub/wrappers"); const resynced = Promise.withResolvers(); const events: string[] = []; const host = new ChatHost({ @@ -196,6 +199,7 @@ for (const available of [true, false]) { } expect(events).toEqual(["held", "resync"]); } finally { + wrapperDir.mockRestore(); host.dispose(); globalDb.close(); } From 8043810c36bbdf6ce363173a48b10812bfe00474 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:50:38 +0900 Subject: [PATCH 031/208] fix(search): retain cancellation before registration Co-Authored-By: Claude Opus 5.5 --- internal/search/service.go | 88 +++++++++++++++---- internal/search/service_test.go | 27 ++++++ src/main/features/search/index.ts | 44 ++++++---- .../unit/main/features/remote/search.test.ts | 32 ++++--- .../ipc/channels/fs/search-handlers.test.ts | 33 +++++++ 5 files changed, 176 insertions(+), 48 deletions(-) diff --git a/internal/search/service.go b/internal/search/service.go index b44b1603f..4fe77a34f 100644 --- a/internal/search/service.go +++ b/internal/search/service.go @@ -26,6 +26,8 @@ const ( batchMatchesTrigger = 200 batchTimeTrigger = 30 * time.Millisecond perFileMatchCap = 1000 + earlyCancelLifetime = 30 * time.Second + maxEarlyCancels = 1024 // previewMaxBytes bounds Match.Preview. Lines up to this length are sent // whole; longer lines (minified bundles, single-line JSON) are cut to a @@ -50,9 +52,10 @@ type EventSink func(event string, payload any) error type Service struct { root string - mu sync.Mutex - sink EventSink - cancels map[string]context.CancelFunc + mu sync.Mutex + sink EventSink + cancels map[string]context.CancelFunc + earlyCancels map[string]time.Time } type Params struct { @@ -129,7 +132,10 @@ func New(root string) (*Service, error) { if err != nil { return nil, err } - return &Service{root: filepath.Clean(abs), cancels: make(map[string]context.CancelFunc)}, nil + return &Service{ + root: filepath.Clean(abs), cancels: make(map[string]context.CancelFunc), + earlyCancels: make(map[string]time.Time), + }, nil } func (s *Service) SetEventSink(sink EventSink) { @@ -152,23 +158,19 @@ func (s *Service) Text(ctx context.Context, raw json.RawMessage) (any, error) { if p.SearchID == "" { return nil, proto.ProtocolError("search.text searchId is required") } + searchCtx, finish, err := s.registerSearch(ctx, p.SearchID) + if err != nil { + return nil, err + } + defer finish() normalizeQuery(&p.Query) - re, err := compilePattern(p.Query) if err != nil { return nil, err } - - searchCtx, cancel := context.WithCancel(ctx) - s.mu.Lock() - s.cancels[p.SearchID] = cancel - s.mu.Unlock() - defer func() { - cancel() - s.mu.Lock() - delete(s.cancels, p.SearchID) - s.mu.Unlock() - }() + if err := searchCtx.Err(); err != nil { + return nil, err + } start := time.Now() result, err := s.walk(searchCtx, p.SearchID, p.Query, re) @@ -179,20 +181,68 @@ func (s *Service) Text(ctx context.Context, raw json.RawMessage) (any, error) { return result, nil } +// registerSearch consumes a cancellation that overtook this request or +// publishes its cancel function before compilation or walking begins. +func (s *Service) registerSearch(ctx context.Context, id string) (context.Context, func(), error) { + s.mu.Lock() + defer s.mu.Unlock() + if expiry, ok := s.earlyCancels[id]; ok { + delete(s.earlyCancels, id) + if time.Now().Before(expiry) { + return nil, nil, context.Canceled + } + } + if err := ctx.Err(); err != nil { + return nil, nil, err + } + if s.cancels[id] != nil { + return nil, nil, proto.ProtocolError("search.text searchId is already running") + } + searchCtx, cancel := context.WithCancel(ctx) + s.cancels[id] = cancel + return searchCtx, func() { + s.mu.Lock() + defer s.mu.Unlock() + cancel() + delete(s.cancels, id) + }, nil +} + func (s *Service) Cancel(_ context.Context, raw json.RawMessage) (any, error) { var p CancelParams if len(raw) == 0 || json.Unmarshal(raw, &p) != nil || p.SearchID == "" { return nil, proto.ProtocolError("search.cancel params must include searchId") } s.mu.Lock() - cancel := s.cancels[p.SearchID] - s.mu.Unlock() - if cancel != nil { + defer s.mu.Unlock() + if cancel := s.cancels[p.SearchID]; cancel != nil { cancel() + } else { + s.rememberCancel(p.SearchID, time.Now()) } return struct{}{}, nil } +// rememberCancel keeps recent unmatched cancellations with a fixed capacity. +// The caller holds mu so lookup and registration see each cancel exactly once. +func (s *Service) rememberCancel(id string, now time.Time) { + var oldestID string + var oldest time.Time + for key, expiry := range s.earlyCancels { + if !now.Before(expiry) { + delete(s.earlyCancels, key) + continue + } + if oldest.IsZero() || expiry.Before(oldest) { + oldestID, oldest = key, expiry + } + } + if len(s.earlyCancels) >= maxEarlyCancels && s.earlyCancels[id].IsZero() { + delete(s.earlyCancels, oldestID) + } + s.earlyCancels[id] = now.Add(earlyCancelLifetime) +} + func normalizeQuery(q *Query) { if q.MaxResults <= 0 { q.MaxResults = defaultMaxResults diff --git a/internal/search/service_test.go b/internal/search/service_test.go index 63f73496c..a6bcc5706 100644 --- a/internal/search/service_test.go +++ b/internal/search/service_test.go @@ -3,6 +3,7 @@ package search import ( "context" "encoding/json" + "errors" "os" "path/filepath" "slices" @@ -12,6 +13,32 @@ import ( "unicode/utf8" ) +// TestCancelBeforeSearchRegistration verifies that a cancel dispatched first +// still stops its search before any progress reaches the client. +func TestCancelBeforeSearchRegistration(t *testing.T) { + root := t.TempDir() + must(t, os.WriteFile(filepath.Join(root, "match.txt"), []byte("needle\n"), 0o644)) + service := mustSearch(t, root) + service.SetEventSink(func(_ string, payload any) error { + if progress := payload.(ProgressPayload); progress.SearchID == "closed" { + t.Error("canceled search sent progress") + } + return nil + }) + ctx := context.Background() + _, err := service.Cancel(ctx, mustJSON(t, CancelParams{SearchID: "closed"})) + must(t, err) + _, err = service.Text(ctx, mustJSON(t, Params{SearchID: "closed", Query: Query{Pattern: "needle"}})) + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled search returned %v", err) + } + result, err := service.Text(ctx, mustJSON(t, Params{SearchID: "next", Query: Query{Pattern: "needle"}})) + must(t, err) + if result.(Complete).MatchesFound != 1 { + t.Fatalf("replacement search returned %+v", result) + } +} + func TestTextSearchBoundsPreviewOnLongLines(t *testing.T) { root := t.TempDir() // One 256 KiB line: before the preview window existed, every one of the diff --git a/src/main/features/search/index.ts b/src/main/features/search/index.ts index ba4dbc021..5b886eafe 100644 --- a/src/main/features/search/index.ts +++ b/src/main/features/search/index.ts @@ -69,35 +69,45 @@ export function searchTextStream(manager: WorkspaceManager): SearchTextStreamHan // a local request timeout, the consumer stopping early) leaves the // search running on the agent, so it must be cancelled there. let answered = false; + let started = false; + let cancelSent = false; const unsubscribe = provider.onAgentEvent(SEARCH_PROGRESS_EVENT, (payload) => { const parsed = AgentSearchProgressPayloadSchema.safeParse(payload); if (!parsed.success || parsed.data.searchId !== searchId) return; queue.push(parsed.data.batch); }); - const complete = provider - .callAgentMethod(SEARCH_TEXT_METHOD, { searchId, query }) - .then((result) => { - answered = true; - return AgentSearchCompleteSchema.parse(result); - }) - .catch((error) => { - throw normalizeSearchError(error); - }) - .finally(() => { - queue.close(); - }); - complete.catch(() => {}); - - const abort = (): void => { + const cancel = (): void => { + if (!started || answered || cancelSent) return; + cancelSent = true; void provider.callAgentMethod(SEARCH_CANCEL_METHOD, { searchId }).catch(() => {}); + }; + const abort = (): void => { queue.fail(createAbortError()); + cancel(); }; ctx.signal.addEventListener("abort", abort, { once: true }); try { + if (ctx.signal.aborted) throw createAbortError(); + started = true; + const complete = provider + .callAgentMethod(SEARCH_TEXT_METHOD, { searchId, query }) + .then((result) => { + answered = true; + return AgentSearchCompleteSchema.parse(result); + }) + .catch((error) => { + throw normalizeSearchError(error); + }) + .finally(() => { + queue.close(); + }); + complete.catch(() => {}); + for (;;) { const next = await queue.next(); + if (ctx.signal.aborted) throw createAbortError(); if (next.done) { return await complete; } @@ -106,9 +116,7 @@ export function searchTextStream(manager: WorkspaceManager): SearchTextStreamHan } finally { ctx.signal.removeEventListener("abort", abort); unsubscribe(); - if (!answered) { - void provider.callAgentMethod(SEARCH_CANCEL_METHOD, { searchId }).catch(() => {}); - } + cancel(); } }; } diff --git a/tests/unit/main/features/remote/search.test.ts b/tests/unit/main/features/remote/search.test.ts index 64f1b2fc7..795b0c107 100644 --- a/tests/unit/main/features/remote/search.test.ts +++ b/tests/unit/main/features/remote/search.test.ts @@ -1,5 +1,5 @@ /** A workspace's files searched from another device: by name, and for text, in its agent. */ -import { describe, expect, test } from "bun:test"; +import { describe, expect, jest, test } from "bun:test"; import type { FsProvider } from "../../../../../src/main/features/fs/bridge/provider"; import { findFiles, searchFiles } from "../../../../../src/main/features/remote/search"; import type { FileMatch } from "../../../../../src/shared/search/types"; @@ -171,16 +171,26 @@ describe("searching files for text", () => { }); test("out of time: what it found so far, cut", async () => { - const { fs, calls } = fakeAgent({ - batches: [[{ relPath: "x", matches: [match(0, 0, 1, "a")] }]], - hang: true, - }); - const found = await searchFiles(fs, { workspaceId: "w1", query: "a" }, 20); - expect(found).toEqual({ - files: [{ path: "x", matches: [{ line: 1, column: 0, length: 1, text: "a" }] }], - truncated: true, - }); - expect(calls.at(-1)?.method).toBe("search.cancel"); + jest.useFakeTimers(); + try { + const { fs, calls } = fakeAgent({ + batches: [[{ relPath: "x", matches: [match(0, 0, 1, "a")] }]], + hang: true, + }); + const pending = searchFiles(fs, { workspaceId: "w1", query: "a" }, 20); + await Promise.resolve(); + expect(calls.map((call) => call.method)).toEqual(["search.text"]); + jest.advanceTimersByTime(20); + expect(await pending).toEqual({ + files: [{ path: "x", matches: [{ line: 1, column: 0, length: 1, text: "a" }] }], + truncated: true, + }); + expect(calls.slice(1)).toEqual([ + { method: "search.cancel", params: { searchId: calls[0]?.params.searchId } }, + ]); + } finally { + jest.useRealTimers(); + } }); test("a pattern that is no regular expression is the asker's error", async () => { diff --git a/tests/unit/main/ipc/channels/fs/search-handlers.test.ts b/tests/unit/main/ipc/channels/fs/search-handlers.test.ts index 05fb8ada1..58e49aa35 100644 --- a/tests/unit/main/ipc/channels/fs/search-handlers.test.ts +++ b/tests/unit/main/ipc/channels/fs/search-handlers.test.ts @@ -118,6 +118,39 @@ async function consumeSearch( } describe("searchTextStream", () => { + test("cancels once when IPC aborts as the agent request is sent", async () => { + const ctrl = new AbortController(); + const provider = makeAgentProvider({}); + const canceled: unknown[] = []; + let searchParams: unknown; + let reply!: (result: SearchComplete) => void; + const response = new Promise((resolve) => { + reply = resolve; + }); + provider.callAgentMethod = async (method, params) => { + if (method === "search.cancel") { + canceled.push(params); + return {}; + } + searchParams = params; + ctrl.abort(); + return response; + }; + const handler = searchTextStream(makeManager(provider) as never); + const pending = handler( + { workspaceId: VALID_UUID, query: baseQuery({ pattern: "needle" }) }, + context(ctrl.signal), + ).next(); + await Promise.resolve(); + const canceledBeforeReply = canceled.slice(); + reply({ filesScanned: 1, matchesFound: 0, limitHit: false, elapsedMs: 1 }); + await expect(pending).rejects.toThrow("aborted"); + expect(canceledBeforeReply).toEqual([ + { searchId: (searchParams as { searchId: string }).searchId }, + ]); + expect(canceled).toHaveLength(1); + }); + test("throws AbortError when the stream signal is already aborted", async () => { const ctrl = new AbortController(); ctrl.abort(); From 6126fb30585710e05dfbe71de0ec9631b1fc800d Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:26:37 +0900 Subject: [PATCH 032/208] fix(workspace): stop remote daemons during provider setup Co-Authored-By: Claude Opus 5.5 --- cmd/agent/daemon.go | 15 +++-- cmd/agent/daemon_test.go | 5 ++ src/main/features/workspace/manager.ts | 30 ++++++---- .../manager-reattach-lifecycle.test.ts | 60 +++++++++++++++++++ 4 files changed, 91 insertions(+), 19 deletions(-) diff --git a/cmd/agent/daemon.go b/cmd/agent/daemon.go index 15385d3de..daf491b34 100644 --- a/cmd/agent/daemon.go +++ b/cmd/agent/daemon.go @@ -303,11 +303,10 @@ func runDaemon(root string) { // reconnect state must be discarded. epoch := agentrun.NewEpoch() - // cleanupAndExit tears down all shared resources and terminates. - // Called only on genuine daemon shutdown — not on dialer disconnect. - // Only the first caller tears down; any other blocks until it exits. + // Release the workspace before acknowledging shutdown. A new launcher + // may try this socket and lock as soon as the reply reaches the app. var shutdown sync.Once - cleanupAndExit := func(code int) { + releaseWorkspace := func() { shutdown.Do(func() { pty.Close() // hang up every terminal, as closing its tab does chat.Close() // and end every Claude tab's program @@ -318,16 +317,20 @@ func runDaemon(root string) { _ = ln.Close() _ = os.Remove(paths.Sock) lock.Unlock() - _ = logFile.Close() - os.Exit(code) }) } + cleanupAndExit := func(code int) { + releaseWorkspace() + _ = logFile.Close() + os.Exit(code) + } // agent.shutdown comes from the app removing the workspace: no dialer // will come back, so the daemon exits now instead of holding its // terminals and language servers through reattachGrace. d.Register("agent.shutdown", func(_ context.Context, _ json.RawMessage) (any, error) { agentLogger.Info("daemon shutdown requested") + releaseWorkspace() time.AfterFunc(shutdownReplyDelay, func() { cleanupAndExit(0) }) return struct{}{}, nil }) diff --git a/cmd/agent/daemon_test.go b/cmd/agent/daemon_test.go index 005079afa..30e6895b3 100644 --- a/cmd/agent/daemon_test.go +++ b/cmd/agent/daemon_test.go @@ -485,6 +485,11 @@ func TestDaemonExitsOnShutdown(t *testing.T) { } } + // The client can re-add the workspace as soon as it receives the reply. + if _, err := os.Stat(sockPath); !os.IsNotExist(err) { + t.Errorf("old daemon socket is still present after shutdown reply: %v", err) + } + select { case err := <-exited: if err != nil { diff --git a/src/main/features/workspace/manager.ts b/src/main/features/workspace/manager.ts index 064d7700a..177cce82e 100644 --- a/src/main/features/workspace/manager.ts +++ b/src/main/features/workspace/manager.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; -import { createAbortError, isAbortError } from "../../../shared/abort"; +import { createAbortError } from "../../../shared/abort"; import { AgentManifestSchema } from "../../../shared/agent/manifest"; import { createLogger } from "../../../shared/log/main"; import { @@ -496,6 +496,9 @@ export class WorkspaceManager { channel.dispose(); } this.sshChannels.clear(); + for (const bootstrap of this.sshBootstraps.values()) { + bootstrap.dispose?.(); + } this.sshBootstraps.clear(); this.sshProviderReady.clear(); for (const master of this.adoptedSshMasters.values()) { @@ -1151,11 +1154,7 @@ export class WorkspaceManager { // One not connected, or whose agent cannot be reached, is stopped by // another agent on its host, if one is connected. const sshChannel = this.sshChannels.get(id); - const status = this.connectionStatuses.get(id); - if ( - sshChannel && - (status === "connected" || status === "unstable" || status === "reconnecting") - ) { + if (sshChannel) { this.stoppingSshChannels.add(sshChannel); const bootstrap = this.sshBootstraps.get(id); const meta = ctx.getMeta(); @@ -1177,7 +1176,6 @@ export class WorkspaceManager { this.localChannels.get(id)?.dispose(); this.localChannels.delete(id); this.localProviderReady.delete(id); - this.sshChannels.get(id)?.dispose(); this.sshChannels.delete(id); this.sshBootstraps.delete(id); this.sshProviderReady.delete(id); @@ -1499,6 +1497,7 @@ export class WorkspaceManager { // A workspace removed and added again connects once its old daemon has // been stopped, not to it as that stop ends. await this.daemonStopped(location); + if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); // A workspace created from a browse session inherits that session's // already-authenticated ControlMaster; reusing its socket lets bootstrap // skip the interactive auth round entirely (no second password prompt). @@ -1541,8 +1540,9 @@ export class WorkspaceManager { // Bootstrap failed before any channel existed. Release the adopted // master (we own it now) and surface the error state instead of // leaving the renderer stuck on "connecting". - this.broadcastConnectionStatus(meta.id, "error"); adoptedMaster?.dispose(); + if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); + this.broadcastConnectionStatus(meta.id, "error"); throw error; } // ensureRemoteAgent only returns a dispose handle for a master it @@ -1597,6 +1597,7 @@ export class WorkspaceManager { // ownership of the ControlMaster to us, so we must dispose both // bootstrap (ControlMaster) and channel here before re-throwing. disposeLifecycleListener(); + if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); this.broadcastConnectionStatus(meta.id, "error"); if (this.sshChannels.get(meta.id) === channel) { this.sshChannels.delete(meta.id); @@ -1605,17 +1606,22 @@ export class WorkspaceManager { bootstrap.dispose?.(); channel.dispose(); ctx.setFsProvider(createInitialFsProvider(ctx.getMeta())); - if (isAbortError(error) && this.sshChannels.get(meta.id) !== channel) { - throw error; - } throw error; } + if (!this.isLiveContext(meta.id, ctx)) { + disposeLifecycleListener(); + throw createWorkspaceRemovedError(meta.id); + } + try { const info = await this.readHookInfo(meta.id, channel); + if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); if (this.sshChannels.get(meta.id) === channel) this.cacheHookInfo(meta.id, info); } catch (err) { disposeLifecycleListener(); + // Removal owns the daemon shutdown once the workspace is gone. + if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); this.broadcastConnectionStatus(meta.id, "error"); if (this.sshChannels.get(meta.id) === channel) { this.sshChannels.delete(meta.id); @@ -1641,8 +1647,6 @@ export class WorkspaceManager { if (!this.isLiveContext(meta.id, ctx)) { disposeLifecycleListener(); - channel.dispose(); - bootstrap.dispose?.(); // remove() already deleted the shim dir; this boot rewrote it. this.removeShimDirQuietly(meta.id); throw createWorkspaceRemovedError(meta.id); diff --git a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts index f13531fcf..768a93c0a 100644 --- a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts +++ b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts @@ -93,6 +93,7 @@ function makeManager(overrides?: { sshChannelFactory?: Parameters[4]; writeShimFiles?: Parameters[9]; removeShimDir?: Parameters[10]; + wsl?: Parameters[11]; ptyRestoreAfterReauth?: (workspaceId: string) => Promise; ptyReleaseHeld?: (workspaceId: string) => void; }) { @@ -130,6 +131,7 @@ function makeManager(overrides?: { undefined as never, // sshLspBootstrap overrides?.writeShimFiles ?? defaultWriteShimFiles, overrides?.removeShimDir ?? defaultRemoveShimDir, + overrides?.wsl, ); // Wire held-session callbacks — default no-ops when not provided. @@ -800,6 +802,64 @@ describe("removing an SSH workspace", () => { return { channel, manager, globalDb, meta }; } + test.each([ + "ssh", + "wsl", + ] as const)("%s removal during provider setup owns shutdown and defers re-add", async (kind) => { + const hookStarted = Promise.withResolvers(); + const hookReply = Promise.withResolvers(); + class BootingChannel extends ShutdownChannel { + override async call(method: string, params?: unknown): Promise { + if (method !== "hook.getInfo") return super.call(method, params); + hookStarted.resolve(); + return hookReply.promise; + } + } + + const original = new BootingChannel(); + const replacement = new StubChannel(); + const createChannel = mock((): StubChannel => original); + createChannel.mockImplementationOnce(() => original); + createChannel.mockImplementationOnce(() => replacement); + const bootstrap = mock(async () => ({ + remoteCommand: "exec agent", + remoteHome: "/home/user", + platform: { os: "linux" as const, arch: "amd64" as const }, + uploaded: false, + remoteBinDir: "/home/user/.nexus-code/bin", + })); + const { manager, globalDb } = makeManager({ + sshBootstrap: bootstrap, + sshChannelFactory: createChannel, + wsl: { bootstrap, createChannel, lspBootstrap: mock() }, + }); + const meta = + kind === "ssh" + ? makeSshMeta(manager) + : manager.create({ + location: { kind: "wsl", distro: "Ubuntu", remotePath: "/home/user/project" }, + }); + const boot = manager.getAgentChannel(meta.id); + const removed = boot.catch((error: unknown) => error); + original.resolveChannel(); + await hookStarted.promise; + + manager.remove(meta.id); + const next = manager.create({ location: meta.location }); + const nextBoot = manager.getAgentChannel(next.id); + replacement.resolveChannel(); + hookReply.resolve({ socketPath: "/tmp/test.sock", token: "removed" }); + expect(await removed).toMatchObject({ name: "AbortError" }); + + expect(manager.getHookInfo(meta.id)).toBeNull(); + expect(createChannel).toHaveBeenCalledTimes(1); + expect(original.events).toEqual(["agent.shutdown"]); + original.answerShutdown(); + expect(await nextBoot).toBe(replacement as never); + expect(original.events).toEqual(["agent.shutdown", "dispose"]); + globalDb.close(); + }); + test("asks the remote agent to exit before closing its channel", async () => { const { channel, manager, globalDb, meta } = await bootSsh(); From bef7a06df157226dd235ec90de8384052c9003a6 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:29:11 +0900 Subject: [PATCH 033/208] fix(workspace): keep SSH reauthentication in control of retries Co-Authored-By: Claude Opus 5.5 --- src/main/features/workspace/manager.ts | 342 ++++++++---------- src/main/infra/agent/ssh/auth-prompt.ts | 12 +- src/main/infra/agent/ssh/auth-pty.ts | 8 +- src/main/infra/agent/ssh/auth.ts | 8 + src/main/infra/agent/ssh/ssh2/connect.ts | 4 + tests/unit/main/agent/ssh-auth-pty.test.ts | 7 +- tests/unit/main/agent/ssh2-client.test.ts | 8 +- .../manager-reattach-lifecycle.test.ts | 229 +++++------- 8 files changed, 279 insertions(+), 339 deletions(-) diff --git a/src/main/features/workspace/manager.ts b/src/main/features/workspace/manager.ts index 177cce82e..d4e68c652 100644 --- a/src/main/features/workspace/manager.ts +++ b/src/main/features/workspace/manager.ts @@ -68,6 +68,9 @@ import { WorkspaceContext } from "./context"; const log = createLogger("workspace"); +/** Delays before the three automatic SSH reauthentication attempts. */ +const SSH_REAUTH_BACKOFF_MS = [0, 5_000, 30_000]; + /** * How long a removed SSH workspace's agent has to answer agent.shutdown, * asked again included: one being reconnected to is asked once the link is @@ -380,18 +383,11 @@ export class WorkspaceManager { private readonly hookInfoByWorkspace = new Map(); /** One wait per local reconnect, until the replacement's hooks are known. */ private readonly localHookRefreshes = new WeakMap(); - /** - * Tracks workspaces with an in-flight automatic re-authentication attempt so - * the manager never opens a second prompt for the same workspace concurrently. - * Also prevents racing with a manual "Connect" action. - */ - private readonly reauthInFlight = new Set(); - /** - * Counts consecutive manager-level re-authentication attempts per workspace. - * Reset to 0 on a successful connection. Used for exponential backoff: - * 0 → 0 ms, 1 → 5 000 ms, 2 → 30 000 ms, then give up. - */ - private readonly reauthAttempts = new Map(); + /** One retry loop per workspace, including the gaps between attempts. */ + private readonly sshReauth = new Map< + string, + { controller: AbortController; ready: Promise } + >(); /** * Pending timers for `degraded-recovered` debounce. * Clears the "unstable" badge ~1 s after the last heartbeat recovery signal @@ -483,6 +479,8 @@ export class WorkspaceManager { */ close(): void { for (const [id, ctx] of this.contexts) { + this.cancelSshReauth(id); + this.clearDegradedRecovery(id); ctx.close(); this.contexts.delete(id); this.connectionStatuses.delete(id); @@ -1136,6 +1134,8 @@ export class WorkspaceManager { // The PTY host emits pty.exit events for each live session so the // renderer's dead-terminal banner fires without waiting for IPC. this.ptySessionCloser?.(id); + this.cancelSshReauth(id); + this.clearDegradedRecovery(id); // Step 1b — destroy all browser views for this workspace and schedule // clearStorageData. View destroys happen synchronously inside the async @@ -1458,12 +1458,18 @@ export class WorkspaceManager { * Lazily connects one SSH or WSL channel per workspace and injects it into * the context. */ - private async ensureRemoteProviderReady(ctx: WorkspaceContext): Promise { + private async ensureRemoteProviderReady(ctx: WorkspaceContext, reauth = false): Promise { const meta = ctx.getMeta(); if (meta.location.kind === "local") { return; } + const recovery = this.sshReauth.get(meta.id); + if (recovery && !reauth) { + await recovery.ready; + return; + } + const pending = this.sshProviderReady.get(meta.id); if (pending) { await pending; @@ -1542,7 +1548,7 @@ export class WorkspaceManager { // leaving the renderer stuck on "connecting". adoptedMaster?.dispose(); if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); - this.broadcastConnectionStatus(meta.id, "error"); + if (!this.sshReauth.has(meta.id)) this.broadcastConnectionStatus(meta.id, "error"); throw error; } // ensureRemoteAgent only returns a dispose handle for a master it @@ -1558,7 +1564,6 @@ export class WorkspaceManager { bootstrap.dispose?.(); throw createWorkspaceRemovedError(meta.id); } - this.sshBootstraps.set(meta.id, bootstrap); let providerMeta = meta; if (!location.remoteArch) { providerMeta = { @@ -1572,86 +1577,83 @@ export class WorkspaceManager { ctx.setMeta(providerMeta); this.broadcastFn("workspace", "changed", providerMeta); } - const channel = - location.kind === "wsl" - ? this.wsl.createChannel({ - distro: location.distro, - remoteCommand: bootstrap.remoteCommand, - }) - : this.sshChannelFactory( - sshChannelOptionsFromLocation( - { ...location, remoteArch: bootstrap.platform }, - bootstrap.remoteCommand, - bootstrap.controlPath, - ), - ); - this.sshChannels.set(meta.id, channel); - const disposeLifecycleListener = channel.onLifecycle((event) => { - this.handleSshChannelLifecycle(meta.id, channel, event); - }); - + let channel: SshChannel; try { - await channel.ready; + channel = + location.kind === "wsl" + ? this.wsl.createChannel({ + distro: location.distro, + remoteCommand: bootstrap.remoteCommand, + }) + : this.sshChannelFactory( + sshChannelOptionsFromLocation( + { ...location, remoteArch: bootstrap.platform }, + bootstrap.remoteCommand, + bootstrap.controlPath, + ), + ); } catch (error) { - // channel.ready failed: bootstrap already succeeded and transferred - // ownership of the ControlMaster to us, so we must dispose both - // bootstrap (ControlMaster) and channel here before re-throwing. - disposeLifecycleListener(); - if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); - this.broadcastConnectionStatus(meta.id, "error"); - if (this.sshChannels.get(meta.id) === channel) { - this.sshChannels.delete(meta.id); - } - this.sshBootstraps.delete(meta.id); bootstrap.dispose?.(); - channel.dispose(); - ctx.setFsProvider(createInitialFsProvider(ctx.getMeta())); + if (!this.sshReauth.has(meta.id)) this.broadcastConnectionStatus(meta.id, "error"); throw error; } + this.sshBootstraps.set(meta.id, bootstrap); + this.sshChannels.set(meta.id, channel); + let installed = false; + let bootFailure: Error | undefined; + const disposeLifecycleListener = channel.onLifecycle((event) => { + if (installed) this.handleSshChannelLifecycle(meta.id, channel, event); + else if (event.type === "failure") bootFailure = event.error; + else if (event.type === "exit" || event.type === "held-then-expired") { + bootFailure = new Error("Agent connection ended during provider setup"); + } + }); - if (!this.isLiveContext(meta.id, ctx)) { - disposeLifecycleListener(); - throw createWorkspaceRemovedError(meta.id); - } - - try { - const info = await this.readHookInfo(meta.id, channel); + /** Checks ownership after each asynchronous stage of provider setup. */ + const checkBoot = () => { if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); + if (bootFailure) throw bootFailure; + }; + let shimStarted = false; + try { + await channel.ready; + checkBoot(); + + let info: HookInfo | null; + try { + info = await this.readHookInfo(meta.id, channel); + } catch (error) { + checkBoot(); + log.warn(`agent hook setup failed for ${meta.id}: ${(error as Error).message}`); + throw new Error(`Agent hook setup failed: ${(error as Error).message}`, { cause: error }); + } + checkBoot(); if (this.sshChannels.get(meta.id) === channel) this.cacheHookInfo(meta.id, info); - } catch (err) { + + // The remote workspace's local shim supplies env/args for local PTYs. + shimStarted = true; + try { + await this.writeShimFiles(meta.id); + } catch (error) { + log.warn( + `shim file write failed for ${meta.id}; shell PATH priority may be degraded: ${(error as Error).message}`, + ); + } + checkBoot(); + } catch (error) { disposeLifecycleListener(); - // Removal owns the daemon shutdown once the workspace is gone. + if (shimStarted) this.removeShimDirQuietly(meta.id); if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); - this.broadcastConnectionStatus(meta.id, "error"); - if (this.sshChannels.get(meta.id) === channel) { - this.sshChannels.delete(meta.id); - } + this.sshChannels.delete(meta.id); this.sshBootstraps.delete(meta.id); - bootstrap.dispose?.(); + this.hookInfoByWorkspace.delete(meta.id); channel.dispose(); - ctx.setFsProvider(createInitialFsProvider(ctx.getMeta())); - log.warn(`agent hook setup failed for ${meta.id}: ${(err as Error).message}`); - throw new Error(`Agent hook setup failed: ${(err as Error).message}`, { cause: err }); - } - - // Write the PTY shim files into the workspace-specific directory. - // An SSH workspace's shim serves local processes — its purpose is not remote PATH control but - // injecting env/args when a local PTY spawns. On failure, warn gracefully. - try { - await this.writeShimFiles(meta.id); - } catch (shimErr) { - log.warn( - `shim file write failed for ${meta.id}; shell PATH priority may be degraded: ${(shimErr as Error).message}`, - ); - } - - if (!this.isLiveContext(meta.id, ctx)) { - disposeLifecycleListener(); - // remove() already deleted the shim dir; this boot rewrote it. - this.removeShimDirQuietly(meta.id); - throw createWorkspaceRemovedError(meta.id); + bootstrap.dispose?.(); + if (!this.sshReauth.has(meta.id)) this.broadcastConnectionStatus(meta.id, "error"); + throw error; } + installed = true; const provider = createFsProvider(providerMeta, channel); ctx.setFsProvider(provider, () => { disposeLifecycleListener(); @@ -1763,6 +1765,8 @@ export class WorkspaceManager { return; } + this.clearDegradedRecovery(workspaceId); + // ── Transient quality events ────────────────────────────────────────── if (event.type === "degraded") { this.broadcastConnectionStatus(workspaceId, "unstable"); @@ -1770,9 +1774,6 @@ export class WorkspaceManager { } if (event.type === "degraded-recovered") { - // Cancel any pending debounce timer so rapid transitions don't stack. - const pending = this.degradedRecoveryTimers.get(workspaceId); - if (pending) clearTimeout(pending); // ~1 s debounce recommended by designer (plan issue 5) to prevent flapping. const timer = setTimeout(() => { this.degradedRecoveryTimers.delete(workspaceId); @@ -1787,12 +1788,6 @@ export class WorkspaceManager { // ── Reconnecting: keep references, update UI ────────────────────────── if (event.type === "reconnecting") { - // Cancel any pending degraded-recovery timer: we're reconnecting now. - const pendingTimer = this.degradedRecoveryTimers.get(workspaceId); - if (pendingTimer) { - clearTimeout(pendingTimer); - this.degradedRecoveryTimers.delete(workspaceId); - } this.broadcastConnectionStatus(workspaceId, "reconnecting"); return; } @@ -1824,14 +1819,8 @@ export class WorkspaceManager { this.tearDownSshProvider(workspaceId, ctx); - // ── Auto re-authentication (plan issue 6) ───────────────────────────── - // Conditions: auth-failed terminal failure + interactive auth + context - // and meta still present (CRITICAL: re-confirm after tearDown) + no - // concurrent reauth in flight. - if (isAuthFailure && isInteractive && !this.reauthInFlight.has(workspaceId)) { - void this.scheduleReauth(workspaceId); - // PTY hold state is preserved — scheduleReauth owns the resolution - // (restoreAfterReauth on success, releaseHeld on all non-reauth exits). + if (isAuthFailure && isInteractive && this.isLiveContext(workspaceId, ctx)) { + this.startSshReauth(ctx); return; } @@ -1847,12 +1836,6 @@ export class WorkspaceManager { this.sshChannels.delete(workspaceId); this.sshBootstraps.delete(workspaceId); this.sshProviderReady.delete(workspaceId); - // Cancel any pending degraded-recovery timer. - const pendingTimer = this.degradedRecoveryTimers.get(workspaceId); - if (pendingTimer) { - clearTimeout(pendingTimer); - this.degradedRecoveryTimers.delete(workspaceId); - } // Stale hookInfo is invalid once the channel dies — the next boot fills it again. this.hookInfoByWorkspace.delete(workspaceId); ctx.setFsProvider(createInitialFsProvider(ctx.getMeta())); @@ -1862,97 +1845,80 @@ export class WorkspaceManager { }); } - /** - * Schedules (or immediately starts) an automatic SSH re-authentication - * attempt after an auth-failed terminal failure on an interactive workspace. - * - * Backoff schedule (plan issue 6): - * attempt 0 → immediate (0 ms) - * attempt 1 → 5 000 ms - * attempt 2 → 30 000 ms - * attempt 3 → give up, surface error - * - * Guards: - * - `reauthInFlight` prevents concurrent prompts (including manual Connect). - * - ctx/meta re-confirmed inside the scheduled callback (CRITICAL: prevents - * re-booting a workspace that was removed while the timer was pending). - * - ssh.auth-cancelled → disconnected (no retry loop). - */ - private async scheduleReauth(workspaceId: string): Promise { - const attempts = this.reauthAttempts.get(workspaceId) ?? 0; - const BACKOFF_MS = [0, 5_000, 30_000]; - - if (attempts >= BACKOFF_MS.length) { - // Exhausted retries — surface permanent error, release held sessions. - log.warn(`reauth exhausted for ${workspaceId} after ${attempts} attempts`); - this.broadcastConnectionStatus(workspaceId, "error"); - this.reauthAttempts.delete(workspaceId); - this.ptyReleaseHeld?.(workspaceId); - return; - } - - const delayMs = BACKOFF_MS[attempts]; - this.reauthInFlight.add(workspaceId); - - const attemptReauth = async (): Promise => { - // CRITICAL: re-confirm ctx/meta existence before attempting re-boot. - const ctx = this.contexts.get(workspaceId); - if (!ctx) { - this.reauthInFlight.delete(workspaceId); - this.reauthAttempts.delete(workspaceId); - // Workspace gone — release any still-held sessions. - this.ptyReleaseHeld?.(workspaceId); - return; - } - const meta = ctx.getMeta(); - if (meta.location.kind !== "ssh" || meta.location.authMode !== "interactive") { - this.reauthInFlight.delete(workspaceId); - this.reauthAttempts.delete(workspaceId); - this.ptyReleaseHeld?.(workspaceId); - return; + /** Cancels a delayed transition back to connected. */ + private clearDegradedRecovery(workspaceId: string): void { + clearTimeout(this.degradedRecoveryTimers.get(workspaceId)); + this.degradedRecoveryTimers.delete(workspaceId); + } + + /** Owns the held PTYs until automatic SSH reauthentication is resolved. */ + private startSshReauth(ctx: WorkspaceContext): void { + const { id } = ctx.getMeta(); + if (this.sshReauth.has(id)) return; + const controller = new AbortController(); + const ready = Promise.resolve() + .then(() => this.retrySshReauth(ctx, controller.signal)) + .then( + () => { + if (controller.signal.aborted) throw createWorkspaceRemovedError(id); + this.sshReauth.delete(id); + this.ptyRestoreAfterReauth?.(id).catch((error: unknown) => { + log.warn(`restoreAfterReauth failed for ${id}: ${(error as Error).message}`); + }); + }, + (error: unknown) => { + if (controller.signal.aborted) throw createWorkspaceRemovedError(id); + this.sshReauth.delete(id); + const cancelled = (error as { code?: string }).code === "ssh.auth-cancelled"; + this.broadcastConnectionStatus(id, cancelled ? "disconnected" : "error"); + this.ptyReleaseHeld?.(id); + throw error; + }, + ); + this.sshReauth.set(id, { controller, ready }); + // Automatic recovery can run without any caller awaiting it. + void ready.catch(() => {}); + } + + /** Runs all attempts in order, keeping manual Connect on the same promise. */ + private async retrySshReauth(ctx: WorkspaceContext, signal: AbortSignal): Promise { + const { id } = ctx.getMeta(); + for (const [attempt, delay] of SSH_REAUTH_BACKOFF_MS.entries()) { + if (delay > 0 && !signal.aborted) { + await new Promise((resolve) => { + const finish = () => { + clearTimeout(timer); + signal.removeEventListener("abort", finish); + resolve(); + }; + const timer = setTimeout(finish, delay); + timer.unref?.(); + signal.addEventListener("abort", finish, { once: true }); + }); } - - this.reauthAttempts.set(workspaceId, attempts + 1); + if (signal.aborted) throw createWorkspaceRemovedError(id); try { - await this.ensureRemoteProviderReady(ctx); - // Success — reset attempt counter and trigger PTY session restore. - this.reauthAttempts.delete(workspaceId); - // restoreAfterReauth acquires the new channel, subscribes lifecycle, - // and runs session.list reconcile → replay/exit. Fire-and-forget: - // internal failures are logged inside restoreAfterReauth itself. - this.ptyRestoreAfterReauth?.(workspaceId).catch((err: unknown) => { - log.warn(`restoreAfterReauth failed for ${workspaceId}: ${(err as Error).message}`); - }); - } catch (err) { - // ssh.auth-cancelled: user explicitly cancelled — stop the retry loop - // and release held sessions. - const code = (err as { code?: string }).code; - if (code === "ssh.auth-cancelled") { - log.info(`reauth cancelled by user for ${workspaceId}`); - this.broadcastConnectionStatus(workspaceId, "disconnected"); - this.reauthAttempts.delete(workspaceId); - this.ptyReleaseHeld?.(workspaceId); - } else { - // Other failures (connect error, etc.) handled by the new lifecycle - // event from the fresh channel — don't double-broadcast here. Hold - // state is preserved so the next channel's lifecycle can restore it. - log.warn( - `reauth attempt ${attempts + 1} failed for ${workspaceId}: ${(err as Error).message}`, - ); + await this.ensureRemoteProviderReady(ctx, true); + return; + } catch (error) { + if (signal.aborted || (error as { code?: string }).code === "ssh.auth-cancelled") { + throw error; } - } finally { - this.reauthInFlight.delete(workspaceId); + log.warn(`reauth attempt ${attempt + 1} failed for ${id}: ${(error as Error).message}`); + if (attempt === SSH_REAUTH_BACKOFF_MS.length - 1) throw error; } - }; - - if (delayMs === 0) { - void attemptReauth(); - } else { - const timer = setTimeout(() => void attemptReauth(), delayMs); - timer.unref?.(); } } + /** Stops pending retries and releases held PTYs when the workspace closes. */ + private cancelSshReauth(workspaceId: string): void { + const recovery = this.sshReauth.get(workspaceId); + if (!recovery) return; + this.sshReauth.delete(workspaceId); + recovery.controller.abort(); + this.ptyReleaseHeld?.(workspaceId); + } + /** * Handles terminal local channel lifecycle events and restores the inert provider. */ diff --git a/src/main/infra/agent/ssh/auth-prompt.ts b/src/main/infra/agent/ssh/auth-prompt.ts index 668314efe..13b5c4c77 100644 --- a/src/main/infra/agent/ssh/auth-prompt.ts +++ b/src/main/infra/agent/ssh/auth-prompt.ts @@ -7,6 +7,10 @@ import { } from "../../../../shared/ssh/auth-prompt"; import { register, validateArgs } from "../../ipc-router"; +import { AuthCancelledError } from "./auth"; + +export { AuthCancelledError } from "./auth"; + type BroadcastFn = (channelName: string, event: string, args: unknown) => void; interface PendingSshAuthPrompt { @@ -16,14 +20,6 @@ interface PendingSshAuthPrompt { readonly reject: (error: AuthCancelledError) => void; } -/** Error raised when the renderer cancels an active SSH authentication prompt. */ -export class AuthCancelledError extends Error { - constructor(promptId: string) { - super(`SSH authentication prompt cancelled: ${promptId}`); - this.name = "AuthCancelledError"; - } -} - /** * Coordinates main-initiated SSH authentication prompts with renderer replies. * Requests are keyed by `promptId`, so unrelated IPC request ids cannot resolve diff --git a/src/main/infra/agent/ssh/auth-pty.ts b/src/main/infra/agent/ssh/auth-pty.ts index 60ccac59a..f6d11e318 100644 --- a/src/main/infra/agent/ssh/auth-pty.ts +++ b/src/main/infra/agent/ssh/auth-pty.ts @@ -2,6 +2,7 @@ import type { IPty } from "node-pty"; import type { SshAuthPrompt, SshAuthResponse } from "../../../../shared/ssh/auth-prompt"; import type { SshErrorCode } from "../../../../shared/ssh/errors"; import { createSshError } from "../pipe"; +import { AuthCancelledError } from "./auth"; import { buildSshControlMasterArgs, createSshControlMaster, @@ -110,7 +111,12 @@ export function authenticateSshControlMaster( } throw createSshError("ssh.auth-failed"); } catch (error) { - failAuth(createSshError("ssh.auth-failed", error)); + failAuth( + createSshError( + error instanceof AuthCancelledError ? "ssh.auth-cancelled" : "ssh.auth-failed", + error, + ), + ); } finally { promptInFlight = false; } diff --git a/src/main/infra/agent/ssh/auth.ts b/src/main/infra/agent/ssh/auth.ts index ce5121672..e08245380 100644 --- a/src/main/infra/agent/ssh/auth.ts +++ b/src/main/infra/agent/ssh/auth.ts @@ -9,3 +9,11 @@ import { classifyStderrLine } from "./stderr-patterns"; export function classifyAuthLine(line: string): SshErrorCode | null { return classifyStderrLine(line); } + +/** Error raised when the renderer cancels an active SSH authentication prompt. */ +export class AuthCancelledError extends Error { + constructor(promptId: string) { + super(`SSH authentication prompt cancelled: ${promptId}`); + this.name = "AuthCancelledError"; + } +} diff --git a/src/main/infra/agent/ssh/ssh2/connect.ts b/src/main/infra/agent/ssh/ssh2/connect.ts index 91a627a07..eae39237f 100644 --- a/src/main/infra/agent/ssh/ssh2/connect.ts +++ b/src/main/infra/agent/ssh/ssh2/connect.ts @@ -38,6 +38,7 @@ import type { import type { SshAuthPrompt } from "../../../../../shared/ssh/auth-prompt"; import type { SshErrorCode } from "../../../../../shared/ssh/errors"; import { createSshError } from "../../pipe"; +import { AuthCancelledError } from "../auth"; import type { SshAuthPromptHandler } from "../auth-pty"; import { resolveSshHostConfig, type SshHostConfig, type SshTarget } from "./config"; import { @@ -238,6 +239,9 @@ function authenticate( disarmTimer(); try { return await promptHandler(prompt); + } catch (error) { + if (error instanceof AuthCancelledError) fail("ssh.auth-cancelled", error); + throw error; } finally { promptsOpen -= 1; if (promptsOpen === 0 && !settled) armTimer(); diff --git a/tests/unit/main/agent/ssh-auth-pty.test.ts b/tests/unit/main/agent/ssh-auth-pty.test.ts index 202426f0f..204dd7348 100644 --- a/tests/unit/main/agent/ssh-auth-pty.test.ts +++ b/tests/unit/main/agent/ssh-auth-pty.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "bun:test"; import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { EventEmitter } from "node:events"; +import { AuthCancelledError } from "../../../../src/main/infra/agent/ssh/auth"; import { authenticateSshControlMaster } from "../../../../src/main/infra/agent/ssh/auth-pty"; import type { SshAuthPrompt } from "../../../../src/shared/ssh/auth-prompt"; @@ -181,14 +182,14 @@ describe("authenticateSshControlMaster", () => { await expect(promise).resolves.toMatchObject({ controlPath: "/tmp/nexus-test.sock" }); }); - it("kills the PTY, reports ssh.auth-failed, and unlinks the socket when cancelled", async () => { + it("kills the PTY, reports ssh.auth-cancelled, and unlinks the socket when cancelled", async () => { const pty = new FakePty(); const unlinkCalls: string[] = []; const disposeSpawnCalls: string[][] = []; const promise = authenticateSshControlMaster( { host: "127.0.0.1", user: "alice", port: 2223, controlPath: "/tmp/nexus-test.sock" }, async () => { - throw new Error("cancelled"); + throw new AuthCancelledError("test-prompt"); }, { promptIdPrefix: "prompt-1", @@ -206,7 +207,7 @@ describe("authenticateSshControlMaster", () => { ); pty.emitData("alice@127.0.0.1's password:"); - await expect(promise).rejects.toMatchObject({ code: "ssh.auth-failed" }); + await expect(promise).rejects.toMatchObject({ code: "ssh.auth-cancelled" }); expect(pty.killed).toEqual([undefined]); expect(disposeSpawnCalls[0]).toContain("-O"); diff --git a/tests/unit/main/agent/ssh2-client.test.ts b/tests/unit/main/agent/ssh2-client.test.ts index 85a638c81..05c0e6a80 100644 --- a/tests/unit/main/agent/ssh2-client.test.ts +++ b/tests/unit/main/agent/ssh2-client.test.ts @@ -3,11 +3,13 @@ * authentication prompts, and commands sharing one connection as they would * a ControlMaster. */ + import { afterEach, describe, expect, it, setDefaultTimeout } from "bun:test"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { type Connection, Server, utils } from "ssh2"; +import { AuthCancelledError } from "../../../../src/main/infra/agent/ssh/auth"; import { buildSshArgs } from "../../../../src/main/infra/agent/ssh/master"; import type { SshHostConfig } from "../../../../src/main/infra/agent/ssh/ssh2/config"; import { connectSsh2 } from "../../../../src/main/infra/agent/ssh/ssh2/connect"; @@ -244,16 +246,16 @@ describe("connectSsh2", () => { ]); }); - it("fails as an authentication failure when the user cancels", async () => { + it("preserves explicit authentication cancellation", async () => { const t = await setup({ password: "pw" }); const cancelling = async (prompt: SshAuthPrompt): Promise => { if (prompt.kind === "host-key") return { kind: "host-key", promptId: prompt.promptId, trust: "yes" }; - throw new Error("cancelled"); + throw new AuthCancelledError("test-prompt"); }; await expect(connectSsh2(t.target, cancelling, t.dependencies)).rejects.toMatchObject({ - code: "ssh.auth-failed", + code: "ssh.auth-cancelled", }); }); diff --git a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts index 768a93c0a..c2041e127 100644 --- a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts +++ b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts @@ -49,14 +49,8 @@ type LifecycleCb = (event: { type: string; [k: string]: unknown }) => void; class StubChannel { readonly calls: Array<{ method: string; params: unknown }> = []; private readonly lifecycleListeners = new Set(); - private resolveReady!: () => void; - readonly ready: Promise; - - constructor() { - this.ready = new Promise((r) => { - this.resolveReady = r; - }); - } + private readonly handshake = Promise.withResolvers(); + readonly ready = this.handshake.promise; async call(method: string, params?: unknown): Promise { this.calls.push({ method, params: params ?? null }); @@ -79,7 +73,11 @@ class StubChannel { } resolveChannel(): void { - this.resolveReady(); + this.handshake.resolve(); + } + failHandshake(error: Error): void { + this.emitLifecycle({ type: "failure", error }); + this.handshake.reject(error); } dispose(): void {} } @@ -230,7 +228,12 @@ describe("acceptance 3: degraded lifecycle → unstable broadcast", () => { jest.advanceTimersByTime(999); expect(connectedAfterUnstable()).toBe(false); + channel.emitLifecycle({ type: "degraded" }); jest.advanceTimersByTime(1); + expect(connectedAfterUnstable()).toBe(false); + + channel.emitLifecycle({ type: "degraded-recovered" }); + jest.advanceTimersByTime(1000); expect(connectedAfterUnstable()).toBe(true); } finally { jest.useRealTimers(); @@ -422,104 +425,97 @@ describe("acceptance 4c: auth-cancelled → disconnected (no retry)", () => { // Acceptance 4d: 3 consecutive failures → error (give up) // --------------------------------------------------------------------------- -describe("acceptance 4d: reauth backoff — 3 attempts then error", () => { - test("after retries exhausted (reauthAttempts≥3) broadcasts error immediately", async () => { - const channel = new StubChannel(); - const sshBootstrap = mock(async () => ({ +describe("SSH reauthentication across bootstrap and ready failures", () => { + test.each([ + "exhausted", + "recovered", + "removed", + ] as const)("keeps PTYs held across failed attempts until %s", async (outcome) => { + const initial = new StubChannel(); + const next = new StubChannel(); + const last = new StubChannel(); + const ptyReleaseHeld = mock((_id: string) => {}); + const ptyRestoreAfterReauth = mock(async (_id: string) => {}); + const bootstrap = { remoteCommand: "exec agent", remoteHome: "/home/user", platform: { os: "linux" as const, arch: "amd64" as const }, uploaded: false, remoteBinDir: "/home/user/.nexus-code/bin", - controlPath: undefined, - dispose: undefined, - })); - - const sshChannelFactory = mock(() => channel); - const { manager, globalDb, broadcasts } = makeManager({ sshBootstrap, sshChannelFactory }); - const meta = makeSshMeta(manager); - const bootPromise = manager.getAgentChannel(meta.id); - channel.resolveChannel(); - await bootPromise; - - // Pre-seed reauthAttempts to 3 (exhausted). The next scheduleReauth call - // will immediately broadcast "error" and return (no timer, no new prompt). - const m = manager as unknown as { reauthAttempts: Map }; - m.reauthAttempts.set(meta.id, 3); - - const authFailedError = Object.assign(new Error("SSH auth failed"), { - code: "ssh.auth-failed", + }; + const sshBootstrap = mock(async () => bootstrap); + sshBootstrap.mockImplementationOnce(async () => bootstrap); + sshBootstrap.mockImplementationOnce(async () => { + throw Object.assign(new Error("Temporary SSH connection failure"), { + code: "ssh.connect-failed", + }); }); - channel.emitLifecycle({ type: "failure", error: authFailedError }); - - // scheduleReauth is async (void) — allow the microtask to complete. - await new Promise((r) => setTimeout(r, 0)); - - const statusBroadcasts = broadcasts - .filter((b) => b.channelName === "workspace" && b.event === "connectionChanged") - .map((b) => b.args as { status: string; workspaceId: string }); - const errorForWs = statusBroadcasts.filter( - (b) => b.workspaceId === meta.id && b.status === "error", - ); - expect(errorForWs.length).toBeGreaterThan(0); - - globalDb.close(); - }); -}); - -// --------------------------------------------------------------------------- -// Acceptance 5: ctx absent at reauth time → no action -// --------------------------------------------------------------------------- - -describe("acceptance 5: ctx absent guard in reauth", () => { - test("workspace removed before reauth timer fires → no boot attempt", async () => { - let bootCallCount = 0; - const channel = new StubChannel(); - const sshBootstrap = mock(async () => { - bootCallCount++; - return { - remoteCommand: "exec agent", - remoteHome: "/home/user", - platform: { os: "linux" as const, arch: "amd64" as const }, - uploaded: false, - remoteBinDir: "/home/user/.nexus-code/bin", - controlPath: undefined, - dispose: undefined, - }; + const factory = mock(() => next); + factory.mockImplementationOnce(() => initial); + factory.mockImplementationOnce(() => next); + factory.mockImplementationOnce(() => last); + const { manager, globalDb, broadcasts } = makeManager({ + sshBootstrap, + sshChannelFactory: factory, + ptyReleaseHeld, + ptyRestoreAfterReauth, }); - - const sshChannelFactory = mock(() => channel); - const { manager, globalDb } = makeManager({ sshBootstrap, sshChannelFactory }); const meta = makeSshMeta(manager); - const bootPromise = manager.getAgentChannel(meta.id); - channel.resolveChannel(); - await bootPromise; - expect(bootCallCount).toBe(1); - - // Seed reauthAttempts=1 so the backoff delay is 5 s (won't fire before remove). - const m = manager as unknown as { reauthAttempts: Map }; - m.reauthAttempts.set(meta.id, 1); - - const authFailedError = Object.assign(new Error("SSH auth failed"), { - code: "ssh.auth-failed", - }); - channel.emitLifecycle({ type: "failure", error: authFailedError }); - - // Remove the workspace immediately before the timer fires. - manager.remove(meta.id); - - // Wait longer than 5 s would be awkward in a unit test, but we can verify - // that the reauthInFlight was registered (timer was scheduled). - // We confirm the workspace context is gone, which is the CRITICAL guard. - const ctx = (manager as unknown as { contexts: Map }).contexts.get(meta.id); - expect(ctx).toBeUndefined(); + const boot = manager.getAgentChannel(meta.id); + initial.resolveChannel(); + await boot; - // Boot count should still be 1 — the 5 s delayed reauth won't fire in this - // test's timeframe (0 ms poll window). The guard check inside attemptReauth - // would bail out anyway since ctx is gone. - expect(bootCallCount).toBe(1); + const flush = () => new Promise((resolve) => setImmediate(resolve)); + const authFailed = Object.assign(new Error("SSH auth failed"), { code: "ssh.auth-failed" }); + jest.useFakeTimers(); + try { + initial.emitLifecycle({ type: "failure", error: authFailed }); + await flush(); + expect(sshBootstrap).toHaveBeenCalledTimes(2); + expect(ptyReleaseHeld).not.toHaveBeenCalled(); + + if (outcome === "removed") { + manager.remove(meta.id); + jest.advanceTimersByTime(35_000); + await flush(); + expect(sshBootstrap).toHaveBeenCalledTimes(2); + expect(ptyReleaseHeld).toHaveBeenCalledTimes(1); + expect(ptyRestoreAfterReauth).not.toHaveBeenCalled(); + return; + } - globalDb.close(); + jest.advanceTimersByTime(4_999); + await flush(); + expect(sshBootstrap).toHaveBeenCalledTimes(2); + jest.advanceTimersByTime(1); + await flush(); + expect(factory).toHaveBeenCalledTimes(2); + next.failHandshake(authFailed); + await flush(); + expect(ptyReleaseHeld).not.toHaveBeenCalled(); + + jest.advanceTimersByTime(30_000); + await flush(); + expect(factory).toHaveBeenCalledTimes(3); + if (outcome === "recovered") { + last.resolveChannel(); + await flush(); + expect(ptyRestoreAfterReauth).toHaveBeenCalledWith(meta.id); + expect(ptyReleaseHeld).not.toHaveBeenCalled(); + } else { + last.failHandshake(authFailed); + await flush(); + expect(ptyReleaseHeld).toHaveBeenCalledTimes(1); + expect(ptyRestoreAfterReauth).not.toHaveBeenCalled(); + expect(broadcasts.at(-1)?.args).toEqual({ workspaceId: meta.id, status: "error" }); + jest.advanceTimersByTime(60_000); + await flush(); + expect(sshBootstrap).toHaveBeenCalledTimes(4); + } + } finally { + jest.useRealTimers(); + globalDb.close(); + } }); }); @@ -576,45 +572,6 @@ describe("manager hold resolution: releaseHeld called on non-reauth exits", () = globalDb.close(); }); - test("backoff exhausted (reauthAttempts≥3) → manager calls releaseHeld", async () => { - const channel = new StubChannel(); - const releaseHeldCalls: string[] = []; - const sshBootstrap = mock(async () => ({ - remoteCommand: "exec agent", - remoteHome: "/home/user", - platform: { os: "linux" as const, arch: "amd64" as const }, - uploaded: false, - remoteBinDir: "/home/user/.nexus-code/bin", - controlPath: undefined, - dispose: undefined, - })); - - const sshChannelFactory = mock(() => channel); - const { manager, globalDb } = makeManager({ - sshBootstrap, - sshChannelFactory, - ptyReleaseHeld: (id) => releaseHeldCalls.push(id), - }); - const meta = makeSshMeta(manager); - const bootPromise = manager.getAgentChannel(meta.id); - channel.resolveChannel(); - await bootPromise; - - // Pre-seed exhausted attempts. - const m = manager as unknown as { reauthAttempts: Map }; - m.reauthAttempts.set(meta.id, 3); - - const authFailedError = Object.assign(new Error("SSH auth failed"), { - code: "ssh.auth-failed", - }); - channel.emitLifecycle({ type: "failure", error: authFailedError }); - await new Promise((r) => setTimeout(r, 0)); - - expect(releaseHeldCalls).toContain(meta.id); - - globalDb.close(); - }); - test("reauth success → manager calls restoreAfterReauth (not releaseHeld)", async () => { const restoreCalls: string[] = []; const releaseHeldCalls: string[] = []; From 51e8ceaaf70dcd353cf9fc3d5401b33b52bf97d8 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:38:05 +0900 Subject: [PATCH 034/208] fix(agent): bound remote bootstrap and ready handshakes Co-Authored-By: Claude Opus 5.5 --- src/main/features/workspace/ipc.ts | 1 + src/main/features/workspace/manager.ts | 20 ++++- src/main/index.ts | 4 +- .../channel/reconnecting-process-channel.ts | 8 +- src/main/infra/agent/collect-process.ts | 58 +++++++++++++ src/main/infra/agent/pipe.ts | 24 +++++- src/main/infra/agent/ssh/auth-prompt.ts | 21 ++++- src/main/infra/agent/ssh/auth-pty.ts | 38 ++++++--- src/main/infra/agent/ssh/channel.ts | 4 + src/main/infra/agent/ssh/credential-cache.ts | 10 ++- .../infra/agent/ssh/ssh-bootstrap/index.ts | 81 ++++++++++++++++--- .../agent/ssh/ssh-bootstrap/transport.ts | 45 +++++------ .../infra/agent/ssh/ssh-bootstrap/types.ts | 4 + src/main/infra/agent/ssh/ssh2/connect.ts | 55 ++++++++++--- src/main/infra/agent/ssh/ssh2/index.ts | 18 +++-- src/main/infra/agent/wsl/index.ts | 65 +++++++-------- .../workspace/use-ssh-auth-prompts.ts | 3 + src/shared/ipc/contract.ts | 1 + .../reconnect-channel-ready-lifecycle.test.ts | 45 +++++++++++ tests/unit/main/agent/ssh-auth-prompt.test.ts | 21 +++++ tests/unit/main/agent/ssh-auth-pty.test.ts | 33 +++++++- tests/unit/main/agent/ssh-bootstrap.test.ts | 56 ++++++++++++- tests/unit/main/agent/wsl.test.ts | 46 ++++++++++- .../manager-reattach-lifecycle.test.ts | 45 +++++++++++ tests/unit/main/workspace/manager-wsl.test.ts | 1 + .../workspace/SshAuthPromptDialog.test.tsx | 20 ++++- 26 files changed, 608 insertions(+), 119 deletions(-) create mode 100644 src/main/infra/agent/collect-process.ts diff --git a/src/main/features/workspace/ipc.ts b/src/main/features/workspace/ipc.ts index 9b6340db0..d2b910e4e 100644 --- a/src/main/features/workspace/ipc.ts +++ b/src/main/features/workspace/ipc.ts @@ -177,6 +177,7 @@ export function testSshHandler( identityFile: testArgs.identityFile, authMode: testArgs.authMode, remotePath: testArgs.remotePath, + signal, }); disposeBootstrap = bootstrap.dispose; throwIfAborted(signal); diff --git a/src/main/features/workspace/manager.ts b/src/main/features/workspace/manager.ts index d4e68c652..0b6c0fb40 100644 --- a/src/main/features/workspace/manager.ts +++ b/src/main/features/workspace/manager.ts @@ -374,6 +374,8 @@ export class WorkspaceManager { */ private readonly daemonStopsByLocation = new Map>(); private readonly sshBootstraps = new Map(); + /** Bootstrap still owns its SSH/WSL processes until it hands off the channel. */ + private readonly remoteBootstrapControllers = new Map(); private readonly sshProviderReady = new Map>(); // ControlMasters handed off from an SSH browse session, keyed by workspace // id, awaiting their first provider boot. Consumed by startRemoteProvider. @@ -479,6 +481,7 @@ export class WorkspaceManager { */ close(): void { for (const [id, ctx] of this.contexts) { + this.remoteBootstrapControllers.get(id)?.abort(createWorkspaceRemovedError(id)); this.cancelSshReauth(id); this.clearDegradedRecovery(id); ctx.close(); @@ -1134,6 +1137,7 @@ export class WorkspaceManager { // The PTY host emits pty.exit events for each live session so the // renderer's dead-terminal banner fires without waiting for IPC. this.ptySessionCloser?.(id); + this.remoteBootstrapControllers.get(id)?.abort(createWorkspaceRemovedError(id)); this.cancelSshReauth(id); this.clearDegradedRecovery(id); @@ -1509,9 +1513,13 @@ export class WorkspaceManager { // skip the interactive auth round entirely (no second password prompt). const adoptedMaster = this.adoptedSshMasters.get(meta.id); this.adoptedSshMasters.delete(meta.id); + const controller = new AbortController(); + this.remoteBootstrapControllers.set(meta.id, controller); + const signal = controller.signal; let bootstrap: EnsureRemoteAgentResult; - const onProgress = (event: LspBootstrapProgressEvent) => - this.broadcastConnectionProgress(meta.id, event); + const onProgress = (event: LspBootstrapProgressEvent) => { + if (!signal.aborted) this.broadcastConnectionProgress(meta.id, event); + }; try { bootstrap = location.kind === "wsl" @@ -1521,6 +1529,7 @@ export class WorkspaceManager { remotePath: location.remotePath, cachedRemoteArch: location.remoteArch, workspaceId: meta.id, + signal, }, { onProgress }, ) @@ -1539,6 +1548,7 @@ export class WorkspaceManager { // `~/.nexus-code/shim/shared/`, making them available to the // remote PTY's zsh `ZDOTDIR` / bash `--rcfile` activation. workspaceId: meta.id, + signal, }, { onProgress }, ); @@ -1550,6 +1560,8 @@ export class WorkspaceManager { if (!this.isLiveContext(meta.id, ctx)) throw createWorkspaceRemovedError(meta.id); if (!this.sshReauth.has(meta.id)) this.broadcastConnectionStatus(meta.id, "error"); throw error; + } finally { + this.remoteBootstrapControllers.delete(meta.id); } // ensureRemoteAgent only returns a dispose handle for a master it // authenticated itself. When we supplied an adopted master, wire its @@ -1577,6 +1589,10 @@ export class WorkspaceManager { ctx.setMeta(providerMeta); this.broadcastFn("workspace", "changed", providerMeta); } + if (!this.isLiveContext(meta.id, ctx)) { + bootstrap.dispose?.(); + throw createWorkspaceRemovedError(meta.id); + } let channel: SshChannel; try { channel = diff --git a/src/main/index.ts b/src/main/index.ts index 9323da6f8..f83fd7fef 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -225,8 +225,8 @@ const sshAuthPromptHub = new SshAuthPromptHub(forwardBroadcast); // Session-scoped credential cache: wraps the hub so successful passwords are // reused on automatic reconnects without re-prompting the user. The cache // invalidates itself on retry=true prompts (SSH "Permission denied, try again"). -const cachedSshAuthPromptHandler = createCachingAuthPromptHandler((prompt) => - sshAuthPromptHub.request(prompt), +const cachedSshAuthPromptHandler = createCachingAuthPromptHandler((prompt, signal) => + sshAuthPromptHub.request(prompt, signal), ); function wrappedBroadcast(channelName: string, event: string, args: unknown): void { diff --git a/src/main/infra/agent/channel/reconnecting-process-channel.ts b/src/main/infra/agent/channel/reconnecting-process-channel.ts index 8d8ac16a6..8add7a7fb 100644 --- a/src/main/infra/agent/channel/reconnecting-process-channel.ts +++ b/src/main/infra/agent/channel/reconnecting-process-channel.ts @@ -36,6 +36,7 @@ function getChannelLogger(): ReturnType { /** Max chars of a child's stderr tail to embed in one close-diagnostic line. */ const CLOSE_LOG_STDERR_TAIL_CHARS = 300; +const AGENT_READY_TIMEOUT_MS = 30_000; const DISPOSE_KILL_GRACE_MS = 100; const DEFAULT_MAX_PENDING_RECONNECT_CALLS = 32; const DEFAULT_RECONNECT_DELAY_MS = 100; @@ -229,6 +230,7 @@ export function createReconnectingProcessChannel( classifyStderr: options.classifyStderr, onTerminalError: (error) => handlePipeFailure(attempt, error, phase), requestTimeoutMs: options.requestTimeoutMs, + readyTimeoutMs: AGENT_READY_TIMEOUT_MS, expectedProtocolMajor: options.expectedProtocolMajor, onDegraded: () => { if (state === "disposed" || active !== attempt) return; @@ -329,8 +331,11 @@ export function createReconnectingProcessChannel( getChannelLogger().warn( `[${label}] agent pipe failure (phase=${phase}, pid=${attempt.child.pid}, code=${error.code}): ${error.message}`, ); + // A stalled handshake must be stopped before the next dialer starts. + // This process has no active RPCs to drain. + if (!attempt.ready && error.code === "transport.timeout") attempt.child.kill("SIGKILL"); + else terminateChild(attempt); if (phase === "reconnecting") { - terminateChild(attempt); if (options.isFatalReconnectError?.(error)) { consecutiveFatalFailures += 1; if (consecutiveFatalFailures >= MAX_CONSECUTIVE_FATAL_RECONNECT_FAILURES) { @@ -348,7 +353,6 @@ export function createReconnectingProcessChannel( state = "terminal"; terminalError = error; emitLifecycle({ type: "failure", error }); - terminateChild(attempt); } /** diff --git a/src/main/infra/agent/collect-process.ts b/src/main/infra/agent/collect-process.ts new file mode 100644 index 000000000..5828b307f --- /dev/null +++ b/src/main/infra/agent/collect-process.ts @@ -0,0 +1,58 @@ +import type { ChildProcessWithoutNullStreams } from "node:child_process"; +import { createSshError } from "./pipe"; + +interface CollectProcessOptions { + readonly name: string; + readonly input?: Buffer | string; + readonly signal?: AbortSignal; + readonly timeoutMs: number; +} + +/** Collects one transport command and kills it on cancellation or deadline. */ +export function collectProcess( + child: ChildProcessWithoutNullStreams, + { name, input, signal, timeoutMs }: CollectProcessOptions, +): Promise<{ stdout: Buffer; stderr: Buffer; code: number | null }> { + return new Promise((resolve, reject) => { + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + const timer = setTimeout(() => { + stop(createSshError("transport.timeout", new Error(`${name} exceeded ${timeoutMs}ms`))); + }, timeoutMs); + timer.unref?.(); + + /** Drops cancellation hooks once the caller has its result. */ + const cleanup = () => { + clearTimeout(timer); + signal?.removeEventListener("abort", abort); + }; + /** Keeps the original transport error while terminating the child. */ + const stop = (error: unknown) => { + cleanup(); + reject(error); + child.kill("SIGKILL"); + }; + const abort = () => stop(signal?.reason); + + child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk)); + child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk)); + child.on("error", (error) => { + cleanup(); + reject(error); + }); + child.on("close", (code) => { + cleanup(); + resolve({ stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr), code }); + }); + child.stdin.on("error", (error: NodeJS.ErrnoException) => { + // A child closing its input can still report the cause on stderr. + if (error.code !== "EPIPE" && error.code !== "ERR_STREAM_DESTROYED") stop(error); + }); + if (signal?.aborted) { + abort(); + } else { + signal?.addEventListener("abort", abort, { once: true }); + child.stdin.end(input); + } + }); +} diff --git a/src/main/infra/agent/pipe.ts b/src/main/infra/agent/pipe.ts index ee2faa557..a8b10fb85 100644 --- a/src/main/infra/agent/pipe.ts +++ b/src/main/infra/agent/pipe.ts @@ -172,6 +172,7 @@ export interface NdjsonPipeDependencies { readonly classifyStderr: StderrClassifier; readonly onTerminalError: (error: SshError) => void; readonly requestTimeoutMs?: number; + readonly readyTimeoutMs?: number; readonly expectedProtocolMajor?: string; /** * Called when the first heartbeat miss is detected (advertisedInterval × 1). @@ -233,7 +234,7 @@ export interface NdjsonPipe { /** Marks the pipe terminally failed from the orchestrator's side. */ fail(error: Error): void; /** - * Flushes buffered lines and reports whether ready had settled before close. + * Flushes buffered lines and reports whether the handshake had succeeded before close. * `stderrTail` carries the last few raw stderr lines (loader errors, panics, * unclassified warnings) so the orchestrator can attach them to the terminal * error's cause — the file log is then self-sufficient for diagnosis. @@ -286,6 +287,8 @@ export function createNdjsonPipe(deps: NdjsonPipeDependencies): NdjsonPipe { let resolveReady!: () => void; let rejectReady!: (error: Error) => void; let readySettled = false; + let readyReceived = false; + let readyTimer: NodeJS.Timeout | undefined; // Capabilities from the ready frame — populated once ready arrives. let capabilityMethods: readonly string[] | undefined; @@ -317,11 +320,14 @@ export function createNdjsonPipe(deps: NdjsonPipeDependencies): NdjsonPipe { resolveReady = () => { if (readySettled) return; readySettled = true; + readyReceived = true; + clearTimeout(readyTimer); resolve(); }; rejectReady = (error) => { if (readySettled) return; readySettled = true; + clearTimeout(readyTimer); reject(error); }; }); @@ -755,13 +761,25 @@ export function createNdjsonPipe(deps: NdjsonPipeDependencies): NdjsonPipe { notifyClose(): { wasReady: boolean; stderrTail: string } { stdoutLines.flush(); stderrLines.flush(); - const wasReady = readySettled; - if (!wasReady && deferredSpawnFailure !== null) { + const wasReady = readyReceived; + if (!readySettled && deferredSpawnFailure !== null) { selfFail(createSshError("server.spawn-failed", deferredSpawnFailure)); } return { wasReady, stderrTail: recentStderr.join(" | ") }; }, }; + const readyTimeoutMs = deps.readyTimeoutMs; + if (readyTimeoutMs !== undefined && !readySettled) { + readyTimer = setTimeout(() => { + selfFail( + createSshError( + "transport.timeout", + new Error(`Agent handshake exceeded ${readyTimeoutMs}ms`), + ), + ); + }, readyTimeoutMs); + readyTimer.unref?.(); + } return pipe; } diff --git a/src/main/infra/agent/ssh/auth-prompt.ts b/src/main/infra/agent/ssh/auth-prompt.ts index 13b5c4c77..7da201e78 100644 --- a/src/main/infra/agent/ssh/auth-prompt.ts +++ b/src/main/infra/agent/ssh/auth-prompt.ts @@ -34,18 +34,31 @@ export class SshAuthPromptHub { } /** Broadcasts a validated prompt and waits for the renderer response. */ - request(prompt: SshAuthPrompt): Promise { + request(prompt: SshAuthPrompt, signal?: AbortSignal): Promise { + if (signal?.aborted) return Promise.reject(signal.reason); const parsed = SshAuthPromptSchema.parse(prompt); if (this.pending.has(parsed.promptId)) { throw new Error(`Duplicate SSH authentication prompt id: ${parsed.promptId}`); } return new Promise((resolve, reject) => { + const abort = () => { + this.pending.delete(parsed.promptId); + reject(signal?.reason); + this.broadcast("sshAuth", "dismissed", { promptId: parsed.promptId }); + }; + signal?.addEventListener("abort", abort, { once: true }); this.pending.set(parsed.promptId, { promptId: parsed.promptId, prompt: parsed, - resolve, - reject, + resolve: (response) => { + signal?.removeEventListener("abort", abort); + resolve(response); + }, + reject: (error) => { + signal?.removeEventListener("abort", abort); + reject(error); + }, }); this.broadcast("sshAuth", "prompt", parsed); }); @@ -90,6 +103,6 @@ export function registerSshAuthPromptIpcChannels(hub: SshAuthPromptHub): void { cancel: (args) => hub.cancel(args), pending: () => hub.listPending(), }, - listen: { prompt: {} }, + listen: { prompt: {}, dismissed: {} }, }); } diff --git a/src/main/infra/agent/ssh/auth-pty.ts b/src/main/infra/agent/ssh/auth-pty.ts index f6d11e318..493eed4bd 100644 --- a/src/main/infra/agent/ssh/auth-pty.ts +++ b/src/main/infra/agent/ssh/auth-pty.ts @@ -19,7 +19,10 @@ const HOST_KEY_PROMPT_PATTERN = const FINGERPRINT_PATTERN = /([A-Z0-9]+) key fingerprint is:? (SHA256:[^\s.]+)/i; const DEFAULT_AUTH_TIMEOUT_MS = 30_000; -export type SshAuthPromptHandler = (prompt: SshAuthPrompt) => Promise; +export type SshAuthPromptHandler = ( + prompt: SshAuthPrompt, + signal?: AbortSignal, +) => Promise; export type SpawnPty = ( command: string, args: string[], @@ -32,6 +35,7 @@ export interface AuthenticateSshControlMasterDependencies { readonly unlink?: (path: string) => void; readonly promptIdPrefix?: string; readonly authTimeoutMs?: number; + readonly signal?: AbortSignal; } /** @@ -45,8 +49,10 @@ export function authenticateSshControlMaster( promptHandler: SshAuthPromptHandler, dependencies: AuthenticateSshControlMasterDependencies = {}, ): Promise { + const { signal } = dependencies; + if (signal?.aborted) return Promise.reject(signal.reason); if (dependencies.spawnPty === undefined && usesSsh2Client()) { - return authenticateSsh2Master(options, promptHandler); + return authenticateSsh2Master(options, promptHandler, { signal }); } const master = createSshControlMaster(options, { spawn: dependencies.spawn, @@ -54,12 +60,18 @@ export function authenticateSshControlMaster( }); const spawnPty = dependencies.spawnPty ?? defaultSpawnPty; const authTimeoutMs = dependencies.authTimeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS; - const ptyProcess = spawnPty("ssh", buildSshControlMasterArgs(master), { - name: "xterm-256color", - cols: 80, - rows: 24, - env: process.env, - }); + let ptyProcess: IPty; + try { + ptyProcess = spawnPty("ssh", buildSshControlMasterArgs(master), { + name: "xterm-256color", + cols: 80, + rows: 24, + env: process.env, + }); + } catch (error) { + master.dispose(); + return Promise.reject(error); + } const sessionPrefix = dependencies.promptIdPrefix ?? `ssh-auth:${master.controlPath}`; let buffer = ""; @@ -67,6 +79,8 @@ export function authenticateSshControlMaster( let promptInFlight = false; return new Promise((resolve, reject) => { + const prompts = new AbortController(); + const abort = () => failAuth(signal?.reason); const dataDisposable = ptyProcess.onData((chunk) => { buffer = trimAuthBuffer(buffer + chunk); void maybeHandlePrompt(); @@ -87,6 +101,8 @@ export function authenticateSshControlMaster( master.dispose(); reject(createSshError(classifyPtyExit(buffer))); }); + if (signal?.aborted) abort(); + else signal?.addEventListener("abort", abort, { once: true }); async function maybeHandlePrompt(): Promise { if (settled || promptInFlight) return; @@ -96,7 +112,7 @@ export function authenticateSshControlMaster( promptInFlight = true; disarmAuthTimer(); try { - const response = await promptHandler(prompt); + const response = await promptHandler(prompt, prompts.signal); if (settled) return; armAuthTimer(); if (response.kind === "password" && prompt.kind === "password") { @@ -136,7 +152,7 @@ export function authenticateSshControlMaster( authTimer = null; } - function failAuth(error: Error): void { + function failAuth(error: unknown): void { if (settled) return; cleanupListeners(); settled = true; @@ -146,6 +162,8 @@ export function authenticateSshControlMaster( } function cleanupListeners(): void { + signal?.removeEventListener("abort", abort); + prompts.abort(); disarmAuthTimer(); dataDisposable.dispose(); exitDisposable.dispose(); diff --git a/src/main/infra/agent/ssh/channel.ts b/src/main/infra/agent/ssh/channel.ts index 011929567..0f137e3b1 100644 --- a/src/main/infra/agent/ssh/channel.ts +++ b/src/main/infra/agent/ssh/channel.ts @@ -129,11 +129,13 @@ function createAuthenticatedSshChannel( let disposeInnerLifecycle: (() => void) | null = null; let disposeMaster: (() => void) | null = null; + const auth = new AbortController(); // Reached only when no controlPath was provided by the caller — i.e. the // bootstrap path was not used and we must authenticate our own ControlMaster. const ready = authenticateSshControlMaster(options, promptHandler, { ...dependencies.auth, spawn: dependencies.auth?.spawn ?? dependencies.spawn, + signal: auth.signal, }) .then((master) => { if (disposed) { @@ -161,6 +163,7 @@ function createAuthenticatedSshChannel( }) .catch((error) => { rejectPendingCalls(error); + if (disposed) throw error; emitLifecycle({ type: "failure", error: error instanceof Error ? error : createSshError("ssh.unknown", error), @@ -212,6 +215,7 @@ function createAuthenticatedSshChannel( dispose(): void { if (disposed) return; disposed = true; + auth.abort(createDisposedError()); rejectPendingCalls(createDisposedError()); disposeInnerLifecycle?.(); inner?.dispose(); diff --git a/src/main/infra/agent/ssh/credential-cache.ts b/src/main/infra/agent/ssh/credential-cache.ts index ead06eaa5..20cb52ea0 100644 --- a/src/main/infra/agent/ssh/credential-cache.ts +++ b/src/main/infra/agent/ssh/credential-cache.ts @@ -29,10 +29,14 @@ function credentialKey(prompt: Extract): st export function createCachingAuthPromptHandler(inner: SshAuthPromptHandler): SshAuthPromptHandler { const cache = new Map(); - return async function cachingAuthPromptHandler(prompt: SshAuthPrompt): Promise { + return async function cachingAuthPromptHandler( + prompt: SshAuthPrompt, + signal?: AbortSignal, + ): Promise { + signal?.throwIfAborted(); // Host-key prompts are never cached — always ask the user. if (prompt.kind !== "password") { - return inner(prompt); + return inner(prompt, signal); } const key = credentialKey(prompt); @@ -48,7 +52,7 @@ export function createCachingAuthPromptHandler(inner: SshAuthPromptHandler): Ssh } } - const response = await inner(prompt); + const response = await inner(prompt, signal); if (response.kind === "password" && response.value) { cache.set(key, response.value); } diff --git a/src/main/infra/agent/ssh/ssh-bootstrap/index.ts b/src/main/infra/agent/ssh/ssh-bootstrap/index.ts index 3c75093fa..d0dd8cd17 100644 --- a/src/main/infra/agent/ssh/ssh-bootstrap/index.ts +++ b/src/main/infra/agent/ssh/ssh-bootstrap/index.ts @@ -36,11 +36,7 @@ import { ZSHENV_CONTENT, ZSHRC_CONTENT, } from "../../runtimeDirs"; -import { - type AuthenticateSshControlMasterDependencies, - authenticateSshControlMaster, - type SshAuthPromptHandler, -} from "../auth-pty"; +import { authenticateSshControlMaster, type SshAuthPromptHandler } from "../auth-pty"; import { absoluteRemotePath, agentArtifactKey, @@ -73,6 +69,7 @@ import { LSP_BOOTSTRAP_PROGRESS_EVENT, type LspBootstrapProgressEvent, type LspBootstrapProgressPhase, + REMOTE_AGENT_BOOTSTRAP_TIMEOUT_MS, REMOTE_AGENT_MANIFEST, REMOTE_AGENT_PROTOCOL_MAJOR, REMOTE_AGENT_ROOT, @@ -126,7 +123,10 @@ interface ArtifactEnsureResult { // Process-wide deduplication of concurrent ensure() calls for the same // artifact on the same remote. Each key resolves to the in-flight promise // so multiple workspaces booting against the same host upload once. -const artifactLocks = new Map>(); +const artifactLocks = new Map< + string, + { ready: Promise; signal?: AbortSignal } +>(); /** * Ensures the agent binary is present at the canonical path on the remote. @@ -139,11 +139,31 @@ export async function ensureRemoteAgent( dependencies: SshBootstrapDependencies = {}, ): Promise { const context = await createBootstrapContext(options, dependencies); - const { runner, distDir, now, sshOptions, authenticatedMaster } = context; + const { distDir, now, authenticatedMaster } = context; + // Interactive authentication has its own timeout, paused for user input. + const deadline = new AbortController(); + const timer = setTimeout(() => { + deadline.abort( + createSshError( + "transport.timeout", + new Error(`Remote agent bootstrap exceeded ${REMOTE_AGENT_BOOTSTRAP_TIMEOUT_MS}ms`), + ), + ); + }, REMOTE_AGENT_BOOTSTRAP_TIMEOUT_MS); + timer.unref?.(); + const signal = options.signal + ? AbortSignal.any([options.signal, deadline.signal]) + : deadline.signal; + const sshOptions = { ...context.sshOptions, signal }; + const runner: SshBootstrapRunner = (command, args, input) => + untilAborted(() => context.runner(command, args, input, signal), signal); try { + signal.throwIfAborted(); const localManifest = AgentManifestSchema.parse( - JSON.parse(await fs.readFile(path.join(distDir, "manifest.json"), "utf8")), + JSON.parse( + await fs.readFile(path.join(distDir, "manifest.json"), { encoding: "utf8", signal }), + ), ); const platform = options.cachedRemoteArch ?? (await detectRemotePlatform(sshOptions, runner)); const binary = findAgentBinary(localManifest, platform); @@ -218,6 +238,7 @@ export async function ensureRemoteAgent( ? await ensureRemoteShimFiles(sshOptions, runner, remoteHome) : undefined; + signal.throwIfAborted(); // On success, ownership of a ControlMaster authenticated *here* passes to // the caller via `dispose`. When the caller supplied its own controlPath // (a reused master), we surface that path back but no dispose handle — @@ -241,7 +262,9 @@ export async function ensureRemoteAgent( // This function never returned, so the caller has no dispose handle. // Dispose the ControlMaster here before propagating the error. authenticatedMaster?.dispose(); - throw error; + throw signal.aborted ? signal.reason : error; + } finally { + clearTimeout(timer); } } @@ -420,6 +443,26 @@ export function buildRemoteAgentCommand( return `bash -lc ${singleQuoteShellArg(script)}`; } +/** Waits for a bootstrap step while allowing the caller to abandon the wait. */ +async function untilAborted(run: () => Promise, signal?: AbortSignal): Promise { + signal?.throwIfAborted(); + if (!signal) return run(); + let onAbort!: () => void; + const cancelled = new Promise((_resolve, reject) => { + onAbort = () => reject(signal.reason); + signal.addEventListener("abort", onAbort, { once: true }); + }); + try { + const result = Promise.resolve().then(() => { + signal.throwIfAborted(); + return run(); + }); + return await Promise.race([cancelled, result]); + } finally { + signal.removeEventListener("abort", onAbort); + } +} + /** * Resolves the dependency defaults and, when this is the first call against * this remote in interactive mode, opens the ControlMaster up front so every @@ -435,6 +478,7 @@ async function createBootstrapContext( readonly sshOptions: EnsureRemoteAgentOptions; readonly authenticatedMaster: Awaited> | null; }> { + options.signal?.throwIfAborted(); const runner = dependencies.runner ?? defaultRunner; const distDir = dependencies.distDir ?? getAgentDistDir(); const now = dependencies.now ?? (() => new Date()); @@ -444,7 +488,7 @@ async function createBootstrapContext( ? await authenticateSshControlMaster( options, dependencies.promptHandler as SshAuthPromptHandler, - dependencies.auth as AuthenticateSshControlMasterDependencies | undefined, + { ...dependencies.auth, signal: options.signal }, ) : null; const sshOptions = authenticatedMaster @@ -513,16 +557,27 @@ async function ensureRemoteArtifact( ): Promise { const lockKey = artifactLockKey(options, request.key, request.record.sha256); const existing = artifactLocks.get(lockKey); - if (existing) return existing; + if (existing) { + try { + return await untilAborted(() => existing.ready, options.signal); + } catch (error) { + // A cancelled installer releases the lock. A surviving workspace can + // take ownership with its own transport and remaining deadline. + if (existing.signal?.aborted && !options.signal?.aborted) { + return ensureRemoteArtifact(options, runner, now, request, onProgress); + } + throw error; + } + } const pending = ensureRemoteArtifactUnlocked(options, runner, now, request, onProgress).finally( () => { - if (artifactLocks.get(lockKey) === pending) { + if (artifactLocks.get(lockKey)?.ready === pending) { artifactLocks.delete(lockKey); } }, ); - artifactLocks.set(lockKey, pending); + artifactLocks.set(lockKey, { ready: pending, signal: options.signal }); return pending; } diff --git a/src/main/infra/agent/ssh/ssh-bootstrap/transport.ts b/src/main/infra/agent/ssh/ssh-bootstrap/transport.ts index 8a2432ee2..5728f9e87 100644 --- a/src/main/infra/agent/ssh/ssh-bootstrap/transport.ts +++ b/src/main/infra/agent/ssh/ssh-bootstrap/transport.ts @@ -8,13 +8,15 @@ import { createHash, randomBytes } from "node:crypto"; import fs from "node:fs/promises"; import path from "node:path"; +import { collectProcess } from "../../collect-process"; import { createSshError } from "../../pipe"; import { defaultSpawnSsh } from "../master"; -import type { - EnsureRemoteAgentOptions, - LspBootstrapProgressEvent, - SshBootstrapRunner, - SshBootstrapRunnerResult, +import { + type EnsureRemoteAgentOptions, + type LspBootstrapProgressEvent, + REMOTE_AGENT_BOOTSTRAP_TIMEOUT_MS, + type SshBootstrapRunner, + type SshBootstrapRunnerResult, } from "./types"; /** @@ -26,26 +28,23 @@ export async function defaultRunner( command: string, args: string[], input?: Buffer | string, + signal?: AbortSignal, ): Promise { - return new Promise((resolve, reject) => { - const child = defaultSpawnSsh(command, args, { - detached: false, - stdio: ["pipe", "pipe", "pipe"], - }); - const stdout: Buffer[] = []; - const stderr: Buffer[] = []; - child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk)); - child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk)); - child.on("error", reject); - child.on("close", (code) => { - const out = Buffer.concat(stdout).toString("utf8"); - const err = Buffer.concat(stderr).toString("utf8"); - if (code === 0) resolve({ stdout: out, stderr: err }); - else reject(createSshError("ssh.unknown", new Error(err || `${command} exited ${code}`))); - }); - if (input !== undefined) child.stdin.end(input); - else child.stdin.end(); + signal?.throwIfAborted(); + const child = defaultSpawnSsh(command, args, { + detached: false, + stdio: ["pipe", "pipe", "pipe"], }); + const { stdout, stderr, code } = await collectProcess(child, { + name: command, + input, + signal, + timeoutMs: REMOTE_AGENT_BOOTSTRAP_TIMEOUT_MS, + }); + const err = stderr.toString("utf8").trim(); + if (code !== 0) + throw createSshError("ssh.unknown", new Error(err || `${command} exited ${code}`)); + return { stdout: stdout.toString("utf8"), stderr: err }; } /** Runs one remote command through ssh with the standard transport args. */ diff --git a/src/main/infra/agent/ssh/ssh-bootstrap/types.ts b/src/main/infra/agent/ssh/ssh-bootstrap/types.ts index 5be38fbc4..ce6745296 100644 --- a/src/main/infra/agent/ssh/ssh-bootstrap/types.ts +++ b/src/main/infra/agent/ssh/ssh-bootstrap/types.ts @@ -16,6 +16,8 @@ import type { SshMasterOptions } from "../master"; // bricking every local workspace — see the envelope.ts comment.) export const REMOTE_AGENT_PROTOCOL_MAJOR = AGENT_PROTOCOL_VERSION; export const REMOTE_AGENT_VERSION = "0.1.0"; +/** Maximum duration of agent installation after authentication. */ +export const REMOTE_AGENT_BOOTSTRAP_TIMEOUT_MS = 120_000; /** * Root path on the remote host where the agent is installed. @@ -59,6 +61,7 @@ export interface LspBootstrapProgressEvent { export interface EnsureRemoteAgentOptions extends Omit { readonly remotePath: string; + readonly signal?: AbortSignal; readonly cachedRemoteArch?: RemoteAgentPlatform; readonly authMode?: "interactive" | "key-only"; /** @@ -126,6 +129,7 @@ export type SshBootstrapRunner = ( command: string, args: string[], input?: Buffer | string, + signal?: AbortSignal, ) => Promise; export interface SshBootstrapDependencies { diff --git a/src/main/infra/agent/ssh/ssh2/connect.ts b/src/main/infra/agent/ssh/ssh2/connect.ts index eae39237f..a52e94ff3 100644 --- a/src/main/infra/agent/ssh/ssh2/connect.ts +++ b/src/main/infra/agent/ssh/ssh2/connect.ts @@ -60,6 +60,7 @@ const PASSPHRASE_ATTEMPTS = 3; export interface ConnectSsh2Dependencies { readonly resolveConfig?: (target: SshTarget) => Promise; readonly connectTimeoutMs?: number; + readonly signal?: AbortSignal; } /** An open connection and the jump hosts and proxy process it runs through. */ @@ -78,13 +79,17 @@ export async function connectSsh2( dependencies: ConnectSsh2Dependencies = {}, ): Promise { const resolveConfig = dependencies.resolveConfig ?? ((t: SshTarget) => resolveSshHostConfig(t)); + const { signal } = dependencies; + signal?.throwIfAborted(); const config = await resolveConfig(target); + signal?.throwIfAborted(); const hops: Ssh2Connection[] = []; let proxy: ChildProcess | null = null; const endAll = (): void => { proxy?.kill(); for (const hop of [...hops].reverse()) hop.end(); }; + signal?.addEventListener("abort", endAll, { once: true }); try { let sock: Duplex | undefined; if (config.proxyJump.length > 0) { @@ -93,9 +98,10 @@ export async function connectSsh2( for (const jump of config.proxyJump) { const hop = await connectThrough(parseJumpHost(jump), via, promptHandler, dependencies); hops.push(hop); + signal?.throwIfAborted(); via = hop; } - sock = await forwardTo(via as Ssh2Connection, config.hostname, config.port); + sock = await forwardTo(via as Ssh2Connection, config.hostname, config.port, signal); } else if (config.proxyCommand !== null) { proxy = spawnProxyCommand(config); sock = proxySocket(proxy); @@ -113,6 +119,8 @@ export async function connectSsh2( } catch (error) { endAll(); throw error; + } finally { + signal?.removeEventListener("abort", endAll); } } @@ -126,7 +134,7 @@ async function connectThrough( const resolveConfig = dependencies.resolveConfig ?? ((t: SshTarget) => resolveSshHostConfig(t)); // A jump host's own ProxyJump is not followed; it is reached through the one before it. const config = { ...(await resolveConfig(target)), proxyJump: [], proxyCommand: null }; - const sock = await forwardTo(via, config.hostname, config.port); + const sock = await forwardTo(via, config.hostname, config.port, dependencies.signal); const client = await authenticate(config, sock, promptHandler, dependencies); return { client, config, end: () => client.end() }; } @@ -149,14 +157,25 @@ export function parseJumpHost(spec: string): SshTarget { return { host, user: user || undefined, port }; } -function forwardTo(via: Ssh2Connection, hostname: string, port: number): Promise { +/** Opens a forwarding stream without keeping a cancelled jump attempt alive. */ +function forwardTo( + via: Ssh2Connection, + hostname: string, + port: number, + signal?: AbortSignal, +): Promise { return new Promise((resolve, reject) => { + signal?.throwIfAborted(); + const abort = () => reject(signal?.reason); + signal?.addEventListener("abort", abort, { once: true }); via.client.forwardOut("127.0.0.1", 0, hostname, port, (error, stream) => { + signal?.removeEventListener("abort", abort); if (error) { reject(createSshError("ssh.connect-failed", error)); return; } - resolve(stream); + if (signal?.aborted) stream.destroy(); + else resolve(stream); }); }); } @@ -214,6 +233,8 @@ function authenticate( // ssh2 is loaded on first use: only the Windows SSH path needs it. // eslint-disable-next-line @typescript-eslint/no-require-imports const { Client: ClientClass } = require("ssh2") as typeof import("ssh2"); + const { signal } = dependencies; + signal?.throwIfAborted(); const client = new ClientClass(); const timeoutMs = dependencies.connectTimeoutMs ?? config.connectTimeoutMs ?? CONNECT_TIMEOUT_MS; @@ -222,6 +243,7 @@ function authenticate( let hostKeyRefused: string | null = null; let timer: ReturnType | null = null; let promptsOpen = 0; + const prompts = new AbortController(); const armTimer = (): void => { disarmTimer(); @@ -238,7 +260,7 @@ function authenticate( promptsOpen += 1; disarmTimer(); try { - return await promptHandler(prompt); + return await promptHandler(prompt, prompts.signal); } catch (error) { if (error instanceof AuthCancelledError) fail("ssh.auth-cancelled", error); throw error; @@ -250,17 +272,25 @@ function authenticate( // The error is made only for a connection still opening: making an // SshError logs it. const fail = (code: SshErrorCode, cause: unknown): void => { + if (!settled) stop(createSshError(code, cause)); + }; + const stop = (error: unknown): void => { if (settled) return; + settle(); + client.end(); + reject(error); + }; + const abort = () => stop(signal?.reason); + const settle = (): void => { settled = true; disarmTimer(); - client.end(); - reject(createSshError(code, cause)); + prompts.abort(); + signal?.removeEventListener("abort", abort); }; client.once("ready", () => { if (settled) return; - settled = true; - disarmTimer(); + settle(); resolve(client); }); // Kept for the connection's life: an error with no listener would throw. @@ -299,7 +329,12 @@ function authenticate( ...(config.forwardAgent !== null ? { agent: config.forwardAgent, agentForward: true } : {}), }; armTimer(); - client.connect(connectConfig); + signal?.addEventListener("abort", abort, { once: true }); + try { + client.connect(connectConfig); + } catch (error) { + stop(error); + } }); } diff --git a/src/main/infra/agent/ssh/ssh2/index.ts b/src/main/infra/agent/ssh/ssh2/index.ts index 9c8884103..42abbb03d 100644 --- a/src/main/infra/agent/ssh/ssh2/index.ts +++ b/src/main/infra/agent/ssh/ssh2/index.ts @@ -39,7 +39,7 @@ export function usesSsh2Client(env: NodeJS.ProcessEnv = process.env): boolean { /** One authenticated connection that commands share, opened again when it drops. */ class SharedConnection { private current: Promise | null = null; - private disposed = false; + private readonly lifetime = new AbortController(); constructor( private readonly target: SshTarget, @@ -48,16 +48,22 @@ class SharedConnection { ) {} client(): Promise { - if (this.disposed) return Promise.reject(new Error("the ssh2 connection was closed")); + if (this.lifetime.signal.aborted) return Promise.reject(this.lifetime.signal.reason); if (this.current === null) { - const opening = connectSsh2(this.target, this.promptHandler, this.dependencies); + const signal = this.dependencies.signal + ? AbortSignal.any([this.dependencies.signal, this.lifetime.signal]) + : this.lifetime.signal; + const opening = connectSsh2(this.target, this.promptHandler, { + ...this.dependencies, + signal, + }); this.current = opening; opening.then( (connection) => { connection.client.on("close", () => { if (this.current === opening) this.current = null; }); - if (this.disposed) connection.end(); + if (signal.aborted) connection.end(); }, () => { if (this.current === opening) this.current = null; @@ -68,8 +74,8 @@ class SharedConnection { } dispose(): void { - if (this.disposed) return; - this.disposed = true; + if (this.lifetime.signal.aborted) return; + this.lifetime.abort(); const current = this.current; this.current = null; void current?.then( diff --git a/src/main/infra/agent/wsl/index.ts b/src/main/infra/agent/wsl/index.ts index 4c3e628bc..f857e3fec 100644 --- a/src/main/infra/agent/wsl/index.ts +++ b/src/main/infra/agent/wsl/index.ts @@ -12,6 +12,7 @@ import { type AgentReconnectOptions, createReconnectingProcessChannel, } from "../channel/reconnecting-process-channel"; +import { collectProcess } from "../collect-process"; import { createSshError } from "../pipe"; import { formatCloseDiagnostic } from "../ssh/channel"; import { @@ -23,10 +24,11 @@ import { REMOTE_AGENT_PROTOCOL_MAJOR, type RemoteAgentPlatform, type SshBootstrapRunner, - type SshBootstrapRunnerResult, } from "../ssh/ssh-bootstrap"; const WSL_EXE = "wsl.exe"; +const WSL_COMMAND_TIMEOUT_MS = 120_000; +const WSL_LIST_TIMEOUT_MS = 10_000; /** Starts `argv` in `distro`, in the distribution user's home. */ export type SpawnWslProcess = ( @@ -38,6 +40,7 @@ export interface WslAgentOptions { readonly distro: string; /** Absolute path inside the distribution; the agent's root. */ readonly remotePath: string; + readonly signal?: AbortSignal; /** Installs the workspace's shell shim files too, as for SSH. */ readonly workspaceId?: string; readonly cachedRemoteArch?: RemoteAgentPlatform; @@ -89,26 +92,6 @@ export function decodeWslOutput(buffer: Buffer): string { return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text; } -function collect( - child: ChildProcessWithoutNullStreams, - input?: Buffer | string, -): Promise { - return new Promise((resolve, reject) => { - const stdout: Buffer[] = []; - const stderr: Buffer[] = []; - child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk)); - child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk)); - child.on("error", (error) => reject(createSshError("transport.unknown", error))); - child.on("close", (code) => { - const out = Buffer.concat(stdout).toString("utf8"); - const err = decodeWslOutput(Buffer.concat(stderr)).trim(); - if (code === 0) resolve({ stdout: out, stderr: err }); - else reject(createSshError("transport.unknown", new Error(err || `wsl.exe exited ${code}`))); - }); - child.stdin.end(input); - }); -} - /** * Runs the SSH bootstrap's remote steps in `distro`. The bootstrap hands * each step over as `ssh -- `; the command @@ -120,12 +103,27 @@ export function createWslBootstrapRunner( distro: string, spawnImpl: SpawnWslProcess = defaultSpawnWsl, ): SshBootstrapRunner { - return (command, args, input) => { + return async (command, args, input, signal) => { if (command !== "ssh") { - return Promise.reject(new Error(`${command} is not used in WSL`)); + throw new Error(`${command} is not used in WSL`); } const remoteCommand = args[args.length - 1] ?? ""; - return collect(spawnImpl(distro, ["sh", "-c", remoteCommand]), input); + signal?.throwIfAborted(); + const child = spawnImpl(distro, ["sh", "-c", remoteCommand]); + const { stdout, stderr, code } = await collectProcess(child, { + name: WSL_EXE, + input, + signal, + timeoutMs: WSL_COMMAND_TIMEOUT_MS, + }).catch((error: unknown) => { + if (signal?.aborted || (error as { code?: string }).code === "transport.timeout") throw error; + throw createSshError("transport.unknown", error); + }); + const err = decodeWslOutput(stderr).trim(); + if (code !== 0) { + throw createSshError("transport.unknown", new Error(err || `wsl.exe exited ${code}`)); + } + return { stdout: stdout.toString("utf8"), stderr: err }; }; } @@ -135,6 +133,7 @@ function bootstrapOptions(options: WslAgentOptions) { host: `wsl:${options.distro}`, authMode: "key-only" as const, remotePath: options.remotePath, + signal: options.signal, cachedRemoteArch: options.cachedRemoteArch, workspaceId: options.workspaceId, }; @@ -229,15 +228,13 @@ export function listWslDistros( ); } -function runWslExe(args: readonly string[]): Promise { - return new Promise((resolve, reject) => { - const child = spawn(WSL_EXE, [...args], { windowsHide: true, env: wslEnv() }); - const stdout: Buffer[] = []; - child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk)); - child.on("error", reject); - child.on("close", (code) => { - if (code === 0) resolve(Buffer.concat(stdout)); - else reject(new Error(`wsl.exe exited ${code}`)); - }); +/** Runs WSL discovery with the same child ownership as bootstrap commands. */ +export async function runWslExe(args: readonly string[], spawnImpl = spawn): Promise { + const child = spawnImpl(WSL_EXE, [...args], { windowsHide: true, env: wslEnv() }); + const { stdout, code } = await collectProcess(child, { + name: WSL_EXE, + timeoutMs: WSL_LIST_TIMEOUT_MS, }); + if (code !== 0) throw new Error(`wsl.exe exited ${code}`); + return stdout; } diff --git a/src/renderer/components/workspace/use-ssh-auth-prompts.ts b/src/renderer/components/workspace/use-ssh-auth-prompts.ts index da1990117..5d77823f5 100644 --- a/src/renderer/components/workspace/use-ssh-auth-prompts.ts +++ b/src/renderer/components/workspace/use-ssh-auth-prompts.ts @@ -76,6 +76,8 @@ export function installSshAuthPromptListeners(listen: typeof ipcListen = ipcList enqueuePrompt(prompt); }); + const unlistenDismissed = listen("sshAuth", "dismissed", ({ promptId }) => clearPrompt(promptId)); + // Track held/restored/expired so we know which prompts are reattach-context. const unlistenHeld = listen("pty", "held", (args) => { heldWorkspaceIds.add(args.workspaceId); @@ -91,6 +93,7 @@ export function installSshAuthPromptListeners(listen: typeof ipcListen = ipcList return () => { unlistenPrompt(); + unlistenDismissed(); unlistenHeld(); unlistenRestored(); unlistenExpired(); diff --git a/src/shared/ipc/contract.ts b/src/shared/ipc/contract.ts index c73a43985..76ae5faed 100644 --- a/src/shared/ipc/contract.ts +++ b/src/shared/ipc/contract.ts @@ -681,6 +681,7 @@ export const ipcContract = { }, listen: { prompt: listen(SshAuthPromptSchema), + dismissed: listen(SshAuthCancelArgsSchema), }, }, diff --git a/tests/unit/main/agent/reconnect-channel-ready-lifecycle.test.ts b/tests/unit/main/agent/reconnect-channel-ready-lifecycle.test.ts index c8f6e36d0..5a95ca62e 100644 --- a/tests/unit/main/agent/reconnect-channel-ready-lifecycle.test.ts +++ b/tests/unit/main/agent/reconnect-channel-ready-lifecycle.test.ts @@ -98,3 +98,48 @@ describe("no-epoch reconnect emits the ready lifecycle event", () => { } }); }); + +describe("agent ready deadline", () => { + it("rejects initial ready and terminates a silent process", async () => { + jest.useFakeTimers(); + try { + const { channel, children } = makeHarness(); + const ready = channel.ready.catch((error: unknown) => error); + jest.advanceTimersByTime(30_000); + expect(children[0]?.killed).toBe(true); + expect(await ready).toMatchObject({ code: "transport.timeout" }); + expect(children).toHaveLength(1); + channel.dispose(); + } finally { + jest.useRealTimers(); + } + }); + + it("terminates a silent reconnect attempt and resumes on the next ready", async () => { + jest.useFakeTimers(); + try { + const { channel, children } = makeHarness(); + const recovered = Promise.withResolvers(); + channel.onLifecycle((event) => { + if (event.type === "ready") recovered.resolve(); + }); + children[0]?.stdout.emitData('{"type":"ready"}\n'); + await channel.ready; + children[0]?.emit("close", 137, "SIGKILL"); + jest.advanceTimersByTime(1); + + const silent = children[1]; + expect(silent).toBeDefined(); + jest.advanceTimersByTime(30_000); + expect(silent?.killed).toBe(true); + silent?.emit("close", 137, "SIGKILL"); + jest.advanceTimersByTime(1); + expect(children).toHaveLength(3); + children[2]?.stdout.emitData('{"type":"ready"}\n'); + await recovered.promise; + channel.dispose(); + } finally { + jest.useRealTimers(); + } + }); +}); diff --git a/tests/unit/main/agent/ssh-auth-prompt.test.ts b/tests/unit/main/agent/ssh-auth-prompt.test.ts index b57fad87c..e6becda8e 100644 --- a/tests/unit/main/agent/ssh-auth-prompt.test.ts +++ b/tests/unit/main/agent/ssh-auth-prompt.test.ts @@ -68,6 +68,27 @@ describe("SshAuthPromptHub", () => { await expect(promise).rejects.toBeInstanceOf(AuthCancelledError); }); + it("dismisses only the prompt owned by an aborted connection", async () => { + const events: BroadcastEvent[] = []; + const hub = new SshAuthPromptHub((channelName, event, args) => { + events.push({ channelName, event, args }); + }); + const controller = new AbortController(); + const aborted = hub.request(passwordPrompt("removed"), controller.signal); + const next = hub.request(hostKeyPrompt("next")); + + controller.abort(); + await expect(aborted).rejects.toMatchObject({ name: "AbortError" }); + expect(hub.listPending().map((prompt) => prompt.promptId)).toEqual(["next"]); + expect(events.at(-1)).toEqual({ + channelName: "sshAuth", + event: "dismissed", + args: { promptId: "removed" }, + }); + hub.respond({ kind: "host-key", promptId: "next", trust: "yes" }); + await next; + }); + it("treats duplicate respond and cancel calls as no-ops", async () => { const hub = new SshAuthPromptHub(() => {}); const promise = hub.request(passwordPrompt("prompt-1")); diff --git a/tests/unit/main/agent/ssh-auth-pty.test.ts b/tests/unit/main/agent/ssh-auth-pty.test.ts index 204dd7348..f48b9c91c 100644 --- a/tests/unit/main/agent/ssh-auth-pty.test.ts +++ b/tests/unit/main/agent/ssh-auth-pty.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "bun:test"; +import { describe, expect, it, mock } from "bun:test"; import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { EventEmitter } from "node:events"; import { AuthCancelledError } from "../../../../src/main/infra/agent/ssh/auth"; @@ -214,6 +214,37 @@ describe("authenticateSshControlMaster", () => { expect(unlinkCalls).toEqual(["/tmp/nexus-test.sock"]); }); + it("aborts the PTY and outstanding prompt when its bootstrap is discarded", async () => { + const pty = new FakePty(); + const controller = new AbortController(); + const promptAborted = mock(() => {}); + const unlink = mock((_path: string) => {}); + const promise = authenticateSshControlMaster( + { host: "example.test", controlPath: "/tmp/nexus-test.sock" }, + async (_prompt, signal) => { + signal?.addEventListener("abort", promptAborted); + return new Promise(() => {}); + }, + { + signal: controller.signal, + spawnPty: () => pty as never, + spawn: () => { + const child = new FakeDisposeChild(); + queueMicrotask(() => child.emitClose()); + return child as unknown as ChildProcessWithoutNullStreams; + }, + unlink, + }, + ); + + pty.emitData("Password:"); + controller.abort(); + expect(pty.killed).toEqual([undefined]); + expect(promptAborted).toHaveBeenCalledTimes(1); + await expect(promise).rejects.toMatchObject({ name: "AbortError" }); + expect(unlink).toHaveBeenCalledWith("/tmp/nexus-test.sock"); + }); + it("fails fast when the PTY never emits prompt data or exit", async () => { const pty = new FakePty(); const unlinkCalls: string[] = []; diff --git a/tests/unit/main/agent/ssh-bootstrap.test.ts b/tests/unit/main/agent/ssh-bootstrap.test.ts index eef6e1350..632291579 100644 --- a/tests/unit/main/agent/ssh-bootstrap.test.ts +++ b/tests/unit/main/agent/ssh-bootstrap.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test"; +import { afterEach, beforeEach, describe, expect, it, jest, mock } from "bun:test"; import { createHash } from "node:crypto"; import { EventEmitter } from "node:events"; import fs from "node:fs"; @@ -219,6 +219,7 @@ describe("ssh-bootstrap", () => { "mkdir -p /home/deploy/.nexus-code/bin && cat > /home/deploy/.nexus-code/bin/nexus && chmod 755 /home/deploy/.nexus-code/bin/nexus", ]), POSIX_CLI_LAUNCHER, + expect.any(AbortSignal), ); expect(runner).toHaveBeenCalledWith( "ssh", @@ -226,6 +227,7 @@ describe("ssh-bootstrap", () => { "mkdir -p /home/deploy/.nexus-code/bin && cat > /home/deploy/.nexus-code/bin/codex && chmod 755 /home/deploy/.nexus-code/bin/codex", ]), CODEX_WRAPPER, + expect.any(AbortSignal), ); expect(result.remoteShell).toBeUndefined(); }); @@ -557,6 +559,58 @@ describe("ssh-bootstrap", () => { expect(unlinkCalls).toEqual([result.controlPath]); }); + it("starts the SSH bootstrap deadline after interactive auth and disposes the master on expiry", async () => { + jest.useFakeTimers(); + try { + const { distDir } = writeDist(); + const pty = new FakePty(); + const prompt = Promise.withResolvers<{ kind: "password"; promptId: string; value: string }>(); + const runnerStarted = Promise.withResolvers(); + const unlink = mock((_path: string) => {}); + const runner = mock(() => { + runnerStarted.resolve(); + return new Promise<{ stdout: string }>(() => {}); + }); + let failure: unknown; + const boot = ensureRemoteAgent( + { host: "example.test", remotePath: "/project", authMode: "interactive" }, + { + distDir, + runner, + promptHandler: () => prompt.promise, + auth: { + spawnPty: () => pty as never, + spawn: () => { + const child = Object.assign(new EventEmitter(), { stdin: { end() {} } }); + queueMicrotask(() => child.emit("close", 0)); + return child as never; + }, + unlink, + }, + }, + ).catch((error: unknown) => { + failure = error; + }); + pty.emitData("alice@example.test's password:"); + jest.advanceTimersByTime(120_000); + expect(runner).not.toHaveBeenCalled(); + expect(failure).toBeUndefined(); + prompt.resolve({ kind: "password", promptId: "prompt", value: "secret" }); + await flushMicrotasks(); + expect(pty.writes).toEqual(["secret\r"]); + pty.emitExit(0); + await runnerStarted.promise; + + jest.advanceTimersByTime(120_000); + await new Promise((resolve) => setImmediate(resolve)); + expect(failure).toMatchObject({ code: "transport.timeout" }); + expect(unlink).toHaveBeenCalledTimes(1); + await boot; + } finally { + jest.useRealTimers(); + } + }); + // ── Acceptance tests for Task 4: wrapper SFTP upload + remoteBinDir ── it("acceptance-1: uploads wrapper exactly once when manifest.wrapper is set", async () => { diff --git a/tests/unit/main/agent/wsl.test.ts b/tests/unit/main/agent/wsl.test.ts index 337ec0800..5f144726c 100644 --- a/tests/unit/main/agent/wsl.test.ts +++ b/tests/unit/main/agent/wsl.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, mock, test } from "bun:test"; +import { describe, expect, jest, mock, test } from "bun:test"; import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { EventEmitter } from "node:events"; import { PassThrough } from "node:stream"; @@ -7,8 +7,22 @@ import { decodeWslOutput, listWslDistros, parseWslDistros, + runWslExe, } from "../../../../src/main/infra/agent/wsl"; +/** A wsl.exe fixture that never reports close unless terminated. */ +function stalledChild() { + const child = new EventEmitter() as ChildProcessWithoutNullStreams; + const kill = mock(() => true); + Object.assign(child, { + stdin: new PassThrough(), + stdout: new PassThrough(), + stderr: new PassThrough(), + kill, + }); + return { child, kill }; +} + /** A child that prints `stdout`/`stderr`, then exits with `code`, once stdin ends. */ function fakeChild(result: { stdout?: string; stderr?: Buffer | string; code: number }) { const child = new EventEmitter() as ChildProcessWithoutNullStreams & { input: Buffer[] }; @@ -53,6 +67,23 @@ describe("createWslBootstrapRunner", () => { expect((error as Error & { cause: Error }).cause.message).toBe("mkdir: Permission denied"); }); + test("ends a stalled WSL bootstrap command even after stdin breaks", async () => { + jest.useFakeTimers(); + try { + const { child, kill } = stalledChild(); + const run = createWslBootstrapRunner("Ubuntu", () => child); + const outcome = run("ssh", ["--", "wsl:Ubuntu", "uname -ms"], "payload").catch( + (error: unknown) => error, + ); + child.stdin.emit("error", Object.assign(new Error("broken pipe"), { code: "EPIPE" })); + jest.advanceTimersByTime(120_000); + expect(kill).toHaveBeenCalledTimes(1); + expect(await outcome).toMatchObject({ code: "transport.timeout" }); + } finally { + jest.useRealTimers(); + } + }); + test("refuses sftp without starting anything, so an upload falls back to cat", async () => { const spawn = mock(() => fakeChild({ code: 0 })); const run = createWslBootstrapRunner("Ubuntu", spawn); @@ -77,6 +108,19 @@ describe("WSL distributions", () => { ).toEqual(["Ubuntu", "Debian"]); }); + test("ends a stalled distribution lookup and returns an empty list", async () => { + jest.useFakeTimers(); + try { + const { child, kill } = stalledChild(); + const listed = listWslDistros((args) => runWslExe(args, (() => child) as never), "win32"); + jest.advanceTimersByTime(10_000); + expect(kill).toHaveBeenCalledTimes(1); + expect(await listed).toEqual([]); + } finally { + jest.useRealTimers(); + } + }); + test("asks wsl.exe on Windows only, and lists none when it fails", async () => { const run = mock(async (_args: readonly string[]) => Buffer.from("Ubuntu\n", "utf16le")); diff --git a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts index c2041e127..99a593e77 100644 --- a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts +++ b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts @@ -657,6 +657,51 @@ describe("held-then-expired lifecycle", () => { }); describe("workspace removed while its SSH agent is starting", () => { + test("cancels in-flight reauthentication when the workspace is removed", async () => { + const channel = new StubChannel(); + const reauthStarted = Promise.withResolvers(); + const cancelBoot = mock(() => {}); + const ptyReleaseHeld = mock((_id: string) => {}); + const bootstrap = { + remoteCommand: "exec agent", + remoteHome: "/home/user", + platform: { os: "linux" as const, arch: "amd64" as const }, + uploaded: false, + remoteBinDir: "/home/user/.nexus-code/bin", + }; + const { manager, globalDb, broadcasts } = makeManager({ + sshBootstrap: mock(async (options) => { + if (!options.cachedRemoteArch) return bootstrap; + return new Promise((_resolve, reject) => { + options.signal?.addEventListener("abort", () => { + cancelBoot(); + reject(options.signal?.reason); + }); + reauthStarted.resolve(); + }); + }), + sshChannelFactory: mock(() => channel), + ptyReleaseHeld, + }); + const meta = makeSshMeta(manager); + const boot = manager.getAgentChannel(meta.id); + channel.resolveChannel(); + await boot; + channel.emitLifecycle({ + type: "failure", + error: Object.assign(new Error("SSH auth failed"), { code: "ssh.auth-failed" }), + }); + await reauthStarted.promise; + const joined = manager.getAgentChannel(meta.id).catch((error: unknown) => error); + manager.remove(meta.id); + + expect(cancelBoot).toHaveBeenCalledTimes(1); + expect(await joined).toMatchObject({ name: "AbortError" }); + expect(ptyReleaseHeld).toHaveBeenCalledTimes(1); + expect(broadcasts.at(-1)?.event).toBe("removed"); + globalDb.close(); + }); + test("disposes the finished bootstrap and opens no channel", async () => { let resolveBootstrap!: (value: unknown) => void; const bootstrapDispose = mock(() => {}); diff --git a/tests/unit/main/workspace/manager-wsl.test.ts b/tests/unit/main/workspace/manager-wsl.test.ts index 7211bbec3..16d1f92a7 100644 --- a/tests/unit/main/workspace/manager-wsl.test.ts +++ b/tests/unit/main/workspace/manager-wsl.test.ts @@ -90,6 +90,7 @@ describe("WSL workspace", () => { remotePath: "/home/me/project", cachedRemoteArch: undefined, workspaceId: meta.id, + signal: expect.any(AbortSignal), }); expect(wsl.createChannel).toHaveBeenCalledWith({ distro: "Ubuntu", diff --git a/tests/unit/renderer/workspace/SshAuthPromptDialog.test.tsx b/tests/unit/renderer/workspace/SshAuthPromptDialog.test.tsx index b938eaf96..5cf75c415 100644 --- a/tests/unit/renderer/workspace/SshAuthPromptDialog.test.tsx +++ b/tests/unit/renderer/workspace/SshAuthPromptDialog.test.tsx @@ -60,6 +60,18 @@ describe("Ssh auth prompt FIFO controller", () => { expect(getSshAuthPromptSnapshot().currentPrompt?.promptId).toBe("keep-me"); }); + it("advances to the next prompt when a connection dismisses the current one", () => { + __resetSshAuthPromptsForTests(); + const { callbacks } = installPromptListenerHarness(); + emitPrompt(callbacks, makePasswordPrompt({ promptId: "removed" })); + emitPrompt(callbacks, makePasswordPrompt({ promptId: "next" })); + + callbacks.get("sshAuth.dismissed")?.({ promptId: "removed" }); + expect(getSshAuthPromptSnapshot().pendingPrompts.map((prompt) => prompt.promptId)).toEqual([ + "next", + ]); + }); + it("replaces duplicate prompt ids in place for retry state", () => { __resetSshAuthPromptsForTests(); const { callbacks } = installPromptListenerHarness(); @@ -83,11 +95,11 @@ function ExtractPasswordPrompt( } function installPromptListenerHarness(): { - callbacks: Map void>; + callbacks: Map void>; } { - const callbacks = new Map void>(); + const callbacks = new Map void>(); const listen = ((channel: string, event: string, callback: (prompt: unknown) => void) => { - callbacks.set(`${channel}.${event}`, callback as (prompt: SshAuthPrompt) => void); + callbacks.set(`${channel}.${event}`, callback); return () => {}; }) as typeof ipcListen; @@ -96,7 +108,7 @@ function installPromptListenerHarness(): { } function emitPrompt( - callbacks: Map void>, + callbacks: Map void>, prompt: SshAuthPrompt, ): void { const callback = callbacks.get("sshAuth.prompt"); From ebca8ec153db4ffea498d0b3996ce7acc7054d5a Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:41:13 +0900 Subject: [PATCH 035/208] fix(chat): fence tab starts and process exits by generation Co-Authored-By: Claude Opus 5.5 --- internal/chat/service.go | 121 +++++++++++++++++++++----- internal/chat/service_test.go | 80 +++++++++++++++++ internal/chat/types.go | 19 ++-- src/main/features/chat/host.ts | 139 +++++++++++++++++++++++++----- tests/unit/main/chat/host.test.ts | 50 ++++++++++- 5 files changed, 357 insertions(+), 52 deletions(-) diff --git a/internal/chat/service.go b/internal/chat/service.go index 1e98732f8..c4455434f 100644 --- a/internal/chat/service.go +++ b/internal/chat/service.go @@ -4,6 +4,8 @@ import ( "bufio" "bytes" "context" + "crypto/rand" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -24,9 +26,11 @@ import ( // Service owns the tabs' programs and their logs. type Service struct { - mu sync.Mutex - sink EventSink - sessions map[tabKey]*session + mu sync.Mutex + sink EventSink + sessions map[tabKey]*session + closedTabs map[tabKey]map[string]struct{} + closed bool } type tabKey struct { @@ -51,11 +55,13 @@ type session struct { snaps *snapshots // closed is set once the tab is closed: its program, still ending, // sends nothing more, as the tab may already run another. - closed bool + closed bool + tabGeneration string } // process is one run of a tab's program. type process struct { + generation string canonicalCwd string cmd *exec.Cmd stdin io.WriteCloser @@ -86,7 +92,7 @@ type process struct { // New constructs an empty service. func New() *Service { - return &Service{sessions: make(map[tabKey]*session)} + return &Service{sessions: make(map[tabKey]*session), closedTabs: make(map[tabKey]map[string]struct{})} } // Register binds the chat.* methods onto the dispatcher. @@ -121,6 +127,7 @@ func (s *Service) SetEventSink(sink EventSink) { // Close kills every program, as the agent shuts down. func (s *Service) Close() { s.mu.Lock() + s.closed = true sessions := make([]*session, 0, len(s.sessions)) for key, sess := range s.sessions { sessions = append(sessions, sess) @@ -128,7 +135,11 @@ func (s *Service) Close() { } s.mu.Unlock() for _, sess := range sessions { - if p := sess.running(); p != nil { + sess.mu.Lock() + sess.closed = true + p := sess.proc + sess.mu.Unlock() + if p != nil { p.kill() } } @@ -150,12 +161,38 @@ func (s *Service) Start(_ context.Context, raw json.RawMessage) (any, error) { // Out of the tab's lock: the login shell may take a while to answer. env := mergeEnv(p.Env) - sess := s.sessionFor(key) + sess, err := s.sessionFor(key, p.TabGeneration) + if err != nil { + return nil, err + } + return s.startSession(sess, p, env) +} + +// startSession starts only while the session still owns the tab. +func (s *Service) startSession(sess *session, p StartParams, env []string) (any, error) { sess.mu.Lock() defer sess.mu.Unlock() + s.mu.Lock() + stale := s.sessions[sess.key] != sess || s.tabClosedLocked(sess.key, p.TabGeneration) + s.mu.Unlock() + if stale { + return nil, staleTab(sess.key) + } + if p.TabGeneration != "" { + sess.tabGeneration = p.TabGeneration + } if sess.proc != nil { return StartResult{PID: sess.proc.cmd.Process.Pid, Attached: true, CanonicalCwd: sess.proc.canonicalCwd}, nil } + defer func() { + if sess.proc == nil { + s.dropIfEmpty(sess) + } + }() + var generation [16]byte + if _, err := rand.Read(generation[:]); err != nil { + return nil, requestFailed("chat.start process generation: %s", err) + } // A node package's command runs as node on its script: through npm's // .cmd, cmd.exe would end a multi-line argument at its first line. @@ -176,11 +213,11 @@ func (s *Service) Start(_ context.Context, raw json.RawMessage) (any, error) { return nil, requestFailed("chat.start: %s", err) } if err := cmd.Start(); err != nil { - s.dropIfEmpty(sess) return nil, requestFailed("chat.start: %s", err) } canonicalCwd, _ := filepath.EvalSymlinks(p.Cwd) proc := &process{ + generation: hex.EncodeToString(generation[:]), canonicalCwd: canonicalCwd, cmd: cmd, stdin: stdin, @@ -196,7 +233,7 @@ func (s *Service) Start(_ context.Context, raw json.RawMessage) (any, error) { if p.ResetLog || sess.snaps == nil || sess.snaps.cwd != p.Cwd { sess.snaps = newSnapshots(p.Cwd) } - start := map[string]any{"event": "start", "pid": cmd.Process.Pid} + start := map[string]any{"event": "start", "pid": cmd.Process.Pid, "processGeneration": proc.generation} if canonicalCwd != "" { start["canonicalCwd"] = canonicalCwd } @@ -286,12 +323,31 @@ func (s *Service) CloseTab(_ context.Context, raw json.RawMessage) (any, error) return nil, err } s.mu.Lock() + if p.TabGeneration != "" { + closed := s.closedTabs[key] + if closed == nil { + closed = make(map[string]struct{}) + s.closedTabs[key] = closed + } + closed[p.TabGeneration] = struct{}{} + } sess := s.sessions[key] - delete(s.sessions, key) s.mu.Unlock() if sess != nil { sess.mu.Lock() + s.mu.Lock() + current := s.sessions[key] == sess + if !current || (p.TabGeneration != "" && sess.tabGeneration != "" && sess.tabGeneration != p.TabGeneration) { + s.mu.Unlock() + sess.mu.Unlock() + return struct{}{}, nil + } + delete(s.sessions, key) + s.mu.Unlock() sess.closed = true + if p.TabGeneration != "" { + sess.tabGeneration = p.TabGeneration + } proc := sess.proc sess.mu.Unlock() if proc != nil { @@ -370,16 +426,29 @@ func (s *Service) List(_ context.Context, raw json.RawMessage) (any, error) { return result, nil } -// sessionFor returns the tab's session, making one when there is none. -func (s *Service) sessionFor(key tabKey) *session { +// sessionFor returns or creates the session for a still-open generation. +func (s *Service) sessionFor(key tabKey, generation string) (*session, error) { s.mu.Lock() defer s.mu.Unlock() + if s.tabClosedLocked(key, generation) { + return nil, staleTab(key) + } if sess := s.sessions[key]; sess != nil { - return sess + return sess, nil } - sess := &session{service: s, key: key, createdAt: time.Now(), log: newLineLog()} + sess := &session{service: s, key: key, createdAt: time.Now(), log: newLineLog(), tabGeneration: generation} s.sessions[key] = sess - return sess + return sess, nil +} + +// tabClosedLocked checks close intents even when they arrived before session creation. +func (s *Service) tabClosedLocked(key tabKey, generation string) bool { + _, closed := s.closedTabs[key][generation] + return s.closed || closed +} + +func staleTab(key tabKey) error { + return proto.NewError("chat.tab-closed", "chat tab "+key.tabID+" is closed") } // dropIfEmpty forgets a session made for a program that did not start. @@ -424,7 +493,11 @@ func (sess *session) addLocked(dir string, message json.RawMessage, text string) return } e := sess.log.add(dir, message, text) - _ = sess.service.emit(EventLine, sess.payload(e)) + payload := sess.payload(e) + if sess.proc != nil { + payload.ProcessGeneration = sess.proc.generation + } + _ = sess.service.emit(EventLine, payload) } // addSysLocked logs a line of the agent's own. @@ -530,10 +603,8 @@ drain: exit := exitPayload(sess.key, state, err) exit.StderrTail = proc.stderr() + exit.ProcessGeneration = proc.generation sess.mu.Lock() - if sess.proc == proc { - sess.proc = nil - } fields := map[string]any{"event": "exit", "code": exit.Code} if exit.Signal != nil { fields["signal"] = *exit.Signal @@ -542,13 +613,17 @@ drain: fields["stderrTail"] = exit.StderrTail } sess.addSysLocked(fields) - // A closed tab's program is told gone only while no other runs for the tab. - told := !sess.closed || sess.service.lookup(sess.key) == nil - sess.mu.Unlock() - close(proc.done) + // Explicit close already told the host its generation was gone. Legacy + // close still expects the exit while no replacement session is present. + told := !sess.closed || (sess.tabGeneration == "" && sess.service.lookup(sess.key) == nil) if told { _ = sess.service.emit(EventExit, exit) } + if sess.proc == proc { + sess.proc = nil + } + close(proc.done) + sess.mu.Unlock() } func (p *process) write(data []byte, context *codexContext) error { diff --git a/internal/chat/service_test.go b/internal/chat/service_test.go index 0b0c50e90..8a5b00aaf 100644 --- a/internal/chat/service_test.go +++ b/internal/chat/service_test.go @@ -539,6 +539,86 @@ func TestCloseForgetsTheTab(t *testing.T) { } } +func TestClosedTabGenerationRejectsLateStart(t *testing.T) { + service := New() + defer service.Close() + closed := json.RawMessage(`{"workspaceId":"ws","tabId":"tab","tabGeneration":"old"}`) + if _, err := service.CloseTab(context.Background(), closed); err != nil { + t.Fatal(err) + } + start, _ := json.Marshal(map[string]any{ + "workspaceId": "ws", "tabId": "tab", "tabGeneration": "old", + "cwd": t.TempDir(), "program": os.Args[0], + "args": []string{"-test.run=^TestFakeProgramHelper$"}, "env": map[string]string{"NEXUS_CHAT_FAKE": "1"}, + }) + if _, err := service.Start(context.Background(), start); err == nil { + t.Fatal("a start from the closed tab reached the process") + } + if service.lookup(tabKey{workspaceID: "ws", tabID: "tab"}) != nil { + t.Fatal("late start registered a chat session") + } +} + +func TestStartCannotUseARemovedSession(t *testing.T) { + for _, closeTab := range []bool{true, false} { + name := "failed start" + if closeTab { + name = "close" + } + t.Run(name, func(t *testing.T) { + service := New() + defer service.Close() + key := tabKey{workspaceID: "ws", tabID: "tab"} + held, err := service.sessionFor(key, "") + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + if closeTab { + if _, err := service.CloseTab(context.Background(), tabParams("tab")); err != nil { + t.Fatal(err) + } + } else if _, err := service.startSession(held, StartParams{Cwd: dir, Program: filepath.Join(dir, "missing")}, nil); err == nil { + t.Fatal("the invalid process started") + } + if _, err := service.startSession(held, StartParams{ + Cwd: dir, Program: os.Args[0], Args: []string{"-test.run=^TestFakeProgramHelper$"}, + }, mergeEnv(map[string]string{"NEXUS_CHAT_FAKE": "1"})); err == nil { + t.Fatal("a retained session could start an untracked process") + } + startFake(t, service, "tab", nil) + }) + } +} + +func TestStopPublishesExitBeforeReleasingProcess(t *testing.T) { + service := New() + defer service.Close() + exiting := make(chan struct{}) + proceed := make(chan struct{}) + defer close(proceed) + service.SetEventSink(func(event string, _ any) error { + if event == EventExit { + close(exiting) + <-proceed + } + return nil + }) + startFake(t, service, "tab", nil) + proc := service.lookup(tabKey{workspaceID: "ws", tabID: "tab"}).running() + go service.Stop(context.Background(), tabParams("tab")) + select { + case <-exiting: + case <-time.After(10 * time.Second): + t.Fatal("agent did not emit the exit") + } + select { + case <-proc.done: + t.Fatal("stop released the process before publishing the exit") + default: + } +} + func TestAClosedTabsProgramSendsNothingToTheTabsNext(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("signals") diff --git a/internal/chat/types.go b/internal/chat/types.go index 1820ab22d..9e66ecc9a 100644 --- a/internal/chat/types.go +++ b/internal/chat/types.go @@ -55,7 +55,9 @@ type EventSink func(event string, payload any) error type StartParams struct { WorkspaceID string `json:"workspaceId"` TabID string `json:"tabId"` - Cwd string `json:"cwd"` + // TabGeneration identifies the open tab that requested the start. + TabGeneration string `json:"tabGeneration,omitempty"` + Cwd string `json:"cwd"` // Program is the program to run, an absolute path on the agent's host. Program string `json:"program"` Args []string `json:"args,omitempty"` @@ -91,6 +93,8 @@ type SendParams struct { type TabParams struct { WorkspaceID string `json:"workspaceId"` TabID string `json:"tabId"` + // TabGeneration limits a close to one opening of the tab. + TabGeneration string `json:"tabGeneration,omitempty"` } // ReplayParams is the wire shape for chat.replay. @@ -143,6 +147,8 @@ type LinePayload struct { Dir string `json:"dir"` Message json.RawMessage `json:"message,omitempty"` Text string `json:"text,omitempty"` + // ProcessGeneration identifies the running program that produced a live line. + ProcessGeneration string `json:"processGeneration,omitempty"` // At is when the agent got the line, in Unix milliseconds. At int64 `json:"at"` // Replay marks a line sent again by chat.replay. @@ -151,11 +157,12 @@ type LinePayload struct { // ExitPayload is the chat.exit event. type ExitPayload struct { - WorkspaceID string `json:"workspaceId"` - TabID string `json:"tabId"` - Code *int `json:"code"` - Signal *string `json:"signal,omitempty"` - StderrTail string `json:"stderrTail,omitempty"` + WorkspaceID string `json:"workspaceId"` + TabID string `json:"tabId"` + Code *int `json:"code"` + Signal *string `json:"signal,omitempty"` + StderrTail string `json:"stderrTail,omitempty"` + ProcessGeneration string `json:"processGeneration,omitempty"` } // ExecParams is the wire shape for chat.exec: a short run of the program, diff --git a/src/main/features/chat/host.ts b/src/main/features/chat/host.ts index 3bd391bfe..eafbb45fb 100644 --- a/src/main/features/chat/host.ts +++ b/src/main/features/chat/host.ts @@ -1,6 +1,7 @@ // Main-process side of the Claude tabs: starts each tab's program through // the workspace's agent and relays its chat.* events to the renderer. +import { randomUUID } from "node:crypto"; import { type AgentProfile, PROFILE_DIR_ENV, @@ -67,8 +68,17 @@ interface Subscription { dispose: () => void; } +interface TabIntent { + generation: string; + starts: Set>; +} + +/** Owns chat programs and events for the desktop's workspace channels. */ export class ChatHost { private readonly subscriptions = new Map(); + private readonly tabIntents = new Map(); + private readonly closingTabs = new Map>(); + private readonly processGenerations = new Map(); /** Workspaces whose tabs have started a program through this host. */ private readonly workspaces = new Set(); private readonly disposeProviderReady: () => void; @@ -102,6 +112,8 @@ export class ChatHost { resume: ResumeOptions, profileId?: string, ): Promise { + const key = `${workspaceId}:${tabId}`; + const intent = this.openTab(key); const channel = await this.channelFor(workspaceId); const { workspaceManager } = this.options; const windows = @@ -150,6 +162,7 @@ export class ChatHost { } try { const profile = await this.profileEnv(channel, "claude", profileId); + await this.closingTabs.get(key); const hookInfo = await workspaceManager.getChatHookInfo(workspaceId, channel); const env = claudeTabEnv({ workspaceId, @@ -163,7 +176,7 @@ export class ChatHost { ...(gitBash ? { gitBash } : {}), }); Object.assign(env, profile); - const result = await channel.call<{ pid: number; attached?: boolean }>("chat.start", { + const result = await this.spawn(key, intent, channel, { workspaceId, tabId, cwd, @@ -192,6 +205,8 @@ export class ChatHost { cwd: string, options: { resetLog?: boolean; profileId?: string }, ): Promise { + const key = `${workspaceId}:${tabId}`; + const intent = this.openTab(key); const channel = await this.channelFor(workspaceId); const found = await channel.call<{ path: string; envPath?: string }>("lsp.findBinary", { name: "codex", @@ -220,6 +235,7 @@ export class ChatHost { workspaceManager.isLocal?.(workspaceId) === true; try { const profile = await this.profileEnv(channel, "codex", options.profileId); + await this.closingTabs.get(key); const hookInfo = await workspaceManager.getChatHookInfo(workspaceId, channel); const env = codexTabEnv({ workspaceId, @@ -232,18 +248,15 @@ export class ChatHost { shimDir: windows ? null : workspaceManager.getWrapperShimDir(workspaceId), }); Object.assign(env, profile); - const result = await channel.call<{ pid: number; attached?: boolean; canonicalCwd?: string }>( - "chat.start", - { - workspaceId, - tabId, - cwd, - program: found.path, - args: ["app-server"], - env, - ...(options.resetLog ? { resetLog: true } : {}), - }, - ); + const result = await this.spawn(key, intent, channel, { + workspaceId, + tabId, + cwd, + program: found.path, + args: ["app-server"], + env, + ...(options.resetLog ? { resetLog: true } : {}), + }); return { ok: true, pid: result.pid, @@ -256,6 +269,68 @@ export class ChatHost { } } + /** Marks a tab as wanted before any asynchronous startup preparation. */ + private openTab(key: string): TabIntent { + const known = this.tabIntents.get(key); + if (known) return known; + const intent = { generation: randomUUID(), starts: new Set>() }; + this.tabIntents.set(key, intent); + return intent; + } + + /** Starts only the still-wanted tab. */ + private async spawn( + key: string, + intent: TabIntent, + channel: AgentChannel, + params: Record, + ): Promise<{ pid: number; attached?: boolean; canonicalCwd?: string }> { + if (this.tabIntents.get(key) !== intent) throw new Error("chat tab closed before it started"); + const run = channel.call<{ pid: number; attached?: boolean; canonicalCwd?: string }>( + "chat.start", + { + ...params, + tabGeneration: intent.generation, + }, + ); + intent.starts.add(run); + try { + return await run; + } finally { + intent.starts.delete(run); + } + } + + /** Invalidates preparation at once and closes any start already sent to the agent. */ + private async closeTab(workspaceId: string, tabId: string): Promise { + const key = `${workspaceId}:${tabId}`; + const intent = this.tabIntents.get(key); + const previous = this.closingTabs.get(key); + if (previous && !intent) return previous; + this.tabIntents.delete(key); + const run = (async () => { + if (previous) await previous.catch(() => undefined); + if (intent) await Promise.allSettled(intent.starts); + try { + const channel = await this.options.workspaceManager.tryGetAgentChannel(workspaceId); + return await channel?.call("chat.close", { + workspaceId, + tabId, + ...(intent ? { tabGeneration: intent.generation } : {}), + }); + } finally { + this.processGenerations.delete(key); + this.options.onProgramExit?.(workspaceId, tabId); + } + })(); + this.closingTabs.set(key, run); + try { + return await run; + } finally { + if (this.closingTabs.get(key) === run) this.closingTabs.delete(key); + } + } + async send(workspaceId: string, tabId: string, message: Record): Promise { const channel = await this.channelFor(workspaceId); const note = @@ -274,14 +349,9 @@ export class ChatHost { method: "stop" | "close" | "replay" | "attach" | "pruneAttachments", args: unknown, ): Promise { - const workspaceId = (args as { workspaceId: string }).workspaceId; - const channel = - method === "close" - ? await this.options.workspaceManager.tryGetAgentChannel(workspaceId) - : await this.channelFor(workspaceId); - if (!channel) return undefined; - if (method !== "close") this.subscribe(workspaceId, channel); - return channel.call(`chat.${method}`, args); + const { workspaceId, tabId } = args as { workspaceId: string; tabId: string }; + if (method === "close") return this.closeTab(workspaceId, tabId); + return (await this.channelFor(workspaceId)).call(`chat.${method}`, args); } async transcript(workspaceId: string, sessionId: string, profileId?: string): Promise { @@ -444,6 +514,29 @@ export class ChatHost { for (const subscription of this.subscriptions.values()) subscription.dispose(); this.subscriptions.clear(); this.workspaces.clear(); + this.tabIntents.clear(); + this.processGenerations.clear(); + } + + /** Drops exit and result events that belong to a replaced program. */ + private acceptProcessEvent(event: string, payload: Record): boolean { + if (payload.replay === true || typeof payload.tabId !== "string") return true; + const key = `${payload.workspaceId}:${payload.tabId}`; + const message = payload.message as { event?: unknown; processGeneration?: unknown } | undefined; + if (event === "line" && payload.dir === "sys" && message?.event === "start") { + if (typeof message.processGeneration === "string") { + this.processGenerations.set(key, message.processGeneration); + } else { + this.processGenerations.delete(key); + } + return true; + } + const current = this.processGenerations.get(key); + return ( + typeof payload.processGeneration !== "string" || + !current || + current === payload.processGeneration + ); } private async channelFor(workspaceId: string): Promise { @@ -487,8 +580,10 @@ export class ChatHost { ); return; } + const frame = payload as Record; + if (!this.acceptProcessEvent(event, frame)) return; this.options.broadcast(event, payload); - this.noteForStatus(event, payload as Record); + this.noteForStatus(event, frame); }; const offLine = channel.on("chat.line", relay("line")); const offExit = channel.on("chat.exit", relay("exit")); diff --git a/tests/unit/main/chat/host.test.ts b/tests/unit/main/chat/host.test.ts index da0054bb1..6d7376295 100644 --- a/tests/unit/main/chat/host.test.ts +++ b/tests/unit/main/chat/host.test.ts @@ -34,13 +34,17 @@ class FakeChannel implements AgentChannel { envPath: "/home/u/.local/bin:/usr/bin", }; versionOutput = "2.1.318 (Claude Code)\n"; + versionWait?: Promise; private readonly listeners = new Map>(); private readonly lifecycle = new Set(); async call(method: string, params?: unknown): Promise { this.calls.push({ method, params }); if (method === "lsp.findBinary") return this.found as T; - if (method === "chat.exec") return { code: 0, stdout: this.versionOutput, stderr: "" } as T; + if (method === "chat.exec") { + await this.versionWait; + return { code: 0, stdout: this.versionOutput, stderr: "" } as T; + } if (method === "chat.start") return { pid: 42 } as T; return {} as T; } @@ -392,6 +396,7 @@ describe("ChatHost", () => { expect(channel.calls.find((c) => c.method === "chat.start")?.params).toEqual({ workspaceId: WS, tabId: TAB, + tabGeneration: expect.any(String), cwd: "/repo", program: "/home/u/.local/bin/codex", args: ["app-server"], @@ -496,6 +501,49 @@ describe("ChatHost", () => { expect(status).toEqual([`stopped ${WS} ${TAB}`, `stopped ${WS} ${TAB}`, `exit ${WS} ${TAB}`]); }); + test("closing a chat during version discovery cancels its late spawn", async () => { + const { host, channel } = setup(); + const version = Promise.withResolvers(); + channel.versionWait = version.promise; + const start = host.start(WS, TAB, "/repo", {}); + await new Promise((resolve) => setImmediate(resolve)); + expect(channel.calls.some((call) => call.method === "chat.exec")).toBe(true); + await host.call("close", { workspaceId: WS, tabId: TAB }); + version.resolve(); + expect(await start).toMatchObject({ ok: false }); + expect(channel.calls.some((call) => call.method === "chat.start")).toBe(false); + expect(await host.start(WS, TAB, "/repo", {})).toMatchObject({ ok: true }); + const generation = (method: string) => + (channel.calls.find((call) => call.method === method)?.params as { tabGeneration?: string }) + ?.tabGeneration; + const closed = generation("chat.close"); + expect(typeof closed).toBe("string"); + expect(generation("chat.start")).not.toBe(closed); + }); + + test("an old process exit and result leave the replacement's hook state alone", async () => { + const { channel, host, status, events } = setup(); + await host.start(WS, TAB, "/repo", {}); + channel.emit("chat.line", { + workspaceId: WS, + tabId: TAB, + dir: "sys", + message: { event: "start", processGeneration: "new" }, + }); + channel.emit("chat.line", { + workspaceId: WS, + tabId: TAB, + dir: "out", + processGeneration: "old", + message: { type: "result", subtype: "error" }, + }); + channel.emit("chat.exit", { workspaceId: WS, tabId: TAB, processGeneration: "old" }); + expect(status).toEqual([]); + expect(events.map((event) => event.event)).toEqual(["line"]); + channel.emit("chat.exit", { workspaceId: WS, tabId: TAB, processGeneration: "new" }); + expect(status).toEqual([`exit ${WS} ${TAB}`]); + }); + test("holds on reconnecting and resyncs when the agent is back", async () => { const { channel, events, host, providerReady } = setup(); await host.start(WS, TAB, "/repo", {}); From cee1afdfba85fa1b01d29600e36c8021e10f57ca Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:43:17 +0900 Subject: [PATCH 036/208] fix(chat): publish ordered stdin outcomes after writes Co-Authored-By: Claude Opus 5.5 --- internal/chat/codex_context_test.go | 4 +- internal/chat/log.go | 13 +++++ internal/chat/service.go | 77 ++++++++++++++++++++----- internal/chat/service_test.go | 88 +++++++++++++++++++++++++++++ src/main/features/chat/ipc.ts | 14 ++++- 5 files changed, 177 insertions(+), 19 deletions(-) diff --git a/internal/chat/codex_context_test.go b/internal/chat/codex_context_test.go index 8c533b68f..1220dd99d 100644 --- a/internal/chat/codex_context_test.go +++ b/internal/chat/codex_context_test.go @@ -95,10 +95,10 @@ func TestCodexContextWriteKeepsJSONLFraming(t *testing.T) { var stdin bytes.Buffer proc.stdin = testCodexStdin{&stdin} turn := `{"method":"turn/start","params":{"threadId":"` + notesThread + `"}}` - if err := proc.write([]byte(turn), &codexContext{Files: "File links"}); err != nil { + if _, err := proc.writeLocked([]byte(turn), &codexContext{Files: "File links"}); err != nil { t.Fatal(err) } - if err := proc.write([]byte(`{"method":"initialized"}`), nil); err != nil { + if _, err := proc.writeLocked([]byte(`{"method":"initialized"}`), nil); err != nil { t.Fatal(err) } reader := bufio.NewReader(&stdin) diff --git a/internal/chat/log.go b/internal/chat/log.go index c7cfa04f9..895a4157c 100644 --- a/internal/chat/log.go +++ b/internal/chat/log.go @@ -65,6 +65,19 @@ func (l *lineLog) add(dir string, message json.RawMessage, text string) *entry { return e } +// finishInput fills a reserved slot, if the log still includes it. +func (l *lineLog) finishInput(slot *entry, dir string, message json.RawMessage) { + for _, e := range l.since(slot.seq - 1) { + if e == slot { + l.bytes += len(message) + break + } + } + slot.dir = dir + slot.message = message + l.trim() +} + // addPinned appends a line the cap keeps. What it holds is bounded by // whoever adds it. func (l *lineLog) addPinned(dir string, message json.RawMessage) *entry { diff --git a/internal/chat/service.go b/internal/chat/service.go index c4455434f..44b2c2049 100644 --- a/internal/chat/service.go +++ b/internal/chat/service.go @@ -51,6 +51,9 @@ type session struct { mu sync.Mutex log *lineLog proc *process + // pending reserves the next line while stdin is writing. Output readers + // can fill the capped log while publication waits for the write result. + pending *entry // snaps takes the originals of the files a Codex program changes. snaps *snapshots // closed is set once the tab is closed: its program, still ending, @@ -274,24 +277,52 @@ func (s *Service) Send(_ context.Context, raw json.RawMessage) (any, error) { if sess == nil { return nil, notRunning(key) } - sess.mu.Lock() - proc := sess.proc + proc := sess.running() if proc == nil { + return nil, notRunning(key) + } + proc.writeMu.Lock() + defer proc.writeMu.Unlock() + sess.mu.Lock() + if sess.closed || sess.proc != proc { sess.mu.Unlock() return nil, notRunning(key) } - message := json.RawMessage(bytes.Clone(line.Bytes())) - sess.addLocked(DirIn, message, "") + slot := sess.log.add(DirSys, nil, "") + sess.pending = slot sess.mu.Unlock() - // Written outside the log's lock: a program that stops reading its - // input must not hold up its output. - if err := proc.write(line.Bytes(), p.CodexContext); err != nil { - return nil, requestFailed("chat.send: %s", err) + message := json.RawMessage(bytes.Clone(line.Bytes())) + written, err := proc.writeLocked(line.Bytes(), p.CodexContext) + if err != nil { + code := "chat.stdin-write-failed" + if written > 0 { + code = "chat.stdin-incomplete" + } + failure, _ := json.Marshal(map[string]string{"event": "stdin-failed", "code": code}) + sess.finishInput(slot, DirSys, failure) + return nil, proto.NewError(code, fmt.Sprintf("chat.send: %s", err)) } + sess.finishInput(slot, DirIn, message) return struct{}{}, nil } +// finishInput publishes the write outcome before any output produced while +// the write was in flight. Earlier logs still use the same DirIn format. +func (sess *session) finishInput(slot *entry, dir string, message json.RawMessage) { + sess.mu.Lock() + defer sess.mu.Unlock() + sess.pending = nil + if sess.closed { + return + } + sess.log.finishInput(slot, dir, message) + sess.emitLineLocked(slot) + for _, e := range sess.log.since(slot.seq) { + sess.emitLineLocked(e) + } +} + // Stop ends the tab's program and keeps its log. func (s *Service) Stop(_ context.Context, raw json.RawMessage) (any, error) { var p TabParams @@ -376,6 +407,9 @@ func (s *Service) Replay(_ context.Context, raw json.RawMessage) (any, error) { defer sess.mu.Unlock() last := p.AfterSeq for _, e := range sess.log.since(p.AfterSeq) { + if sess.pending != nil && e.seq >= sess.pending.seq { + break + } payload := sess.payload(e) payload.Replay = true if err := s.emit(EventLine, payload); err != nil { @@ -493,6 +527,13 @@ func (sess *session) addLocked(dir string, message json.RawMessage, text string) return } e := sess.log.add(dir, message, text) + if sess.pending == nil { + sess.emitLineLocked(e) + } +} + +// emitLineLocked relays one committed input, output or system event. +func (sess *session) emitLineLocked(e *entry) { payload := sess.payload(e) if sess.proc != nil { payload.ProcessGeneration = sess.proc.generation @@ -523,7 +564,9 @@ func (sess *session) addPinnedLocked(fields any) { return } e := sess.log.addPinned(DirSys, bytes.TrimRight(data.Bytes(), "\n")) - _ = sess.service.emit(EventLine, sess.payload(e)) + if sess.pending == nil { + sess.emitLineLocked(e) + } } func (sess *session) payload(e *entry) LinePayload { @@ -604,6 +647,9 @@ drain: exit := exitPayload(sess.key, state, err) exit.StderrTail = proc.stderr() exit.ProcessGeneration = proc.generation + // Closing stdin releases any blocked write. Its outcome precedes exit. + proc.writeMu.Lock() + defer proc.writeMu.Unlock() sess.mu.Lock() fields := map[string]any{"event": "exit", "code": exit.Code} if exit.Signal != nil { @@ -626,15 +672,18 @@ drain: sess.mu.Unlock() } -func (p *process) write(data []byte, context *codexContext) error { - p.writeMu.Lock() - defer p.writeMu.Unlock() +// writeLocked writes one full line as part of the process's ordered send. +func (p *process) writeLocked(data []byte, context *codexContext) (int, error) { p.noteCodexInitialize(data) if context != nil { data = p.withCodexContext(data, *context) } - _, err := p.stdin.Write(append(data, '\n')) - return err + line := append(data, '\n') + n, err := p.stdin.Write(line) + if err == nil && n != len(line) { + err = io.ErrShortWrite + } + return n, err } // stop asks the program to exit, and kills it if it has not after stopGrace. diff --git a/internal/chat/service_test.go b/internal/chat/service_test.go index 8a5b00aaf..d85f5802e 100644 --- a/internal/chat/service_test.go +++ b/internal/chat/service_test.go @@ -2,6 +2,7 @@ package chat import ( "bufio" + "bytes" "context" "encoding/json" "fmt" @@ -245,6 +246,93 @@ func tabParams(tabID string) json.RawMessage { return params } +type testStdin func([]byte) (int, error) + +func (w testStdin) Write(data []byte) (int, error) { return w(data) } +func (w testStdin) Close() error { return nil } + +func TestSendLogsAConfirmedInputBeforeEarlyOutput(t *testing.T) { + service := New() + rec := newRecorder() + service.SetEventSink(rec.sink) + key := tabKey{workspaceID: "ws", tabID: "tab"} + sess, err := service.sessionFor(key, "") + if err != nil { + t.Fatal(err) + } + reading := make(chan struct{}) + unblock := make(chan struct{}) + sess.proc = &process{ + stdin: testStdin(func(data []byte) (int, error) { + if !bytes.Contains(data, []byte("hello")) { + return len(data), nil + } + // Simulates output the CLI produced before Write returned. + sess.addOutput([]byte(`{"type":"result"}`)) + close(reading) + <-unblock + return len(data), nil + }), + } + sent := make(chan error, 1) + go func() { sent <- send(t, service, "tab", "hello") }() + select { + case <-reading: + case <-time.After(10 * time.Second): + t.Fatal("stdout could not be consumed while stdin was writing") + } + queued := make(chan error, 1) + go func() { queued <- send(t, service, "tab", "second") }() + replay, replayErr := service.Replay(context.Background(), tabParams("tab")) + close(unblock) + if err := <-sent; err != nil { + t.Fatal(err) + } + if err := <-queued; err != nil { + t.Fatal(err) + } + if replayErr != nil || replay.(ReplayResult).LastSeq != 0 { + t.Fatalf("replay exposed an input still being written: %+v %v", replay, replayErr) + } + rec.mu.Lock() + defer rec.mu.Unlock() + if len(rec.lines) != 3 || rec.lines[0].Dir != DirIn || rec.lines[1].Dir != DirOut || + rec.lines[2].Dir != DirIn || !bytes.Contains(rec.lines[2].Message, []byte("second")) { + t.Fatalf("want confirmed input followed by its output, got %v", describe(rec.lines)) + } +} + +func TestFailedStdinWriteReplaysFailureInsteadOfApproval(t *testing.T) { + service := New() + rec := newRecorder() + service.SetEventSink(rec.sink) + key := tabKey{workspaceID: "ws", tabID: "tab"} + sess, err := service.sessionFor(key, "") + if err != nil { + t.Fatal(err) + } + sess.proc = &process{ + stdin: testStdin(func(_ []byte) (int, error) { + return 0, io.ErrClosedPipe + }), + } + sess.addOutput([]byte(`{"type":"control_request","request_id":"p","request":{"subtype":"can_use_tool"}}`)) + params := json.RawMessage(`{"workspaceId":"ws","tabId":"tab","message":{"type":"control_response","response":{"request_id":"p"}}}`) + if _, err := service.Send(context.Background(), params); err == nil { + t.Fatal("the write succeeded despite the broken pipe") + } + rec.reset() + if _, err := service.Replay(context.Background(), tabParams("tab")); err != nil { + t.Fatal(err) + } + rec.mu.Lock() + defer rec.mu.Unlock() + if len(rec.lines) != 2 || rec.lines[0].Dir != DirOut || rec.lines[1].Dir != DirSys || + !strings.Contains(string(rec.lines[1].Message), `"stdin-failed"`) { + t.Fatalf("the failed approval was replayed as sent: %v", describe(rec.lines)) + } +} + func TestReplayDropsStreamEventsOfCompleteMessages(t *testing.T) { service := New() rec := newRecorder() diff --git a/src/main/features/chat/ipc.ts b/src/main/features/chat/ipc.ts index b72f76c4f..207135914 100644 --- a/src/main/features/chat/ipc.ts +++ b/src/main/features/chat/ipc.ts @@ -1,7 +1,7 @@ // Claude tab IPC channel: renderer ↔ main ↔ the workspace's agent. import { ipcContract } from "../../../shared/ipc/contract"; -import { ipcOk } from "../../../shared/ipc/result"; +import { ipcErr, ipcOk } from "../../../shared/ipc/result"; import { broadcast, register, validateArgs } from "../../infra/ipc-router"; import { ChatHost, type ChatHostOptions } from "./host"; import { OAuthCallbacks } from "./oauth-callback"; @@ -39,8 +39,16 @@ export function registerChatChannel(options: Omit) }, send: async (args: unknown) => { const { workspaceId, tabId, message } = validateArgs(c.send.args, args); - await host.send(workspaceId, tabId, message); - return ipcOk(undefined); + try { + await host.send(workspaceId, tabId, message); + return ipcOk(undefined); + } catch (error) { + const code = (error as { code?: unknown } | null)?.code; + const detail = error instanceof Error ? error.message : String(error); + return typeof code === "string" + ? ipcErr(code, detail, { category: "failed" }) + : ipcErr("chat.send-failed", detail, { category: "bug" }); + } }, stop: async (args: unknown) => { await host.call("stop", validateArgs(c.stop.args, args)); From ead6ce097fe7ef2185d082202b93bac77c7d0e11 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:46:22 +0900 Subject: [PATCH 037/208] fix(pty): wait for the current agent hook endpoint before spawn Co-Authored-By: Claude Opus 5.5 --- src/main/features/chat/host.ts | 10 ++--- src/main/features/pty/agent-host.ts | 29 ++++++++++++- src/main/features/pty/ipc.ts | 26 ++---------- src/main/features/workspace/manager.ts | 4 +- src/main/index.ts | 1 - tests/unit/main/chat/host.test.ts | 4 +- tests/unit/main/pty/ipc-shell-choice.test.ts | 1 - .../manager-local-lifecycle-degraded.test.ts | 41 ++++++++++++++++++- 8 files changed, 78 insertions(+), 38 deletions(-) diff --git a/src/main/features/chat/host.ts b/src/main/features/chat/host.ts index eafbb45fb..e75ef9165 100644 --- a/src/main/features/chat/host.ts +++ b/src/main/features/chat/host.ts @@ -36,7 +36,7 @@ export interface ChatWorkspaceManager { getAgentChannel(workspaceId: string): Promise; tryGetAgentChannel(workspaceId: string): Promise; onProviderReady(listener: (workspaceId: string) => void): () => void; - getChatHookInfo(workspaceId: string, channel: AgentChannel): Promise; + getSpawnHookInfo(workspaceId: string, channel: AgentChannel): Promise; getWrapperBinDir(workspaceId: string): string | null; getWrapperAgentBin(workspaceId: string): string | null; getWrapperShimDir(workspaceId: string): string | null; @@ -94,7 +94,7 @@ export class ChatHost { .then(async (channel) => { if (!channel) return; await channel.ready; - await this.options.workspaceManager.getChatHookInfo(workspaceId, channel); + await this.options.workspaceManager.getSpawnHookInfo(workspaceId, channel); if (this.disposed) return; this.subscribe(workspaceId, channel); this.options.broadcast("resync", { workspaceId }); @@ -163,7 +163,7 @@ export class ChatHost { try { const profile = await this.profileEnv(channel, "claude", profileId); await this.closingTabs.get(key); - const hookInfo = await workspaceManager.getChatHookInfo(workspaceId, channel); + const hookInfo = await workspaceManager.getSpawnHookInfo(workspaceId, channel); const env = claudeTabEnv({ workspaceId, tabId, @@ -236,7 +236,7 @@ export class ChatHost { try { const profile = await this.profileEnv(channel, "codex", options.profileId); await this.closingTabs.get(key); - const hookInfo = await workspaceManager.getChatHookInfo(workspaceId, channel); + const hookInfo = await workspaceManager.getSpawnHookInfo(workspaceId, channel); const env = codexTabEnv({ workspaceId, tabId, @@ -643,7 +643,7 @@ export class ChatHost { private async resyncAfterHooks(workspaceId: string, subscription: Subscription): Promise { const { revision, channel } = subscription; try { - await this.options.workspaceManager.getChatHookInfo(workspaceId, channel); + await this.options.workspaceManager.getSpawnHookInfo(workspaceId, channel); if ( this.subscriptions.get(workspaceId) === subscription && revision === subscription.revision diff --git a/src/main/features/pty/agent-host.ts b/src/main/features/pty/agent-host.ts index ae855ed69..e665fa630 100644 --- a/src/main/features/pty/agent-host.ts +++ b/src/main/features/pty/agent-host.ts @@ -1,6 +1,8 @@ import { TextDecoder } from "node:util"; import { createLogger } from "../../../shared/log/main"; import type { AgentChannel, ChannelLifecycleEvent } from "../../infra/agent/channel"; +import type { HookInfo } from "../workspace/manager"; +import { tabHookToken } from "../workspace/tab-token"; import type { PtyHostHandle } from "./types"; const log = createLogger("agent-host"); @@ -44,6 +46,8 @@ export interface AgentPtyWorkspaceManager { * racing condition rather than a bug. */ tryGetAgentChannel(workspaceId: string): Promise; + /** The current process's hook endpoint for a wrapped terminal spawn. */ + getSpawnHookInfo?(workspaceId: string, channel: AgentChannel): Promise; /** * Tells when a workspace's agent is ready, a new one after a reconnect * included: its channel is subscribed then, not at its first PTY call. @@ -262,7 +266,16 @@ class AgentPtyHostHandle implements PtyHostHandle { throw new Error("terminal closed before it started"); } const channel = await this.channelForWorkspace(workspaceId); - // Or while its agent was being reached. + if (this.isUnwanted(workspaceId, tabId)) { + throw new Error("terminal closed before it started"); + } + const spawn = args as { env?: Record }; + const env = spawn.env; + const hooks = + env?.NEXUS_WRAPPER_SELF_DIR && this.workspaceManager.getSpawnHookInfo + ? await this.workspaceManager.getSpawnHookInfo(workspaceId, channel) + : null; + // The tab can also close while the replacement's hooks are being read. if (this.isUnwanted(workspaceId, tabId)) { throw new Error("terminal closed before it started"); } @@ -270,7 +283,19 @@ class AgentPtyHostHandle implements PtyHostHandle { let result: AgentSpawnResult; try { sent = true; - result = await channel.call("pty.spawn", args); + result = await channel.call( + "pty.spawn", + hooks + ? { + ...spawn, + env: { + NEXUS_AGENT_SOCKET: hooks.socketPath, + NEXUS_HOOK_TOKEN: tabHookToken(hooks, workspaceId, tabId), + ...env, + }, + } + : args, + ); } catch (error) { this.deleteSession(workspaceId, tabId); throw error; diff --git a/src/main/features/pty/ipc.ts b/src/main/features/pty/ipc.ts index 478e209bb..1d8b6144c 100644 --- a/src/main/features/pty/ipc.ts +++ b/src/main/features/pty/ipc.ts @@ -7,8 +7,6 @@ import type { WorkspacePorts } from "../../../shared/pty/ports"; import type { CustomShell, ShellChoice } from "../../../shared/pty/shell"; import { broadcast, register, validateArgs } from "../../infra/ipc-router"; import { getActiveAppWindow, getFocusedAppWindow } from "../window/app-windows"; -import type { HookInfo } from "../workspace/manager"; -import { tabHookToken } from "../workspace/tab-token"; import { ForwardError, type PortForwards } from "./forwards"; import { injectHarnessTerminalEnv } from "./harness-env"; import type { WorkspaceNameLookup } from "./osc-notification"; @@ -33,13 +31,8 @@ export interface PtyChannelOptions { agentHost: PtyHostHandle; recorder?: PtyRecorderSink; /** - * Provides workspace display names, activation for OS notifications, and - * Pull-based hookserver connection info lookup (getHookInfo). - * - * `getAgentChannel` is used to guarantee that hookInfo is fresh — - * the spawn handler awaits it before capturing the env, which forces channel.ready / the hook.getInfo - * pull to complete before the hookInfo lookup. The returned channel object - * itself is not used; the call exists only for ready synchronization. + * Provides workspace display names and activation for OS notifications. + * The agent must boot before its remote wrapper locations are available. * * `getWrapperBinDir` / `getWrapperAgentBin` — return, by workspace kind, * the absolute paths of the wrapper bin directory and the agent binary. When null is returned, @@ -57,7 +50,6 @@ export interface PtyChannelOptions { */ workspaceManager?: WorkspaceNameLookup & { activate(id: string): Promise; - getHookInfo(workspaceId: string): HookInfo | null; getAgentChannel(workspaceId: string): Promise; getWrapperBinDir(workspaceId: string): string | null; getWrapperAgentBin(workspaceId: string): string | null; @@ -207,17 +199,7 @@ export function registerPtyChannel(options: PtyChannelOptions): void { env = { ...givenEnv, ...fromProfile }; } recorder.start(workspaceId, tabId, cols, rows); - // hookInfo must be read after channel.ready for it to be guaranteed fresh. - // Called right after a channel reconnect, a stale cache (the previous boot's socket path) - // could be baked into the env, creating a hook client that points at a dead socket. - // wm.getAgentChannel triggers ensureProviderReady, and at its end the hook.getInfo - // result is set in hookInfoByWorkspace, so a getHookInfo after this await is - // structurally guaranteed to be the latest. The returned channel object is not used. - if (wm) { - await wm.getAgentChannel(workspaceId); - } - // Look up the socket/token by pull with workspaceManager.getHookInfo and inject them into the env. - const hookInfo = wm?.getHookInfo(workspaceId) ?? null; + if (wm) await wm.getAgentChannel(workspaceId); // Decide the wrapper bin directory and agent binary path by workspace kind. // When null, skip the wrapper-related env injection (keeps the graceful pattern). const wrapperBinDir = wm?.getWrapperBinDir(workspaceId) ?? null; @@ -229,8 +211,6 @@ export function registerPtyChannel(options: PtyChannelOptions): void { workspaceId, tabId, agentBin: wrapperAgentBin ?? undefined, - agentSocket: hookInfo?.socketPath, - hookToken: hookInfo ? tabHookToken(hookInfo, workspaceId, tabId) : undefined, }) : injectHarnessTerminalEnv(env); diff --git a/src/main/features/workspace/manager.ts b/src/main/features/workspace/manager.ts index 064d7700a..83b386a7c 100644 --- a/src/main/features/workspace/manager.ts +++ b/src/main/features/workspace/manager.ts @@ -592,8 +592,8 @@ export class WorkspaceManager { return this.hookInfoByWorkspace.get(workspaceId) ?? null; } - /** Returns the hooks for the channel a chat is about to use. */ - async getChatHookInfo(workspaceId: string, channel: AgentChannel): Promise { + /** Returns the hooks for the channel about to start a chat or terminal. */ + async getSpawnHookInfo(workspaceId: string, channel: AgentChannel): Promise { let refresh = this.localHookRefreshes.get(channel); while (refresh) { await refresh.promise; diff --git a/src/main/index.ts b/src/main/index.ts index 9323da6f8..961a0bbc0 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -750,7 +750,6 @@ app.whenReady().then(async () => { }, }); - // The hookserver connection info is looked up by pull from workspaceManager.getHookInfo(). // A program's own OS notifications (OSC 9/777/99) follow Claude's rules. registerPtyChannel({ agentHost: agentPtyHost, diff --git a/tests/unit/main/chat/host.test.ts b/tests/unit/main/chat/host.test.ts index 6d7376295..ba81c2e3a 100644 --- a/tests/unit/main/chat/host.test.ts +++ b/tests/unit/main/chat/host.test.ts @@ -86,7 +86,7 @@ function setup( providerReady = listener; return () => {}; }, - getChatHookInfo: async () => ({ socketPath: "/tmp/h.sock", token: "tok" }), + getSpawnHookInfo: async () => ({ socketPath: "/tmp/h.sock", token: "tok" }), getWrapperBinDir: () => "/home/u/.nexus-code/bin", getWrapperAgentBin: () => "/home/u/.nexus-code/bin/agent", getWrapperShimDir: () => "/home/u/.nexus-code/shim/ws", @@ -340,7 +340,7 @@ describe("ChatHost", () => { getAgentChannel: async () => channel, tryGetAgentChannel: async () => channel, onProviderReady: () => () => {}, - getChatHookInfo: async () => null, + getSpawnHookInfo: async () => null, getWrapperBinDir: () => "C:\\Users\\u\\.nexus-code\\cli", getWrapperAgentBin: () => null, getWrapperShimDir: () => "C:\\Users\\u\\.nexus-code\\shim\\ws", diff --git a/tests/unit/main/pty/ipc-shell-choice.test.ts b/tests/unit/main/pty/ipc-shell-choice.test.ts index a55f78f21..082eb32dc 100644 --- a/tests/unit/main/pty/ipc-shell-choice.test.ts +++ b/tests/unit/main/pty/ipc-shell-choice.test.ts @@ -109,7 +109,6 @@ function setup(opts: { const wm: PtyChannelOptions["workspaceManager"] = { getName: () => "ws", activate: async () => {}, - getHookInfo: () => null, getAgentChannel: async () => agent, getWrapperBinDir: () => opts.wrapper?.binDir ?? null, getWrapperAgentBin: () => null, diff --git a/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts b/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts index 0270a0e23..66d927988 100644 --- a/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts +++ b/tests/unit/main/workspace/manager-local-lifecycle-degraded.test.ts @@ -33,6 +33,7 @@ const { WorkspaceStorage } = await import("../../../../src/main/infra/storage/wo const { StateService } = await import("../../../../src/main/infra/storage/state-service"); const { WorkspaceManager } = await import("../../../../src/main/features/workspace/manager"); const { ChatHost } = await import("../../../../src/main/features/chat/host"); +const { startAgentPtyHost } = await import("../../../../src/main/features/pty/agent-host"); type ChannelLifecycleCallback = (event: { type: string }) => void; @@ -54,7 +55,7 @@ class StubChannel { if (method === "hook.getInfo") return this.hookInfo(); if (method === "lsp.findBinary") return { path: "/stub/model" }; if (method === "chat.exec") return { code: 0, stdout: "2.1.400" }; - if (method === "chat.start") { + if (method === "chat.start" || method === "pty.spawn") { this.spawns.push(params as (typeof this.spawns)[number]); return { pid: 1 }; } @@ -72,7 +73,7 @@ class StubChannel { return () => this.lifecycleListeners.delete(cb); } - emitLifecycle(event: { type: string }): void { + emitLifecycle(event: { type: string; hadEpoch?: boolean }): void { for (const cb of [...this.lifecycleListeners]) cb(event); } @@ -246,6 +247,42 @@ test("a superseded local hook reply cannot release chat resync", async () => { } }); +test("PTY spawn waits for the local replacement's hook endpoint", async () => { + const harness = makeHarness(); + const { manager, channels, globalDb } = harness; + const host = startAgentPtyHost(manager); + try { + const { id } = await bootLocalWorkspace(harness); + const [channel] = channels; + const answer = Promise.withResolvers(); + channel.hookInfo.mockImplementation(() => answer.promise); + channel.emitLifecycle({ type: "reconnecting", hadEpoch: false }); + channel.emitLifecycle({ type: "ready" }); + const spawn = host.call("spawn", { + workspaceId: id, + tabId: "terminal", + cwd: "/project", + cols: 80, + rows: 24, + env: { NEXUS_IN_APP: "1", NEXUS_WRAPPER_SELF_DIR: "/stub/bin" }, + }); + try { + await new Promise((resolve) => setImmediate(resolve)); + expect(channel.spawns).toHaveLength(0); + } finally { + answer.resolve({ socketPath: "/tmp/new-terminal.sock", token: "new-terminal" }); + await spawn; + } + expect(channel.spawns[0]?.env).toMatchObject({ + NEXUS_AGENT_SOCKET: "/tmp/new-terminal.sock", + NEXUS_HOOK_TOKEN: "new-terminal", + }); + } finally { + host.dispose(); + globalDb.close(); + } +}); + for (const kind of ["ssh", "wsl"] as const) { test(`${kind} reattach keeps hooks and daemon replacement loads them on a new provider`, async () => { const { manager, channels, globalDb } = makeHarness(); From 47f88b542ea3d08c177930658b641bc40692e2ec Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:47:48 +0900 Subject: [PATCH 038/208] fix(chat): keep drafts and approvals recoverable after stdin errors Co-Authored-By: Claude Opus 5.5 --- src/renderer/components/chat/claude-tab.tsx | 3 +- src/renderer/components/chat/codex-tab.tsx | 3 +- src/renderer/components/chat/composer.tsx | 36 +++++++++------ src/renderer/components/chat/send-error.ts | 16 +++++++ .../services/chat/codex-controller.ts | 46 +++++++++++++------ src/renderer/services/chat/controller.ts | 9 ++-- src/renderer/services/chat/store.ts | 12 +++++ .../services/chat/codex-chosen.test.ts | 29 +++++++++++- 8 files changed, 119 insertions(+), 35 deletions(-) create mode 100644 src/renderer/components/chat/send-error.ts diff --git a/src/renderer/components/chat/claude-tab.tsx b/src/renderer/components/chat/claude-tab.tsx index 9fdf6758f..763179939 100644 --- a/src/renderer/components/chat/claude-tab.tsx +++ b/src/renderer/components/chat/claude-tab.tsx @@ -94,6 +94,7 @@ import { PrintRunPane } from "./print-run-pane"; import { QuickLook, type QuickLookList } from "./quick-look"; import { RateLimitBanner } from "./rate-limit-banner"; import { RewindDialog } from "./rewind-dialog"; +import { surfaceChatSendError } from "./send-error"; import { SessionList } from "./session-list"; import { SidePanel } from "./side-panel"; import { StatusLine } from "./status-line"; @@ -213,7 +214,7 @@ export function ClaudeTabView({ workspaceId, tabId, props, isVisible }: ClaudeTa }; const onAnswer = (request: PermissionRequest, answer: PermissionAnswer) => { - void controller.answerPermission(request, answer).catch(() => {}); + void controller.answerPermission(request, answer).catch(surfaceChatSendError); }; const [rewinding, setRewinding] = useState(null); diff --git a/src/renderer/components/chat/codex-tab.tsx b/src/renderer/components/chat/codex-tab.tsx index 61e431b13..97b25b3a7 100644 --- a/src/renderer/components/chat/codex-tab.tsx +++ b/src/renderer/components/chat/codex-tab.tsx @@ -96,6 +96,7 @@ import { focusChatTab, PermissionCard } from "./permission-card"; import { PrintRunPane } from "./print-run-pane"; import { QuickLook, type QuickLookList } from "./quick-look"; import { RewindDialog } from "./rewind-dialog"; +import { surfaceChatSendError } from "./send-error"; import { CodexSessionList } from "./session-list"; import { StatusLine } from "./status-line"; import { SummaryLine } from "./summary-line"; @@ -155,7 +156,7 @@ export function CodexTabView({ workspaceId, tabId, props, isVisible }: CodexTabV }, [isVisible, controller]); const onAnswer = (request: PermissionRequest, answer: PermissionAnswer) => { - void controller.answerPermission(request, answer).catch(() => {}); + void controller.answerPermission(request, answer).catch(surfaceChatSendError); }; // The pane shows the conversation or one of the runs its commands diff --git a/src/renderer/components/chat/composer.tsx b/src/renderer/components/chat/composer.tsx index 8eb4048b9..b5f93b69c 100644 --- a/src/renderer/components/chat/composer.tsx +++ b/src/renderer/components/chat/composer.tsx @@ -74,6 +74,7 @@ import { type ChatAgent, ChatAgentContext, useAgentContext } from "./chat-agent" import { type CompletionItem, CompletionMenu } from "./completion-menu"; import { maxTextHeight } from "./composer-height"; import { DictationOverlay, MicButton, useComposerDictation } from "./dictation"; +import { surfaceChatSendError } from "./send-error"; /** What the composer drives: a Claude tab's controller, or a Codex tab's. */ export interface ComposerController { @@ -485,25 +486,32 @@ export const Composer = memo(function Composer({ if (controller.submitPeer(as, body, images, files)) clear(); return; } - let message: string; - let uploads: string[]; setSending(true); try { - ({ message, uploads } = await withAttachments(body)); - } catch (err) { - showError(err as Error); - return; + const { message, uploads } = await withAttachments(body); + clear(); + try { + if (uploads.length > 0 && controller.sendUploaded) { + await controller.sendUploaded(as, message, images, uploads); + } else if (as === "queue") { + controller.enqueue(message, images); + } else if (as === "now" && controller.sendNow) { + await controller.sendNow(message, images); + } else { + await controller.send(message, images); + } + } catch (error) { + // Restore the original text and attachments for another attempt. + if (body) setText((prev) => (prev ? `${body}\n${prev}` : body)); + if (images.length) setImages((prev) => [...images, ...prev]); + if (files.length) setFiles((prev) => [...files, ...prev]); + throw error; + } + } catch (error) { + surfaceChatSendError(error); } finally { setSending(false); } - const sendUploaded = controller.sendUploaded?.bind(controller); - if (uploads.length > 0 && sendUploaded) { - void sendUploaded(as, message, images, uploads).catch((err: Error) => showError(err)); - } else if (how === "queue" && running) controller.enqueue(message, images); - else if (how === "now" && running && controller.sendNow) { - void controller.sendNow(message, images).catch((err: Error) => showError(err)); - } else void controller.send(message, images).catch((err: Error) => showError(err)); - clear(); }; // The submit of the latest render, for a send that waits on the dictation's end. const submitRef = useRef(submit); diff --git a/src/renderer/components/chat/send-error.ts b/src/renderer/components/chat/send-error.ts new file mode 100644 index 000000000..b20e7a8b9 --- /dev/null +++ b/src/renderer/components/chat/send-error.ts @@ -0,0 +1,16 @@ +import { appErrorBug, appErrorCancelled, appErrorFailed } from "../../../shared/error/app-error"; +import { chatSendErrorKind } from "../../services/chat/store"; +import { surfaceError } from "../../services/error-surface/surface-error"; + +/** Reports send and approval failures without exposing transport details. */ +export function surfaceChatSendError(error: unknown): void { + const code = chatSendErrorKind(error); + const message = error instanceof Error ? error.message : String(error); + const appError = + code === "cancelled" + ? appErrorCancelled(message, { code }) + : code === "chat.send-failed" + ? appErrorBug(message, { code }) + : appErrorFailed(message, { code }); + surfaceError(appError, { surface: "toast" }); +} diff --git a/src/renderer/services/chat/codex-controller.ts b/src/renderer/services/chat/codex-controller.ts index 4dfa24765..8eb7d3c2a 100644 --- a/src/renderer/services/chat/codex-controller.ts +++ b/src/renderer/services/chat/codex-controller.ts @@ -66,9 +66,11 @@ import { type ChatTabState, type CommandCard, chatKey, + chatSendErrorKind, clearObservedQueued, dispatchQueuedMessage, emptyTabState, + isChatWriteRejected, type QueuedMessage, useChatStore, } from "./store"; @@ -1281,10 +1283,7 @@ export class CodexController { const collaboration = this.collaborationChange; if (this.rewinding || this.resumingSelection) throw new Error("Codex is changing the conversation"); - if (!(await this.ensureRunning())) { - if (id) throw new Error("Codex is not running"); - return; - } + if (!(await this.ensureRunning())) throw new Error("Codex is not running"); if (!(await this.ready)) throw new Error(this.state.error ?? "Codex has no thread to send to"); // A message sent while a mode change is pending must use the newly // acknowledged mode. A failed switch must leave the draft unsent. @@ -1355,7 +1354,12 @@ export class CodexController { told(result, turnId); return; } catch (err) { - if (id && !(err instanceof CodexReplyError)) throw err; + if ( + !(err instanceof CodexReplyError) && + (id || isChatWriteRejected(err) || chatSendErrorKind(err) === "chat.stdin-incomplete") + ) { + throw err; + } this.flushNow(); log.info(`steer not taken: ${(err as Error).message}`); // The active turn refused the message. Wait for a turn boundary. @@ -1374,15 +1378,16 @@ export class CodexController { // The thread holds them from this turn on: the tab keeps a pick only // until it is sent, so a thread changed since is not overridden. if (model || effort) this.hooks.onChosen?.({}); - // Its answer, or its error as a notice, comes in the log. - const start = this.request("turn/start", { + // Its answer comes in the log. The composer waits for the separate write outcome. + const { reply, written } = this.requestWithWrite("turn/start", { threadId, clientUserMessageId, input, ...(model ? { model } : {}), ...(effort ? { effort } : {}), ...(mode ? MODE_SETTINGS[mode] : {}), - }) + }); + const start = reply .then((result) => told(result)) .finally(() => { this.flushNow(); @@ -1391,7 +1396,11 @@ export class CodexController { }); this.startingTurn = start; if (id) await start; - else void start.catch(() => {}); + else { + void start.catch(() => {}); + await written; + this.flushNow(); + } } /** The composer took the message the app put back. */ @@ -1479,7 +1488,7 @@ export class CodexController { return { ...next, afterTool: 0 }; return next; }, - (error) => error instanceof CodexReplyError, + (error) => error instanceof CodexReplyError || isChatWriteRejected(error), (id) => this.sawQueuedMessage(id), () => this.sendNextQueued(), (item) => this.canSendQueued(item), @@ -1688,6 +1697,15 @@ export class CodexController { params: Record, timeoutMs = REQUEST_TIMEOUT_MS, ): Promise> { + return this.requestWithWrite(method, params, timeoutMs).reply; + } + + /** Tracks stdin delivery separately from the program's JSON-RPC reply. */ + private requestWithWrite( + method: string, + params: Record, + timeoutMs = REQUEST_TIMEOUT_MS, + ): { written: Promise; reply: Promise> } { const id = nextId(); const key = idKey(id) as string; const promise = new Promise>((resolve, reject) => { @@ -1697,7 +1715,8 @@ export class CodexController { }, timeoutMs); this.pending.set(key, { resolve, reject, timer }); }); - this.write({ id, method, params }).catch((err: Error) => { + const written = this.write({ id, method, params }); + void written.catch((err: Error) => { const entry = this.pending.get(key); if (!entry) return; clearTimeout(entry.timer); @@ -1705,12 +1724,13 @@ export class CodexController { entry.reject(err); }); if (HISTORY_MUTATIONS.has(method)) { - return promise.then((result) => { + const reply = promise.then((result) => { invalidateCodexHistory(this.target.workspaceId); return result; }); + return { reply, written }; } - return promise; + return { reply: promise, written }; } private async write(message: Record): Promise { diff --git a/src/renderer/services/chat/controller.ts b/src/renderer/services/chat/controller.ts index 573badb84..b1f600530 100644 --- a/src/renderer/services/chat/controller.ts +++ b/src/renderer/services/chat/controller.ts @@ -54,6 +54,7 @@ import { clearObservedQueued, dispatchQueuedMessage, emptyTabState, + isChatWriteRejected, type QueuedMessage, useChatStore, } from "./store"; @@ -1058,10 +1059,7 @@ export class ChatController { id?: string, queued = false, ): Promise { - if (!(await this.ensureRunning())) { - if (id) throw new Error("Claude is not running"); - return; - } + if (!(await this.ensureRunning())) throw new Error("Claude is not running"); // A program just started takes the tab's flags and pick first, so its // first turn runs with them. The chain settles on its own failures. await this.initializing; @@ -1076,6 +1074,7 @@ export class ChatController { // Kept before Claude echoes it, so it never shows as the user's. if (from) this.hooks.onRelayed?.({ id: String(message.uuid), from, at: Date.now() }); await this.write(message); + this.flushNow(); if (id) this.hooks.onPeerWritten?.(id); // A session the user named, or the tab, keeps that name; Claude makes it none. if (first && !this.named && !this.ownName) void this.nameSession(first); @@ -1153,7 +1152,7 @@ export class ChatController { this.state.queue, (update) => this.update(update), (next) => this.sendMessage(next.text, next.images, false, next.from, next.id, true), - () => false, + isChatWriteRejected, (id) => this.sawQueuedMessage(id), () => { this.flushNow(); diff --git a/src/renderer/services/chat/store.ts b/src/renderer/services/chat/store.ts index 78f38ad64..1f959d3b0 100644 --- a/src/renderer/services/chat/store.ts +++ b/src/renderer/services/chat/store.ts @@ -38,6 +38,18 @@ export interface QueuedMessage { device?: string; } +/** Reads the failure code the chat IPC carried across the process boundary. */ +export function chatSendErrorKind(error: unknown): string | undefined { + const kind = (error as { kind?: unknown } | null)?.kind; + return typeof kind === "string" ? kind : undefined; +} + +/** The agent knows no bytes of the requested message reached the program. */ +export function isChatWriteRejected(error: unknown): boolean { + const kind = chatSendErrorKind(error); + return kind === "chat.stdin-write-failed" || kind === "chat.not-running"; +} + /** Keeps the payload available for recovery until delivery has been confirmed. */ export function dispatchQueuedMessage( queue: readonly QueuedMessage[], diff --git a/tests/unit/renderer/services/chat/codex-chosen.test.ts b/tests/unit/renderer/services/chat/codex-chosen.test.ts index 57b32bfce..4cf9c85a3 100644 --- a/tests/unit/renderer/services/chat/codex-chosen.test.ts +++ b/tests/unit/renderer/services/chat/codex-chosen.test.ts @@ -7,6 +7,7 @@ */ import { afterEach, describe, expect, mock, test } from "bun:test"; import { CODEX_CONFIG_PROFILE_KEY } from "../../../../../src/renderer/services/chat/codex-config"; +import { ipcErr } from "../../../../../src/shared/ipc/result"; // The version the app tells Codex it is. (globalThis as { __APP_VERSION__?: string }).__APP_VERSION__ ??= "0.0.0"; @@ -16,13 +17,20 @@ type Message = Record & { params?: Record }; let codex: ((message: Message) => void) | undefined; /** Whether a Codex program fails to come up, as a fork's does when its thread cannot be read. */ let startFails = false; +let rejectTurnWrite = false; const realIpc = await import("../../../../../src/renderer/ipc/client"); mock.module("../../../../../src/renderer/ipc/client", () => ({ ...realIpc, ipcListen: () => () => {}, ipcCallResult: (_channel: string, method: string, args: Record) => { - if (method === "send") codex?.(args.message as Message); + if (method === "send") { + const message = args.message as Message; + if (rejectTurnWrite && message.method === "turn/start") { + return Promise.resolve(ipcErr("chat.stdin-write-failed", "broken pipe")); + } + codex?.(message); + } if (method === "codexStart") { return Promise.resolve({ ok: true, @@ -54,6 +62,7 @@ const sent: Message[] = []; afterEach(() => { for (const c of live.splice(0)) c.dispose(); startFails = false; + rejectTurnWrite = false; codex = undefined; sent.length = 0; }); @@ -188,6 +197,24 @@ describe("the pick a Codex tab keeps", () => { }); describe("delivering a Codex queue entry", () => { + test("reports failed stdin to the composer and keeps a failed queued attachment", async () => { + const c = tab(); + await c.prepareSend(); + rejectTurnWrite = true; + const image = { mediaType: "image/png", data: "aW1hZ2U=" }; + await expect(c.send("direct prompt", [image])).rejects.toMatchObject({ + kind: "chat.stdin-write-failed", + }); + expect(c.model.running).toBe(false); + expect(c.model.items).toEqual([]); + + c.enqueue("queued prompt", [image]); + await new Promise((resolve) => setImmediate(resolve)); + expect(c.state.queue).toMatchObject([ + { status: "failed", text: "queued prompt", images: [image] }, + ]); + }); + function line(c: Controller, message: Message, dir: "in" | "out" = "out") { c.receive({ seq: ++lineSeq, dir, message } as never); c.flushNow(); From a973c65ad7478831f45a6f0bfbcb4150096898ae Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:48:30 +0900 Subject: [PATCH 039/208] fix(chat): cancel renderer starts when the tab closes Co-Authored-By: Claude Opus 5.5 --- src/renderer/services/chat/codex-controller.ts | 3 +++ src/renderer/services/chat/controller.ts | 7 ++++++- .../services/chat/codex-before-handshake.test.ts | 15 ++++++++++++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/renderer/services/chat/codex-controller.ts b/src/renderer/services/chat/codex-controller.ts index 8eb7d3c2a..99e09a92b 100644 --- a/src/renderer/services/chat/codex-controller.ts +++ b/src/renderer/services/chat/codex-controller.ts @@ -337,6 +337,7 @@ export class CodexController { catalogOnly = false, forkSettings?: ReturnType, ): Promise { + if (this.disposed) return false; const { workspaceId, tabId, cwd, profileId } = this.target; this.update((prev) => ({ ...prev, phase: "starting", error: undefined })); let result: Awaited>; @@ -352,6 +353,7 @@ export class CodexController { this.update((prev) => ({ ...prev, phase: "failed", error: (err as Error).message })); return false; } + if (this.disposed) return false; if (!result.ok) { this.update((prev) => ({ ...prev, @@ -1734,6 +1736,7 @@ export class CodexController { } private async write(message: Record): Promise { + if (this.disposed) throw new Error("the tab closed"); const { workspaceId, tabId } = this.target; unwrapIpcResult(await ipcCallResult("chat", "send", { workspaceId, tabId, message })); } diff --git a/src/renderer/services/chat/controller.ts b/src/renderer/services/chat/controller.ts index b1f600530..66f876c3d 100644 --- a/src/renderer/services/chat/controller.ts +++ b/src/renderer/services/chat/controller.ts @@ -541,6 +541,7 @@ export class ChatController { } private async start(resume: StartArgs): Promise { + if (this.disposed) return false; const { workspaceId, tabId, cwd } = this.target; // Before the new program's initialize tells the mode it starts in. const mode = this.lastMode; @@ -548,17 +549,20 @@ export class ChatController { this.update((prev) => ({ ...prev, phase: "starting", error: undefined })); let result: Awaited>; try { + const prepared = await this.fromAnotherProfile(resume); + if (this.disposed) return false; result = await startChat({ workspaceId, tabId, cwd, - ...(await this.fromAnotherProfile(resume)), + ...prepared, ...profileArg(this.target.profileId), }); } catch (err) { this.update((prev) => ({ ...prev, phase: "failed", error: (err as Error).message })); return false; } + if (this.disposed) return false; if (!result.ok) { this.update((prev) => ({ ...prev, @@ -1832,6 +1836,7 @@ export class ChatController { } private async write(message: Record): Promise { + if (this.disposed) throw new Error("the tab closed"); const { workspaceId, tabId } = this.target; unwrapIpcResult(await ipcCallResult("chat", "send", { workspaceId, tabId, message })); } diff --git a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts index f9d0839c8..164d9f084 100644 --- a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts +++ b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts @@ -37,7 +37,9 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ } } if (method === "send") codex?.(args.message as Message); - if (method === "replay") return Promise.resolve({ ok: true, value: replayResponse?.() }); + if (method === "replay") { + return Promise.resolve(replayResponse?.()).then((value) => ({ ok: true, value })); + } if (method === "codexStart") { starts.push(args); onStart?.(); @@ -126,6 +128,17 @@ function tab(respond?: (message: Message) => unknown | Promise): Contro const order = () => sent.map((m) => m.method); +test("closing a Codex tab during replay cannot open a new program once replay ends", async () => { + const c = tab(); + const replay = Promise.withResolvers(); + replayResponse = () => replay.promise; + const opening = c.open(); + await c.close(); + replay.resolve({ found: false, running: false, truncated: false, lastSeq: 0 }); + await opening; + expect(starts).toEqual([]); +}); + test("resumes a Codex thread after agent replacement and queues against the new log", async () => { jest.useFakeTimers(); const c = tab(); From a6830b78569fa704c9d419777d47f4fad259f0d6 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:49:16 +0900 Subject: [PATCH 040/208] fix(chat): keep delayed output tied to its originating process Co-Authored-By: Claude Opus 5.5 --- internal/chat/service.go | 24 ++++++++++++++++-------- internal/chat/service_test.go | 23 +++++++++++++++++++++-- src/main/features/chat/host.ts | 27 +++++++++++++++++---------- tests/unit/main/chat/host.test.ts | 19 +++++++++++++++++++ 4 files changed, 73 insertions(+), 20 deletions(-) diff --git a/internal/chat/service.go b/internal/chat/service.go index 44b2c2049..f91753d55 100644 --- a/internal/chat/service.go +++ b/internal/chat/service.go @@ -249,7 +249,7 @@ func (s *Service) startSession(sess *session, p StartParams, env []string) (any, stderrDone := make(chan struct{}) go func() { defer close(stdoutDone) - sess.readStdout(stdout) + sess.readStdout(proc, stdout) }() go func() { defer close(stderrDone) @@ -582,16 +582,18 @@ func (sess *session) payload(e *entry) LinePayload { } // readStdout logs each line the program writes. -func (sess *session) readStdout(stdout io.Reader) { +func (sess *session) readStdout(proc *process, stdout io.Reader) { reader := bufio.NewReaderSize(stdout, 64*1024) for { line, err := readLine(reader, maxLineBytes) if len(line) > 0 { - sess.addOutput(line) + sess.addOutput(proc, line) } if errors.Is(err, errLineTooLong) { sess.mu.Lock() - sess.addSysLocked(map[string]any{"event": "dropped", "reason": "line too long"}) + if sess.proc == proc { + sess.addSysLocked(map[string]any{"event": "dropped", "reason": "line too long"}) + } sess.mu.Unlock() continue } @@ -601,16 +603,20 @@ func (sess *session) readStdout(stdout io.Reader) { } } -func (sess *session) addOutput(line []byte) { +// addOutput records only lines from the process that still owns the session. +func (sess *session) addOutput(proc *process, line []byte) { line = bytes.TrimRight(line, "\r\n") if len(bytes.TrimSpace(line)) == 0 { return } sess.mu.Lock() defer sess.mu.Unlock() + if sess.closed || sess.proc != proc { + return + } if json.Valid(line) { - if sess.proc != nil && isCodexCompaction(line) { - sess.proc.codexCompactions.Add(1) + if isCodexCompaction(line) { + proc.codexCompactions.Add(1) } sess.addLocked(DirOut, json.RawMessage(line), "") if sess.snaps != nil { @@ -690,10 +696,12 @@ func (p *process) writeLocked(data []byte, context *codexContext) (int, error) { func (p *process) stop() { p.stopOnce.Do(func() { _ = p.signalTerm() + timer := time.NewTimer(stopGrace) go func() { + defer timer.Stop() select { case <-p.done: - case <-time.After(stopGrace): + case <-timer.C: p.kill() } }() diff --git a/internal/chat/service_test.go b/internal/chat/service_test.go index d85f5802e..ec54eb42c 100644 --- a/internal/chat/service_test.go +++ b/internal/chat/service_test.go @@ -268,7 +268,7 @@ func TestSendLogsAConfirmedInputBeforeEarlyOutput(t *testing.T) { return len(data), nil } // Simulates output the CLI produced before Write returned. - sess.addOutput([]byte(`{"type":"result"}`)) + sess.addOutput(sess.proc, []byte(`{"type":"result"}`)) close(reading) <-unblock return len(data), nil @@ -316,7 +316,7 @@ func TestFailedStdinWriteReplaysFailureInsteadOfApproval(t *testing.T) { return 0, io.ErrClosedPipe }), } - sess.addOutput([]byte(`{"type":"control_request","request_id":"p","request":{"subtype":"can_use_tool"}}`)) + sess.addOutput(sess.proc, []byte(`{"type":"control_request","request_id":"p","request":{"subtype":"can_use_tool"}}`)) params := json.RawMessage(`{"workspaceId":"ws","tabId":"tab","message":{"type":"control_response","response":{"request_id":"p"}}}`) if _, err := service.Send(context.Background(), params); err == nil { t.Fatal("the write succeeded despite the broken pipe") @@ -707,6 +707,25 @@ func TestStopPublishesExitBeforeReleasingProcess(t *testing.T) { } } +func TestDelayedStdoutCannotBeAttributedToTheReplacement(t *testing.T) { + service := New() + rec := newRecorder() + service.SetEventSink(rec.sink) + sess, err := service.sessionFor(tabKey{workspaceID: "ws", tabID: "tab"}, "") + if err != nil { + t.Fatal(err) + } + old := &process{generation: "old"} + replacement := &process{generation: "current"} + sess.proc = replacement + sess.addOutput(old, []byte(`{"type":"result","subtype":"interrupted"}`)) + sess.addOutput(replacement, []byte(`{"type":"result","subtype":"success"}`)) + if len(rec.lines) != 1 || rec.lines[0].ProcessGeneration != "current" || + !bytes.Contains(rec.lines[0].Message, []byte("success")) { + t.Fatalf("a delayed result was attributed to the replacement: %v", describe(rec.lines)) + } +} + func TestAClosedTabsProgramSendsNothingToTheTabsNext(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("signals") diff --git a/src/main/features/chat/host.ts b/src/main/features/chat/host.ts index e75ef9165..9620e04e3 100644 --- a/src/main/features/chat/host.ts +++ b/src/main/features/chat/host.ts @@ -65,6 +65,7 @@ export type StartResult = interface Subscription { channel: AgentChannel; revision: number; + processes: Map; dispose: () => void; } @@ -78,7 +79,6 @@ export class ChatHost { private readonly subscriptions = new Map(); private readonly tabIntents = new Map(); private readonly closingTabs = new Map>(); - private readonly processGenerations = new Map(); /** Workspaces whose tabs have started a program through this host. */ private readonly workspaces = new Set(); private readonly disposeProviderReady: () => void; @@ -319,7 +319,7 @@ export class ChatHost { ...(intent ? { tabGeneration: intent.generation } : {}), }); } finally { - this.processGenerations.delete(key); + this.subscriptions.get(workspaceId)?.processes.delete(tabId); this.options.onProgramExit?.(workspaceId, tabId); } })(); @@ -515,27 +515,32 @@ export class ChatHost { this.subscriptions.clear(); this.workspaces.clear(); this.tabIntents.clear(); - this.processGenerations.clear(); } /** Drops exit and result events that belong to a replaced program. */ private acceptProcessEvent(event: string, payload: Record): boolean { - if (payload.replay === true || typeof payload.tabId !== "string") return true; - const key = `${payload.workspaceId}:${payload.tabId}`; + const { workspaceId, tabId, replay } = payload; + if (typeof workspaceId !== "string" || typeof tabId !== "string") return true; + const processes = this.subscriptions.get(workspaceId)?.processes; + if (!processes) return true; + const current = processes.get(tabId); const message = payload.message as { event?: unknown; processGeneration?: unknown } | undefined; if (event === "line" && payload.dir === "sys" && message?.event === "start") { + const startSeq = typeof payload.seq === "number" ? payload.seq : 0; if (typeof message.processGeneration === "string") { - this.processGenerations.set(key, message.processGeneration); - } else { - this.processGenerations.delete(key); + if (!replay || !current || startSeq > current.startSeq) { + processes.set(tabId, { generation: message.processGeneration, startSeq }); + } + } else if (!replay) { + processes.delete(tabId); } return true; } - const current = this.processGenerations.get(key); return ( + replay === true || typeof payload.processGeneration !== "string" || !current || - current === payload.processGeneration + current.generation === payload.processGeneration ); } @@ -590,6 +595,7 @@ export class ChatHost { const subscription: Subscription = { channel, revision: 0, + processes: new Map(), dispose: () => { offLine(); offExit(); @@ -615,6 +621,7 @@ export class ChatHost { switch (event.type) { case "reconnecting": subscription.revision += 1; + if (this.options.workspaceManager.isLocal?.(workspaceId)) subscription.processes.clear(); this.options.broadcast("held", { workspaceId }); return; case "ready": diff --git a/tests/unit/main/chat/host.test.ts b/tests/unit/main/chat/host.test.ts index ba81c2e3a..68939bc9d 100644 --- a/tests/unit/main/chat/host.test.ts +++ b/tests/unit/main/chat/host.test.ts @@ -544,6 +544,25 @@ describe("ChatHost", () => { expect(status).toEqual([`exit ${WS} ${TAB}`]); }); + test("reattach recognizes a missed start without reverting to an older replayed process", async () => { + const { channel, host, status } = setup(); + await host.start(WS, TAB, "/repo", {}); + const start = (seq: number, generation: string, replay: boolean) => + channel.emit("chat.line", { + workspaceId: WS, + tabId: TAB, + seq, + replay, + dir: "sys", + message: { event: "start", processGeneration: generation }, + }); + start(1, "old", false); + start(10, "current", true); + start(1, "old", true); + channel.emit("chat.exit", { workspaceId: WS, tabId: TAB, processGeneration: "current" }); + expect(status).toEqual([`exit ${WS} ${TAB}`]); + }); + test("holds on reconnecting and resyncs when the agent is back", async () => { const { channel, events, host, providerReady } = setup(); await host.start(WS, TAB, "/repo", {}); From c532769c1c0707c1a367299e4f10bc42da733d5e Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:51:44 +0900 Subject: [PATCH 041/208] fix(chat): close stdin after a partial JSON write Co-Authored-By: Claude Opus 5.5 --- internal/chat/service.go | 2 ++ internal/chat/service_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/internal/chat/service.go b/internal/chat/service.go index f91753d55..55124f258 100644 --- a/internal/chat/service.go +++ b/internal/chat/service.go @@ -298,6 +298,8 @@ func (s *Service) Send(_ context.Context, raw json.RawMessage) (any, error) { code := "chat.stdin-write-failed" if written > 0 { code = "chat.stdin-incomplete" + // The next request must not be appended to a partial JSON line. + _ = proc.stdin.Close() } failure, _ := json.Marshal(map[string]string{"event": "stdin-failed", "code": code}) sess.finishInput(slot, DirSys, failure) diff --git a/internal/chat/service_test.go b/internal/chat/service_test.go index ec54eb42c..52374070f 100644 --- a/internal/chat/service_test.go +++ b/internal/chat/service_test.go @@ -251,6 +251,38 @@ type testStdin func([]byte) (int, error) func (w testStdin) Write(data []byte) (int, error) { return w(data) } func (w testStdin) Close() error { return nil } +type partialStdin struct { + closed bool +} + +func (p *partialStdin) Write(data []byte) (int, error) { + if p.closed { + return 0, io.ErrClosedPipe + } + return len(data) - 1, io.ErrShortWrite +} + +func (p *partialStdin) Close() error { + p.closed = true + return nil +} + +func TestPartialWriteClosesTheUnframedStdin(t *testing.T) { + service := New() + sess, err := service.sessionFor(tabKey{workspaceID: "ws", tabID: "tab"}, "") + if err != nil { + t.Fatal(err) + } + pipe := &partialStdin{} + sess.proc = &process{stdin: pipe} + if err := send(t, service, "tab", "partially written"); err == nil { + t.Fatal("partial write reported success") + } + if !pipe.closed { + t.Fatal("a subsequent message could be written onto the partial JSON line") + } +} + func TestSendLogsAConfirmedInputBeforeEarlyOutput(t *testing.T) { service := New() rec := newRecorder() From 53c30eea6565a34dade7f4e6008a2e345767895a Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:52:54 +0900 Subject: [PATCH 042/208] fix(chat): join the stop regression test before teardown Co-Authored-By: Claude Opus 5.5 --- internal/chat/service_test.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/internal/chat/service_test.go b/internal/chat/service_test.go index 52374070f..a873a7026 100644 --- a/internal/chat/service_test.go +++ b/internal/chat/service_test.go @@ -716,7 +716,6 @@ func TestStopPublishesExitBeforeReleasingProcess(t *testing.T) { defer service.Close() exiting := make(chan struct{}) proceed := make(chan struct{}) - defer close(proceed) service.SetEventSink(func(event string, _ any) error { if event == EventExit { close(exiting) @@ -726,7 +725,15 @@ func TestStopPublishesExitBeforeReleasingProcess(t *testing.T) { }) startFake(t, service, "tab", nil) proc := service.lookup(tabKey{workspaceID: "ws", tabID: "tab"}).running() - go service.Stop(context.Background(), tabParams("tab")) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + _, _ = service.Stop(context.Background(), tabParams("tab")) + }() + defer func() { + close(proceed) + <-stopped + }() select { case <-exiting: case <-time.After(10 * time.Second): From 4c9c8742ec98989d20a8033b5f08d8c9fcab5928 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:57:09 +0900 Subject: [PATCH 043/208] fix(watch): order agent watch registration and cleanup Co-Authored-By: Claude Opus 5.5 --- internal/fs/service.go | 4 +- internal/fs/watch.go | 7 + internal/git/service.go | 7 +- src/main/features/fs/bridge/agent-watch.ts | 255 ++++++++++++-------- src/main/features/git/bridge/agent-watch.ts | 183 ++++++++------ tests/unit/main/fs/agent-watch.test.ts | 65 +++++ tests/unit/main/git/agent-watch.test.ts | 38 +++ 7 files changed, 370 insertions(+), 189 deletions(-) diff --git a/internal/fs/service.go b/internal/fs/service.go index 5ffa7d0da..16f076a2a 100644 --- a/internal/fs/service.go +++ b/internal/fs/service.go @@ -114,6 +114,6 @@ func Register(d *dispatch.Dispatcher, fsys *Service) { d.Register("fs.rename", fsys.Rename) d.Register("fs.copyFile", fsys.CopyFile) d.Register("fs.removeAll", fsys.RemoveAll) - d.Register("fs.watch", fsys.Watch) - d.Register("fs.unwatch", fsys.Unwatch) + d.RegisterOrderedBy("fs.watch", fsys.Watch, fsys.watchOrderKey) + d.RegisterOrderedBy("fs.unwatch", fsys.Unwatch, fsys.watchOrderKey) } diff --git a/internal/fs/watch.go b/internal/fs/watch.go index 9d3b965ae..86216a344 100644 --- a/internal/fs/watch.go +++ b/internal/fs/watch.go @@ -149,6 +149,13 @@ func (s *Service) Unwatch(ctx context.Context, raw json.RawMessage) (any, error) return struct{}{}, nil } +// watchOrderKey makes watch and unwatch of the same resolved directory share +// a dispatch queue, even when a caller stops waiting before the watch replies. +func (s *Service) watchOrderKey(raw json.RawMessage) string { + path, _ := s.parseWatchPath(raw) + return "fs.watch:" + path +} + func (s *Service) parseWatchPath(raw json.RawMessage) (string, error) { var p WatchParams if len(raw) == 0 || json.Unmarshal(raw, &p) != nil { diff --git a/internal/git/service.go b/internal/git/service.go index 6d21e5b11..0ca1455da 100644 --- a/internal/git/service.go +++ b/internal/git/service.go @@ -71,8 +71,11 @@ func Register(d *dispatch.Dispatcher, service *Service) { d.Register("git.diff", service.Diff) d.Register("git.commitDetail", service.CommitDetail) d.Register("git.changeStats", service.ChangeStats) - d.Register("git.watch", service.Watch) - d.Register("git.unwatch", service.Unwatch) + // Git directory resolution can run Git itself. Keep that work out of + // the dispatch scanner and order watch changes on their own lane. + watchQueue := func(json.RawMessage) string { return "git.watch" } + d.RegisterOrderedBy("git.watch", service.Watch, watchQueue) + d.RegisterOrderedBy("git.unwatch", service.Unwatch, watchQueue) d.Register("git.addToGitignore", service.AddToGitignore) d.Register("git.getFileContent", service.GetFileContent) d.Register("git.blob", service.Blob) diff --git a/src/main/features/fs/bridge/agent-watch.ts b/src/main/features/fs/bridge/agent-watch.ts index d37231673..5edc2a8ed 100644 --- a/src/main/features/fs/bridge/agent-watch.ts +++ b/src/main/features/fs/bridge/agent-watch.ts @@ -5,177 +5,220 @@ import type { BroadcastFn, WorkspaceManager } from "../../workspace/manager"; import { type AgentBackedProvider, isAgentBackedProvider } from "./provider"; const log = createLogger("fs"); - -const AgentFsChangedPayloadSchema = z.object({ - changes: z.array(FsChangeSchema), -}); +const AgentFsChangedPayloadSchema = z.object({ changes: z.array(FsChangeSchema) }); interface WatchSubscription { readonly provider: AgentBackedProvider; readonly unsubscribe: () => void; - readonly watchedRelPaths: Set; } -/** - * Bridges agent-emitted fs.changed events into renderer IPC events. - * - * The OS watcher itself lives inside the Go agent. This class only owns - * per-workspace event subscription and workspaceId fan-out. - */ +interface WorkspaceWatches { + readonly paths: Set; + readonly pending: Map>; + subscription?: WatchSubscription; +} + +/** Owns each workspace's desired paths and forwards changes from its current agent. */ export class AgentFsWatcher { - private readonly subscriptions = new Map(); + private readonly workspaces = new Map(); private readonly disposeProviderReady: () => void; + private disposed = false; constructor( private readonly manager: WorkspaceManager, private readonly broadcast: BroadcastFn, ) { - // After the channel dies, the next boot brings up a new agent with no - // watches, and the listeners on the old provider never fire again. Move - // existing subscriptions over as soon as the replacement is up rather - // than waiting for the renderer to watch again, which it does not do for - // directories that were already expanded. this.disposeProviderReady = manager.onProviderReady((workspaceId, provider) => { - if (this.subscriptions.has(workspaceId) && isAgentBackedProvider(provider)) { - this.ensureSubscription(workspaceId, provider); - } + const state = this.workspaces.get(workspaceId); + if (state && isAgentBackedProvider(provider)) this.bind(workspaceId, state, provider); }); } + /** Tracks a requested path before its RPC completes so teardown and rebind can see it. */ async watch(workspaceId: string, relPath: string): Promise { - const provider = await this.requireReadyAgentProvider(workspaceId); - const subscription = this.ensureSubscription(workspaceId, provider); - await provider.callAgentMethod("fs.watch", { relPath }); - subscription.watchedRelPaths.add(relPath); + const state = this.state(workspaceId); + await this.enqueue(workspaceId, state, relPath, async () => { + if (this.workspaces.get(workspaceId) !== state) return; + const provider = await this.requireReadyAgentProvider(workspaceId); + if (this.workspaces.get(workspaceId) !== state) return; + const subscription = this.bind(workspaceId, state, provider); + const wasWatched = state.paths.has(relPath); + state.paths.add(relPath); + try { + await provider.callAgentMethod("fs.watch", { relPath }); + } catch (error) { + if (!wasWatched && state.subscription === subscription) { + state.paths.delete(relPath); + if ((error as { code?: string }).code === "transport.timeout") { + await this.cleanup(workspaceId, provider, relPath); + } + } + throw error; + } + if (state.subscription !== subscription) { + await this.cleanup(workspaceId, provider, relPath); + } + }); } + /** Stops a path after any earlier watch or replay of that same path. */ async unwatch(workspaceId: string, relPath: string): Promise { - const provider = await this.requireReadyAgentProvider(workspaceId); - await provider.callAgentMethod("fs.unwatch", { relPath }); - - const subscription = this.subscriptions.get(workspaceId); - subscription?.watchedRelPaths.delete(relPath); - if (subscription && subscription.watchedRelPaths.size === 0) { - subscription.unsubscribe(); - this.subscriptions.delete(workspaceId); - } + const state = this.state(workspaceId); + await this.enqueue(workspaceId, state, relPath, async () => { + if (this.workspaces.get(workspaceId) !== state) return; + state.paths.delete(relPath); + const provider = await this.requireReadyAgentProvider(workspaceId); + if (this.workspaces.get(workspaceId) !== state) return; + if (state.paths.size > 0) this.bind(workspaceId, state, provider); + await provider.callAgentMethod("fs.unwatch", { relPath }); + }); } + /** Detaches the listener immediately and clears watches after pending registrations settle. */ disposeWorkspace(workspaceId: string): void { - const subscription = this.subscriptions.get(workspaceId); + const state = this.workspaces.get(workspaceId); + if (!state) return; + this.workspaces.delete(workspaceId); + const subscription = state.subscription; if (!subscription) return; subscription.unsubscribe(); - this.subscriptions.delete(workspaceId); + for (const relPath of state.paths) { + void this.enqueue(workspaceId, state, relPath, () => + this.cleanup(workspaceId, subscription.provider, relPath), + ); + } } + /** Stops new subscriptions and drops every workspace. */ dispose(): void { + this.disposed = true; this.disposeProviderReady(); - for (const subscription of this.subscriptions.values()) { - subscription.unsubscribe(); - } - this.subscriptions.clear(); + for (const workspaceId of this.workspaces.keys()) this.disposeWorkspace(workspaceId); } - /** - * Returns the workspace's subscription on `provider`. One made on an - * earlier provider is moved over: its listeners are dropped and its paths - * are registered with the new agent. - */ - private ensureSubscription( + /** Finds or creates the state before awaiting a provider. */ + private state(workspaceId: string): WorkspaceWatches { + if (this.disposed) throw new Error("file watcher is disposed"); + const existing = this.workspaces.get(workspaceId); + if (existing) return existing; + const state = { paths: new Set(), pending: new Map>() }; + this.workspaces.set(workspaceId, state); + return state; + } + + /** Orders RPCs for one path while allowing other directories to progress independently. */ + private enqueue( workspaceId: string, - provider: AgentBackedProvider, - ): WatchSubscription { - const existing = this.subscriptions.get(workspaceId); - if (existing?.provider === provider) return existing; - - existing?.unsubscribe(); - const subscription = this.subscribe(workspaceId, provider); - if (existing) { - for (const relPath of existing.watchedRelPaths) { - subscription.watchedRelPaths.add(relPath); + state: WorkspaceWatches, + relPath: string, + run: () => Promise, + ): Promise { + const previous = state.pending.get(relPath); + const pending = (previous ? previous.then(run, run) : run()).finally(() => { + if (state.pending.get(relPath) === pending) state.pending.delete(relPath); + if ( + this.workspaces.get(workspaceId) === state && + state.paths.size === 0 && + state.pending.size === 0 + ) { + state.subscription?.unsubscribe(); + this.workspaces.delete(workspaceId); } - this.replayWatches(workspaceId, provider, subscription); - } - return subscription; + }); + state.pending.set(relPath, pending); + return pending; } - private subscribe(workspaceId: string, provider: AgentBackedProvider): WatchSubscription { - const unsubscribeChanged = provider.onAgentEvent("fs.changed", (payload) => { + /** Moves the listener and desired paths to the new provider. */ + private bind( + workspaceId: string, + state: WorkspaceWatches, + provider: AgentBackedProvider, + ): WatchSubscription { + const previous = state.subscription; + if (previous?.provider === provider) return previous; + previous?.unsubscribe(); + + const offChanged = provider.onAgentEvent("fs.changed", (payload) => { + if (this.workspaces.get(workspaceId) !== state || state.subscription !== subscription) return; const parsed = AgentFsChangedPayloadSchema.safeParse(payload); if (!parsed.success || parsed.data.changes.length === 0) return; - this.broadcast("fs", "changed", { - workspaceId, - changes: parsed.data.changes, - }); + this.broadcast("fs", "changed", { workspaceId, changes: parsed.data.changes }); }); - - // Watch registrations live in the agent process, so a respawned agent - // starts with zero watches even though the channel recovered - // transparently. Replay the full set on the `ready` lifecycle event - // (successful reconnect handshake) — re-registering an existing watch is - // a no-op on the agent side, so the replay is safe even when the agent - // actually survived. - const unsubscribeLifecycle = provider.onAgentLifecycle((event) => { - if (event.type !== "ready") return; - const subscription = this.subscriptions.get(workspaceId); - if (!subscription) return; - this.replayWatches(workspaceId, provider, subscription); + const offLifecycle = provider.onAgentLifecycle((event) => { + if ( + event.type === "ready" && + this.workspaces.get(workspaceId) === state && + state.subscription === subscription + ) { + this.replay(workspaceId, state, subscription); + } }); - const subscription = { provider, unsubscribe: () => { - unsubscribeChanged(); - unsubscribeLifecycle(); + offChanged(); + offLifecycle(); }, - watchedRelPaths: new Set(), }; - this.subscriptions.set(workspaceId, subscription); + state.subscription = subscription; + if (previous) this.replay(workspaceId, state, subscription); return subscription; } - /** - * Registers every watched path with an agent that does not have them. - */ - private replayWatches( + /** Restores still-wanted paths and refreshes directories changed during the outage. */ + private replay( workspaceId: string, - provider: AgentBackedProvider, + state: WorkspaceWatches, subscription: WatchSubscription, ): void { - for (const relPath of subscription.watchedRelPaths) { - provider.callAgentMethod("fs.watch", { relPath }).catch((error: unknown) => { + for (const relPath of state.paths) { + void this.enqueue(workspaceId, state, relPath, async () => { + if ( + this.workspaces.get(workspaceId) !== state || + state.subscription !== subscription || + !state.paths.has(relPath) + ) { + return; + } + await subscription.provider.callAgentMethod("fs.watch", { relPath }); + if (state.subscription !== subscription) { + await this.cleanup(workspaceId, subscription.provider, relPath); + } + }).catch((error: unknown) => { log.warn( `fs.watch replay failed (workspace=${workspaceId}, relPath=${relPath}): ${(error as Error).message}`, ); }); } - // Changes made while the agent was down were never reported. Replay - // every watched directory as "added" so the renderer re-reads each one - // (the file tree treats an added directory as recreated) and its - // fs.changed hint refreshes git status. - if (subscription.watchedRelPaths.size > 0) { + if (state.paths.size > 0) { this.broadcast("fs", "changed", { workspaceId, - changes: [...subscription.watchedRelPaths].map((relPath) => ({ - relPath, - kind: "added" as const, - })), + changes: [...state.paths].map((relPath) => ({ relPath, kind: "added" as const })), }); } } - /** - * Resolves the workspace's agent-backed fs provider only after the - * underlying channel is ready. Without this gate, fs.watch IPC that - * arrives before SSH bootstrap or local channel boot completes would - * subscribe against the inert provider returned by createInitialFsProvider - * and throw `channel not yet wired` from the channel accessor. - */ + /** Releases a retired path on the provider that received its watch. */ + private async cleanup( + workspaceId: string, + provider: AgentBackedProvider, + relPath: string, + ): Promise { + try { + await provider.callAgentMethod("fs.unwatch", { relPath }); + } catch (error) { + log.warn( + `fs.unwatch cleanup failed (workspace=${workspaceId}, relPath=${relPath}): ${(error as Error).message}`, + ); + } + } + + /** Waits for the live agent instead of using the inert provider during bootstrap. */ private async requireReadyAgentProvider(workspaceId: string): Promise { const provider = await this.manager.getFs(workspaceId); - if (!isAgentBackedProvider(provider)) { + if (!isAgentBackedProvider(provider)) throw new Error("workspace agent provider is not available"); - } return provider; } } diff --git a/src/main/features/git/bridge/agent-watch.ts b/src/main/features/git/bridge/agent-watch.ts index 21d52fa86..fa12155ee 100644 --- a/src/main/features/git/bridge/agent-watch.ts +++ b/src/main/features/git/bridge/agent-watch.ts @@ -16,29 +16,29 @@ interface GitWatchEntry { readonly gitDir: string; readonly provider: AgentBackedProvider; readonly unsubscribe: () => void; + ready: Promise; + registering: boolean; } -/** - * Bridges Go-agent git.changed events into the existing status coalescer. - * The actual .git directory watcher lives in the agent, so this works for - * local and SSH workspaces through the same provider channel. - */ +/** Owns each workspace's agent-side Git watch and forwards changes to the coalescer. */ export class AgentGitWatcher { private readonly entries = new Map(); + private readonly pending = new Map>(); private readonly disposeProviderReady: () => void; + private disposed = false; constructor( private readonly manager: WorkspaceManager, private readonly onDirty: GitDirtyCallback, ) { - // A replacement agent booted after the channel died has no .git watch, - // and repo detection does not run again to ask for one. Re-register on - // the new agent and refresh status for what changed while none watched. - this.disposeProviderReady = manager.onProviderReady((workspaceId) => { + this.disposeProviderReady = manager.onProviderReady((workspaceId, provider) => { const entry = this.entries.get(workspaceId); - if (!entry) return; - this.watch(workspaceId, entry.gitDir).then( - () => this.onDirty(workspaceId), + if (!entry || !isAgentBackedProvider(provider) || entry.provider === provider) return; + const next = this.bind(workspaceId, entry.gitDir, provider); + void next.ready.then( + () => { + if (this.entries.get(workspaceId) === next) this.onDirty(workspaceId); + }, (error: unknown) => { log.warn( `git.watch rebind failed (workspace=${workspaceId}, gitDir=${entry.gitDir}): ${(error as Error).message}`, @@ -48,95 +48,120 @@ export class AgentGitWatcher { }); } + /** Registers a repository or joins its pending registration. */ async watch(workspaceId: string, gitDir: string): Promise { - const provider = this.requireAgentProvider(workspaceId); - const existing = this.entries.get(workspaceId); - if (existing?.gitDir === gitDir && existing.provider === provider) { - return; - } - if (existing?.provider === provider) { - await this.unwatch(workspaceId).catch(() => {}); - } else if (existing) { - // Made on an agent that has since been replaced; nothing to unwatch. - this.entries.delete(workspaceId); - existing.unsubscribe(); + if (this.disposed) throw new Error("Git watcher is disposed"); + const provider = this.manager.requireContext(workspaceId).fs; + if (!isAgentBackedProvider(provider)) + throw new Error("workspace agent provider is not available"); + await this.bind(workspaceId, gitDir, provider).ready; + } + + /** Detaches the entry now and unwatches on the agent that received the registration. */ + async unwatch(workspaceId: string): Promise { + const entry = this.entries.get(workspaceId); + if (!entry) return; + this.detach(workspaceId, entry); + await this.enqueue(workspaceId, async () => { + await entry.provider.callAgentMethod(GIT_UNWATCH_METHOD, { gitDir: entry.gitDir }); + }); + } + + /** Drops a workspace without blocking its removal broadcast. */ + disposeWorkspace(workspaceId: string): void { + void this.unwatch(workspaceId).catch((error: unknown) => { + log.warn( + `git.unwatch cleanup failed (workspace=${workspaceId}): ${(error as Error).message}`, + ); + }); + } + + /** Stops rebinding and drops all active and pending registrations. */ + dispose(): void { + this.disposed = true; + this.disposeProviderReady(); + for (const workspaceId of this.entries.keys()) this.disposeWorkspace(workspaceId); + } + + /** Publishes the entry before RPC so failure, removal and rebind all find its listeners. */ + private bind(workspaceId: string, gitDir: string, provider: AgentBackedProvider): GitWatchEntry { + const previous = this.entries.get(workspaceId); + if (previous?.gitDir === gitDir && previous.provider === provider) return previous; + if (previous) { + if (previous.provider === provider || previous.registering) + this.disposeWorkspace(workspaceId); + else this.detach(workspaceId, previous); } - const unsubscribeChanged = provider.onAgentEvent(GIT_CHANGED_EVENT, (payload) => { + const offChanged = provider.onAgentEvent(GIT_CHANGED_EVENT, (payload) => { + if (this.entries.get(workspaceId) !== entry) return; const parsed = AgentGitChangedPayloadSchema.safeParse(payload); - if (!parsed.success || parsed.data.gitDir !== gitDir) return; - this.onDirty(workspaceId); + if (parsed.success && parsed.data.gitDir === gitDir) this.onDirty(workspaceId); }); - - // The .git watcher lives in the agent process, so a respawned agent - // starts without it even though the channel recovered transparently. - // Replay the registration on the `ready` lifecycle event (successful - // reconnect handshake) — re-registering is a no-op agent-side when the - // watch already exists, so the replay is safe either way. - const unsubscribeLifecycle = provider.onAgentLifecycle((event) => { - if (event.type !== "ready") return; - if (this.entries.get(workspaceId)?.gitDir !== gitDir) return; - void provider.callAgentMethod(GIT_WATCH_METHOD, { gitDir }).catch((error: unknown) => { + const offLifecycle = provider.onAgentLifecycle((event) => { + if (event.type !== "ready" || this.entries.get(workspaceId) !== entry) return; + void this.enqueue(workspaceId, async () => { + if (this.entries.get(workspaceId) === entry) { + entry.registering = true; + try { + await provider.callAgentMethod(GIT_WATCH_METHOD, { gitDir }); + } finally { + entry.registering = false; + } + } + }).catch((error: unknown) => { log.warn( `git.watch replay failed (workspace=${workspaceId}, gitDir=${gitDir}): ${(error as Error).message}`, ); }); - // .git changes made while the agent was down were never reported. + // Refresh status for changes the disconnected agent did not see. this.onDirty(workspaceId); }); - await provider.callAgentMethod(GIT_WATCH_METHOD, { gitDir }); - this.entries.set(workspaceId, { + const entry: GitWatchEntry = { gitDir, provider, unsubscribe: () => { - unsubscribeChanged(); - unsubscribeLifecycle(); + offChanged(); + offLifecycle(); }, + ready: Promise.resolve(), + registering: true, + }; + this.entries.set(workspaceId, entry); + entry.ready = this.enqueue(workspaceId, async () => { + if (this.entries.get(workspaceId) !== entry) return; + try { + await provider.callAgentMethod(GIT_WATCH_METHOD, { gitDir }); + } catch (error) { + if (this.entries.get(workspaceId) === entry) { + if ((error as { code?: string }).code === "transport.timeout") { + this.disposeWorkspace(workspaceId); + } else { + this.detach(workspaceId, entry); + } + } + throw error; + } finally { + entry.registering = false; + } }); + return entry; } - async unwatch(workspaceId: string): Promise { - const entry = this.entries.get(workspaceId); - if (!entry) return; - this.entries.delete(workspaceId); - entry.unsubscribe(); - const provider = this.tryAgentProvider(workspaceId); - if (provider) { - await provider.callAgentMethod(GIT_UNWATCH_METHOD, { gitDir: entry.gitDir }); - } - } - - disposeWorkspace(workspaceId: string): void { - const entry = this.entries.get(workspaceId); - if (!entry) return; + /** Removes local ownership before any asynchronous cleanup. */ + private detach(workspaceId: string, entry: GitWatchEntry): void { this.entries.delete(workspaceId); entry.unsubscribe(); - const provider = this.tryAgentProvider(workspaceId); - void provider?.callAgentMethod(GIT_UNWATCH_METHOD, { gitDir: entry.gitDir }).catch(() => {}); } - dispose(): void { - this.disposeProviderReady(); - for (const workspaceId of Array.from(this.entries.keys())) { - this.disposeWorkspace(workspaceId); - } - } - - private requireAgentProvider(workspaceId: string): AgentBackedProvider { - const provider = this.manager.requireContext(workspaceId).fs; - if (!isAgentBackedProvider(provider)) { - throw new Error("workspace agent provider is not available"); - } - return provider; - } - - private tryAgentProvider(workspaceId: string): AgentBackedProvider | null { - try { - const provider = this.manager.requireContext(workspaceId).fs; - return isAgentBackedProvider(provider) ? provider : null; - } catch { - return null; - } + /** Orders replacement, replay and cleanup for one workspace's repository. */ + private enqueue(workspaceId: string, run: () => Promise): Promise { + const previous = this.pending.get(workspaceId); + const pending = (previous ? previous.then(run, run) : run()).finally(() => { + if (this.pending.get(workspaceId) === pending) this.pending.delete(workspaceId); + }); + this.pending.set(workspaceId, pending); + return pending; } } diff --git a/tests/unit/main/fs/agent-watch.test.ts b/tests/unit/main/fs/agent-watch.test.ts index 07e280b6f..54d994b1c 100644 --- a/tests/unit/main/fs/agent-watch.test.ts +++ b/tests/unit/main/fs/agent-watch.test.ts @@ -88,6 +88,71 @@ describe("AgentFsWatcher", () => { expect(broadcasts).toEqual([]); }); + it("keeps receiving changes when the last active watch is removed during another registration", async () => { + const { watcher, provider, emitChanged, broadcasts } = makeFixture(); + await watcher.watch(WORKSPACE_ID, "src"); + const started = Promise.withResolvers(); + const reply = Promise.withResolvers(); + provider.callAgentMethod.mockImplementationOnce(() => { + started.resolve(); + return reply.promise; + }); + const watch = watcher.watch(WORKSPACE_ID, "docs"); + await started.promise; + await watcher.unwatch(WORKSPACE_ID, "src"); + reply.resolve({}); + await watch; + + emitChanged({ changes: [{ relPath: "docs/new.md", kind: "added" }] }); + expect(broadcasts).toHaveLength(1); + }); + + it("orders collapse behind the same path's pending watch", async () => { + const { watcher, provider, emitLifecycle } = makeFixture(); + const started = Promise.withResolvers(); + const reply = Promise.withResolvers(); + provider.callAgentMethod.mockImplementationOnce(() => { + started.resolve(); + return reply.promise; + }); + const watch = watcher.watch(WORKSPACE_ID, "src"); + await started.promise; + const unwatch = watcher.unwatch(WORKSPACE_ID, "src"); + await Promise.resolve(); + await Promise.resolve(); + expect(provider.callAgentMethod.mock.calls).toEqual([["fs.watch", { relPath: "src" }]]); + reply.resolve({}); + await Promise.all([watch, unwatch]); + + emitLifecycle({ type: "ready" }); + expect(provider.callAgentMethod.mock.calls).toEqual([ + ["fs.watch", { relPath: "src" }], + ["fs.unwatch", { relPath: "src" }], + ]); + }); + + it("replays a pending path on replacement and cleans up its late registration", async () => { + const fixture = makeFixture(); + const started = Promise.withResolvers(); + const reply = Promise.withResolvers(); + fixture.provider.callAgentMethod.mockImplementationOnce(() => { + started.resolve(); + return reply.promise; + }); + const watch = fixture.watcher.watch(WORKSPACE_ID, "src"); + await started.promise; + const next = fixture.reboot(); + reply.resolve({}); + await watch; + await new Promise((resolve) => setImmediate(resolve)); + + expect(fixture.provider.callAgentMethod.mock.calls).toEqual([ + ["fs.watch", { relPath: "src" }], + ["fs.unwatch", { relPath: "src" }], + ]); + expect(next.provider.callAgentMethod.mock.calls).toEqual([["fs.watch", { relPath: "src" }]]); + }); + // Regression: a respawned agent process starts with zero fs watches, so the // watcher must replay every registered relPath when the channel reports a // successful reconnect handshake (`ready` lifecycle event). diff --git a/tests/unit/main/git/agent-watch.test.ts b/tests/unit/main/git/agent-watch.test.ts index 09d14468f..c6140510c 100644 --- a/tests/unit/main/git/agent-watch.test.ts +++ b/tests/unit/main/git/agent-watch.test.ts @@ -81,6 +81,44 @@ describe("AgentGitWatcher", () => { expect(dirty).not.toHaveBeenCalled(); }); + it("drops listeners after a failed registration before retrying the same repo", async () => { + const { watcher, provider, dirty, emitChanged, emitLifecycle } = makeFixture(); + provider.callAgentMethod.mockRejectedValueOnce(new Error("registration failed")); + await expect(watcher.watch(WORKSPACE_ID, "/repo/.git")).rejects.toThrow("registration failed"); + await watcher.watch(WORKSPACE_ID, "/repo/.git"); + emitChanged({ gitDir: "/repo/.git" }); + expect(dirty).toHaveBeenCalledTimes(1); + + provider.callAgentMethod.mockClear(); + emitLifecycle({ type: "ready" }); + await new Promise((resolve) => setImmediate(resolve)); + expect(provider.callAgentMethod.mock.calls).toEqual([["git.watch", { gitDir: "/repo/.git" }]]); + }); + + it("cleans up a pending registration on removal without reviving its listeners", async () => { + const { watcher, provider, dirty, emitChanged, emitLifecycle } = makeFixture(); + const started = Promise.withResolvers(); + const reply = Promise.withResolvers(); + provider.callAgentMethod.mockImplementationOnce(() => { + started.resolve(); + return reply.promise; + }); + const watch = watcher.watch(WORKSPACE_ID, "/repo/.git"); + await started.promise; + watcher.disposeWorkspace(WORKSPACE_ID); + reply.resolve({}); + await watch; + await new Promise((resolve) => setImmediate(resolve)); + + emitChanged({ gitDir: "/repo/.git" }); + emitLifecycle({ type: "ready" }); + expect(dirty).not.toHaveBeenCalled(); + expect(provider.callAgentMethod.mock.calls).toEqual([ + ["git.watch", { gitDir: "/repo/.git" }], + ["git.unwatch", { gitDir: "/repo/.git" }], + ]); + }); + // Regression: a respawned agent process starts without the .git watcher, so // the registration must be replayed when the channel reports a successful // reconnect handshake (`ready` lifecycle event). From 797c7f935f91f265d4e525c8d78e2c225a8adc00 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:58:23 +0900 Subject: [PATCH 044/208] fix(cli): compare the final probe on versionless pulls Co-Authored-By: Claude Opus 5.5 --- src/main/features/cli/file-pull.ts | 10 +++++++++- tests/unit/main/cli/file-pull.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/main/features/cli/file-pull.ts b/src/main/features/cli/file-pull.ts index 73407e0ae..fadb91b0a 100644 --- a/src/main/features/cli/file-pull.ts +++ b/src/main/features/cli/file-pull.ts @@ -221,7 +221,15 @@ async function copyFile( (bytes) => hash.update(bytes), ); if (first.version === undefined) { - await readBytes(peer, { path: remotePath, offset: 0, length: 1 }, signal, first); + // Older peers cannot pin a version. This final probe detects a size + // or prefix change; the remaining bytes have no snapshot guarantee. + const probe = await readBytes( + peer, + { path: remotePath, offset: 0, length: 1 }, + signal, + first, + ); + if (!probe.data.equals(first.data.subarray(0, 1))) throw changed(remotePath); } signal.throwIfAborted(); if (process.platform !== "win32") { diff --git a/tests/unit/main/cli/file-pull.test.ts b/tests/unit/main/cli/file-pull.test.ts index 2da008a70..ae64c3e31 100644 --- a/tests/unit/main/cli/file-pull.test.ts +++ b/tests/unit/main/cli/file-pull.test.ts @@ -428,6 +428,29 @@ describe("older hosts", () => { expect(reads(app)[1]?.requireVersion).toBeUndefined(); }); + test("keeps the destination when a same-size versionless source changes between chunks", async () => { + const before = Buffer.alloc(MAX_BYTES_CHUNK + 3, 1); + const after = Buffer.alloc(before.length, 2); + const target = path.join(cwd, "source.bin"); + await writeFile(target, "previous"); + const app = peer((request) => + piece( + request, + request.length === MAX_BYTES_CHUNK && request.offset === 0 ? before : after, + REMOTE, + null, + ), + ); + app.peers.devices = [{ ...DEVICE, schema: "0.13.3" }]; + + const result = await pull(app, "source.bin"); + + expect(result.stderr).toContain("changed while copying"); + expect(result.exitCode).not.toBe(0); + expect(await readFile(target, "utf8")).toBe("previous"); + expect(await readdir(cwd)).toEqual(["source.bin"]); + }); + test("detects a size change without a version", async () => { const app = peer((read) => piece(read, read.length === 1 ? Buffer.concat([DATA, DATA]) : DATA, REMOTE, null), From 60d32082e81bee069f4affb6a38549de855fb0f9 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:58:29 +0900 Subject: [PATCH 045/208] fix(hookserver): detect a missed CLI disconnect Co-Authored-By: Claude Opus 5.5 --- internal/hookserver/cli.go | 5 +-- internal/hookserver/cli_test.go | 68 +++++++++++++++++++++++++++++++++ internal/hookserver/server.go | 28 ++++++++------ 3 files changed, 85 insertions(+), 16 deletions(-) diff --git a/internal/hookserver/cli.go b/internal/hookserver/cli.go index 56faede05..67a5c49f0 100644 --- a/internal/hookserver/cli.go +++ b/internal/hookserver/cli.go @@ -3,7 +3,6 @@ package hookserver import ( "encoding/json" "fmt" - "io" "net" "time" ) @@ -89,9 +88,7 @@ func (s *Server) handleCLI(conn net.Conn, req hookWireRequest, verified bool) { } go func() { - // The client sends nothing after its frame, so the read ends only - // when it goes away or the answer closes the connection. - _, _ = io.Copy(io.Discard, conn) + waitForClientGone(conn) if val, ok := s.cliInflight.LoadAndDelete(requestID); ok { val.(net.Conn).Close() _ = sink("cli.cancel", CLICancelPayload{RequestID: requestID, WorkspaceID: req.WorkspaceID}) diff --git a/internal/hookserver/cli_test.go b/internal/hookserver/cli_test.go index ce39baddb..ffea9f00a 100644 --- a/internal/hookserver/cli_test.go +++ b/internal/hookserver/cli_test.go @@ -5,6 +5,8 @@ import ( "encoding/json" "errors" "net" + "os" + "sync" "sync/atomic" "testing" "time" @@ -91,6 +93,72 @@ func TestCLIClientGoneIsToldToMain(t *testing.T) { } } +// missedCloseConn models the Windows AF_UNIX read which misses an immediate +// peer close. A read deadline frees the stalled read so EOF can be observed. +type missedCloseConn struct { + net.Conn + deadline chan struct{} + peerGone chan struct{} + stop chan struct{} + armed sync.Once + firstRead bool +} + +// SetReadDeadline signals that the watcher can recover from the missed close. +func (c *missedCloseConn) SetReadDeadline(deadline time.Time) error { + if !deadline.IsZero() { + c.armed.Do(func() { close(c.deadline) }) + } + return nil +} + +// Read holds the first read after disconnect until its simulated deadline. +func (c *missedCloseConn) Read(p []byte) (int, error) { + if c.firstRead { + return c.Conn.Read(p) + } + c.firstRead = true + <-c.peerGone + select { + case <-c.deadline: + return 0, os.ErrDeadlineExceeded + case <-c.stop: + return 0, net.ErrClosed + } +} + +// TestCLIClientGoneAfterMissedRead verifies the CLI still cancels when the +// transport delivers EOF only after the first read has timed out. +func TestCLIClientGoneAfterMissedRead(t *testing.T) { + requests := make(chan CLIEventPayload, 1) + cancels := make(chan CLICancelPayload, 1) + srv := newTestServer(t, func(_ string, payload any) error { + switch event := payload.(type) { + case CLIEventPayload: + requests <- event + case CLICancelPayload: + cancels <- event + } + return nil + }) + server, client := net.Pipe() + conn := &missedCloseConn{Conn: server, deadline: make(chan struct{}), peerGone: make(chan struct{}), stop: make(chan struct{})} + defer server.Close() + defer close(conn.stop) + srv.handleCLI(conn, cliRequest(srv.Token()), false) + request := <-requests + _ = client.Close() + close(conn.peerGone) + select { + case event := <-cancels: + if event.RequestID != request.RequestID { + t.Fatalf("cancel = %+v, want request %s", event, request.RequestID) + } + case <-time.After(time.Second): + t.Fatal("CLI cancellation was lost when the read missed the disconnect") + } +} + // A request main never answers is answered with an error at the deadline. func TestCLIRequestTimesOut(t *testing.T) { srv := newTestServer(t, func(string, any) error { return nil }) diff --git a/internal/hookserver/server.go b/internal/hookserver/server.go index 2db858ea7..66dae60c5 100644 --- a/internal/hookserver/server.go +++ b/internal/hookserver/server.go @@ -64,7 +64,7 @@ const permissionRequestSubcmd = "permission-request" // printWatchSubcmd is the hook a `claude -p` run holds open while it goes on. const printWatchSubcmd = "print-watch" -// goneRecheck is how often watchGone reads again for a client that went +// goneRecheck is how often waitForClientGone reads again for a client that went // away. On Windows a read started as the client closes can wait on with // the close missed, where a read started again returns at once. const goneRecheck = 500 * time.Millisecond @@ -424,18 +424,9 @@ func (s *Server) handleConn(conn net.Conn) { // watchGone tells main when the client of a waiting hook goes away before // it is answered: Claude Code ends a PermissionRequest hook as the user // interrupts at its dialog, and the app must stop offering an answer; a -// print watch's client ends with its run. The client writes nothing after -// its request, so a read returns only once the connection closes, from -// either side, or as its deadline passes, when it reads again (see -// goneRecheck). +// print watch's client ends with its run. func (s *Server) watchGone(hookID string, conn net.Conn, req hookWireRequest) { - var b [1]byte - for { - _ = conn.SetReadDeadline(time.Now().Add(goneRecheck)) - if _, err := conn.Read(b[:]); err != nil && !errors.Is(err, os.ErrDeadlineExceeded) { - break - } - } + waitForClientGone(conn) if _, waiting := s.inflight.LoadAndDelete(hookID); !waiting { return } @@ -460,6 +451,19 @@ func (s *Server) watchGone(hookID string, conn net.Conn, req hookWireRequest) { } } +// waitForClientGone observes either side closing a connection after the +// request frame. Refreshing the read deadline lets Windows report an EOF +// that the read racing the peer's close missed (see goneRecheck). +func waitForClientGone(conn net.Conn) { + var b [1]byte + for { + _ = conn.SetReadDeadline(time.Now().Add(goneRecheck)) + if _, err := conn.Read(b[:]); err != nil && !errors.Is(err, os.ErrDeadlineExceeded) { + return + } + } +} + // ReleaseHooks answers every hook still waiting with the default response. // The daemon calls it when the app that heard them goes away: an app that // attaches next never heard them, so would never answer them. From 3d1824672197f1d368ea30aa94132db5189ba41c Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:58:29 +0900 Subject: [PATCH 046/208] test(cli): drive the exit watcher with a fake clock Co-Authored-By: Claude Opus 5.5 --- tests/unit/main/cli/claude-exit.test.ts | 44 ++++++++++++++++--------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/tests/unit/main/cli/claude-exit.test.ts b/tests/unit/main/cli/claude-exit.test.ts index 411ff76f6..8311c402a 100644 --- a/tests/unit/main/cli/claude-exit.test.ts +++ b/tests/unit/main/cli/claude-exit.test.ts @@ -3,7 +3,7 @@ * its tab goes quiet with the shell back in the foreground, running nothing, * its state is cleared. */ -import { afterEach, expect, test } from "bun:test"; +import { afterEach, beforeEach, expect, jest, test } from "bun:test"; import { ClaudeStatusBroker } from "../../../../src/main/features/claude/status"; import { ClaudeExitWatch } from "../../../../src/main/features/cli/claude-exit"; @@ -11,11 +11,20 @@ const QUIET_MS = 15; const T = { workspaceId: "w", tabId: "t" }; const open: Array<{ dispose(): void }> = []; +beforeEach(() => { + jest.useFakeTimers(); +}); afterEach(() => { for (const it of open.splice(0)) it.dispose(); + jest.useRealTimers(); }); -const settle = (ms = QUIET_MS * 3) => new Promise((r) => setTimeout(r, ms)); +/** Advances the quiet timer and lets the foreground lookup settle. */ +async function advance(ms = QUIET_MS): Promise { + jest.advanceTimersByTime(ms); + await Promise.resolve(); + await Promise.resolve(); +} type Front = { name: string; alone: boolean | undefined } | null; @@ -58,7 +67,7 @@ test("Claude killed mid-turn: the shell's prompt goes quiet, and its state ends" broker.set(T.workspaceId, T.tabId, "running"); print("zsh: killed claude\r\n% "); expect(broker.get(T.workspaceId, T.tabId)?.status).toBe("running"); - await settle(); + await advance(); expect(broker.get(T.workspaceId, T.tabId)).toBeNull(); }); @@ -66,16 +75,17 @@ test("an idle Claude that died is cleared too, so nothing types a prompt into th const { broker, print } = setup(() => front("-bash")); broker.set(T.workspaceId, T.tabId, "idle"); print(); - await settle(); + await advance(); expect(broker.get(T.workspaceId, T.tabId)).toBeNull(); }); test("Claude, or a program it runs, still in the foreground keeps its state", async () => { for (const program of [front("claude"), front("node"), front("vim"), null]) { - const { broker, print } = setup(() => program); + const { broker, looked, print } = setup(() => program); broker.set(T.workspaceId, T.tabId, "running"); print(); - await settle(); + await advance(); + expect(looked).toEqual(["w:t"]); expect(broker.get(T.workspaceId, T.tabId)?.status).toBe("running"); } }); @@ -85,43 +95,45 @@ test("looks only once output is quiet, and only at tabs with Claude's state", as broker.set(T.workspaceId, T.tabId, "running"); for (let i = 0; i < 4; i++) { print(); - await settle(QUIET_MS / 3); + await advance(QUIET_MS / 3); } expect(looked).toEqual([]); print("x", { workspaceId: "w", tabId: "plain" }); - await settle(); + await advance(); expect(looked).toEqual(["w:t"]); }); test("a Claude started while the program was looked up keeps its state", async () => { let answer: (program: Front) => void = () => {}; - const { broker, print } = setup(() => new Promise((r) => (answer = r))); + const { broker, looked, print } = setup(() => new Promise((r) => (answer = r))); broker.set(T.workspaceId, T.tabId, "running"); print(); - await settle(); + await advance(); + expect(looked).toEqual(["w:t"]); // The shell was in front when looked at; the wrapper then started Claude, // whose SessionStart lands before the answer. - await settle(5); + await advance(1); broker.set(T.workspaceId, T.tabId, "idle", undefined, null); answer(front("bash")); - await settle(5); + await advance(0); expect(broker.get(T.workspaceId, T.tabId)?.status).toBe("idle"); }); test("Claude started by a script keeps its state: the script's shell waits for it", async () => { // `bash run.sh` that runs claude: the script's bash leads the group in // front, with Claude in it, so the shell there is not alone. - const { broker, print } = setup(() => front("bash", false)); + const { broker, looked, print } = setup(() => front("bash", false)); broker.set(T.workspaceId, T.tabId, "running"); print(); - await settle(); + await advance(); + expect(looked).toEqual(["w:t"]); expect(broker.get(T.workspaceId, T.tabId)?.status).toBe("running"); }); test("from an agent that does not tell whether the shell is alone, its name is enough", async () => { - const { broker, print } = setup(() => front("zsh", undefined)); + const { broker, print } = setup(() => ({ name: "zsh", alone: undefined })); broker.set(T.workspaceId, T.tabId, "running"); print(); - await settle(); + await advance(); expect(broker.get(T.workspaceId, T.tabId)).toBeNull(); }); From 0e9ad18f8b3b67db4e4117eb3a7c92ec4db9ba84 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:58:29 +0900 Subject: [PATCH 047/208] test(stdioserver): drive idle watchdog ticks explicitly Co-Authored-By: Claude Opus 5.5 --- internal/stdioserver/host.go | 28 ++++--- internal/stdioserver/host_idle_test.go | 104 ++++++++++--------------- 2 files changed, 57 insertions(+), 75 deletions(-) diff --git a/internal/stdioserver/host.go b/internal/stdioserver/host.go index 7b40673d2..4177d2834 100644 --- a/internal/stdioserver/host.go +++ b/internal/stdioserver/host.go @@ -154,14 +154,14 @@ func (h *Host) Context() context.Context { // stampInbound records "now" (monotonic, relative to startMono) as the last // time an inbound line arrived. Single encoding point for lastInbound so the // watchdog's idleElapsed reads the same units. -func (h *Host) stampInbound() { - h.lastInbound.Store(int64(time.Since(h.startMono))) +func (h *Host) stampInbound(now time.Time) { + h.lastInbound.Store(int64(now.Sub(h.startMono))) } // idleElapsed reports how long it has been since the last inbound line, using // the monotonic clock so it cannot be skewed by wall-clock adjustments. -func (h *Host) idleElapsed() time.Duration { - return time.Since(h.startMono) - time.Duration(h.lastInbound.Load()) +func (h *Host) idleElapsed(now time.Time) time.Duration { + return now.Sub(h.startMono) - time.Duration(h.lastInbound.Load()) } // WriteFrame serializes one frame as NDJSON onto `out`. Used by the @@ -251,7 +251,7 @@ func (h *Host) Run() { continue } // Any inbound line proves the client is alive — reset the idle watchdog. - h.stampInbound() + h.stampInbound(time.Now()) if tooLong { if h.isAccepting() { h.rejectOversizedLine(line) @@ -433,23 +433,31 @@ func (h *Host) StartHeartbeat(interval time.Duration) { // orphan linger. A non-positive limit disables the watchdog. Call before Run(); // the goroutine stops when h.ctx is cancelled (drain). func (h *Host) StartIdleWatchdog(limit time.Duration) { + h.startIdleWatchdog(limit, func(check time.Duration) (<-chan time.Time, func()) { + ticker := time.NewTicker(check) + return ticker.C, ticker.Stop + }) +} + +// startIdleWatchdog checks elapsed time at each tick of the supplied clock. +func (h *Host) startIdleWatchdog(limit time.Duration, newTicker func(time.Duration) (<-chan time.Time, func())) { if limit <= 0 { return } - h.stampInbound() + h.stampInbound(time.Now()) // Check at limit/6 (independent of the old limit/3) so raising the limit // keeps the kill window tight: silence trips between limit and limit+limit/6. check := limit / 6 if check <= 0 { check = limit } + ticks, stop := newTicker(check) go func() { - ticker := time.NewTicker(check) - defer ticker.Stop() + defer stop() for { select { - case <-ticker.C: - if h.idleElapsed() >= limit { + case now := <-ticks: + if h.idleElapsed(now) >= limit { // Exit non-zero so the client distinguishes a watchdog reap // from a clean shutdown: its handleClose treats code 0 as a // terminal exit (no reconnect) but reconnects on any other diff --git a/internal/stdioserver/host_idle_test.go b/internal/stdioserver/host_idle_test.go index 74f46edd3..b6f5a8fed 100644 --- a/internal/stdioserver/host_idle_test.go +++ b/internal/stdioserver/host_idle_test.go @@ -21,85 +21,59 @@ func newTestHost() *Host { return New(dispatch.New(), strings.NewReader(""), io.Discard, logger) } -// Watchdog fires when no inbound line arrives within the limit. -func TestIdleWatchdogExitsWhenClientVanishes(t *testing.T) { +// TestIdleWatchdogWaitsForSilence advances watchdog ticks independently of +// the scheduler and checks that each inbound line restarts the idle window. +func TestIdleWatchdogWaitsForSilence(t *testing.T) { t.Parallel() host := newTestHost() + t.Cleanup(host.cancel) exited := make(chan int, 1) - host.exit = func(code int) { + host.exit = func(code int) { exited <- code } + ticks := make(chan time.Time) + stopped := make(chan struct{}) + const limit = time.Minute + host.startIdleWatchdog(limit, func(time.Duration) (<-chan time.Time, func()) { + return ticks, func() { close(stopped) } + }) + start := host.startMono.Add(time.Duration(host.lastInbound.Load())) + + deadline := time.NewTimer(2 * time.Second) + defer deadline.Stop() + tick := func(at time.Time) { + t.Helper() select { - case exited <- code: - default: + case ticks <- at: + case code := <-exited: + t.Fatalf("watchdog exited before tick %s with code %d", at.Sub(start), code) + case <-deadline.C: + t.Fatal("watchdog never accepted the tick") } } - - host.StartIdleWatchdog(30 * time.Millisecond) - + for i := 1; i <= 6; i++ { + inbound := start.Add(time.Duration(i) * limit / 2) + host.stampInbound(inbound) + tick(inbound.Add(limit / 4)) + } + last := start.Add(3 * limit) + tick(last.Add(limit - time.Nanosecond)) + tick(last.Add(limit)) select { case code := <-exited: - // Non-zero (EX_TEMPFAIL) so the client reconnects instead of treating - // the close as a clean shutdown. if code != IdleWatchdogExitCode { t.Fatalf("exit code = %d, want %d", code, IdleWatchdogExitCode) } - case <-time.After(2 * time.Second): - t.Fatal("idle watchdog did not terminate within 2s of client silence") + case <-deadline.C: + t.Fatal("watchdog did not exit at its idle limit") } + <-stopped } -// Watchdog must NOT fire while inbound lines keep resetting lastInbound. -// -// The window runs three limits, so a watchdog that ignored the traffic would -// fire in it. The limit is many times the stamping interval so that a busy CI -// runner stalling this goroutine for a while does not read as client silence: -// a 60ms limit with 20ms stamps failed on macOS runners. -func TestIdleWatchdogStaysAliveWithTraffic(t *testing.T) { - t.Parallel() - host := newTestHost() - exited := make(chan int, 1) - host.exit = func(code int) { - select { - case exited <- code: - default: - } - } - - const limit = 400 * time.Millisecond - host.StartIdleWatchdog(limit) - - stop := time.After(3 * limit) - tick := time.NewTicker(10 * time.Millisecond) - defer tick.Stop() - for { - select { - case <-tick.C: - host.stampInbound() - case code := <-exited: - t.Fatalf("watchdog fired during active traffic (code=%d)", code) - case <-stop: - return // survived the window without firing - } - } -} - -// A non-positive limit disables the watchdog entirely. +// TestIdleWatchdogDisabledWhenLimitNonPositive checks the disabled option +// without waiting for a watchdog that should never start. func TestIdleWatchdogDisabledWhenLimitNonPositive(t *testing.T) { - t.Parallel() host := newTestHost() - exited := make(chan int, 1) - host.exit = func(code int) { - select { - case exited <- code: - default: - } - } - - host.StartIdleWatchdog(0) - - select { - case <-exited: - t.Fatal("watchdog fired despite a non-positive (disabled) limit") - case <-time.After(100 * time.Millisecond): - // expected: no termination - } + host.startIdleWatchdog(0, func(time.Duration) (<-chan time.Time, func()) { + t.Fatal("disabled idle watchdog started a ticker") + return nil, func() {} + }) } From ed79c929f6a5022831469ded028bb840aff13a88 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:58:29 +0900 Subject: [PATCH 048/208] test(pty): verify concurrent writes keep frames whole Co-Authored-By: Claude Opus 5.5 --- internal/pty/service.go | 2 +- internal/pty/service_test.go | 43 +++++++++++++++++++++--------------- 2 files changed, 26 insertions(+), 19 deletions(-) diff --git a/internal/pty/service.go b/internal/pty/service.go index 25af7dae4..1a21db4ea 100644 --- a/internal/pty/service.go +++ b/internal/pty/service.go @@ -619,7 +619,7 @@ func (s *session) wiggleSIGWINCH() { _ = setSize(cols, rows) } -// write serializes and chunks input writes to preserve one-session input order. +// write keeps each input frame whole even when multiple RPCs write at once. func (s *session) write(data []byte) error { s.writeMu.Lock() defer s.writeMu.Unlock() diff --git a/internal/pty/service_test.go b/internal/pty/service_test.go index 4b46796b4..80ad783a2 100644 --- a/internal/pty/service_test.go +++ b/internal/pty/service_test.go @@ -19,33 +19,40 @@ import ( const testWorkspaceID = "00000000-0000-0000-0000-000000000001" -// TestBurstWriteFrameOrderingPreserved verifies sequential write RPCs return in order. -func TestBurstWriteFrameOrderingPreserved(t *testing.T) { +// TestConcurrentWritesKeepFramesWhole verifies that simultaneous RPCs do +// not splice their input together when each write spans several PTY chunks. +func TestConcurrentWritesKeepFramesWhole(t *testing.T) { t.Parallel() service, recorder := newTestService(t) tabID := "burst-order" spawnTestScript(t, service, tabID, ` -stty -echo -echo READY -cat +stty raw -echo +printf READY +exec cat `) recorder.requireTranscriptContains(t, "READY", 2*time.Second) - const frames = 80 - for i := range frames { - writeSession(t, service, tabID, fmt.Sprintf("FRAME%03d\n", i)) + a := strings.Repeat("A", 32*maxWriteChunkSize) + b := strings.Repeat("B", 32*maxWriteChunkSize) + start := make(chan struct{}) + done := make(chan error, 2) + for _, frame := range []string{a, b} { + params := mustJSON(t, WriteParams{WorkspaceID: testWorkspaceID, TabID: tabID, Data: frame}) + go func() { + <-start + _, err := service.Write(context.Background(), params) + done <- err + }() } - recorder.requireTranscriptContains(t, "FRAME079", 2*time.Second) - - transcript := recorder.transcript() - cursor := 0 - for i := range frames { - marker := fmt.Sprintf("FRAME%03d", i) - idx := strings.Index(transcript[cursor:], marker) - if idx < 0 { - t.Fatalf("missing %s after byte %d in transcript:\n%s", marker, cursor, transcript) + close(start) + recorder.requireDataBytesAtLeast(t, len("READY")+len(a)+len(b), 2*time.Second) + for range 2 { + if err := <-done; err != nil { + t.Fatal(err) } - cursor += idx + len(marker) + } + if got := strings.TrimPrefix(recorder.transcript(), "READY"); got != a+b && got != b+a { + t.Fatalf("PTY input frames interleaved or changed: got %d bytes", len(got)) } } From d724a1555c5b2162c1a38be9666c2df8304e24c0 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:58:29 +0900 Subject: [PATCH 049/208] test(agent): synchronize on dialer input and disconnects Co-Authored-By: Claude Opus 5.5 --- cmd/agent/daemon_connection_test.go | 82 ++++++++++++++++++++++++----- 1 file changed, 68 insertions(+), 14 deletions(-) diff --git a/cmd/agent/daemon_connection_test.go b/cmd/agent/daemon_connection_test.go index 3338ec7de..25e964a28 100644 --- a/cmd/agent/daemon_connection_test.go +++ b/cmd/agent/daemon_connection_test.go @@ -6,9 +6,11 @@ import ( "bufio" "encoding/json" "errors" + "net" "os" "os/exec" "path/filepath" + "runtime" "strings" "syscall" "testing" @@ -16,6 +18,7 @@ import ( "github.com/nexus-code/nexus-code/internal/agentrun" "github.com/nexus-code/nexus-code/internal/proto" + "golang.org/x/sys/unix" ) // dialerProcess is an `agent --dial` run as the SSH session runs it, its @@ -100,6 +103,50 @@ func daemonLog(runDir, root string) string { return string(data) } +// waitForUnreadOutput observes pending data without consuming it, so the +// connection really closes with unread bytes. +func waitForUnreadOutput(t *testing.T, conn net.Conn) { + t.Helper() + raw, err := conn.(*net.UnixConn).SyscallConn() + if err != nil { + t.Fatal(err) + } + _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second)) + defer func() { _ = conn.SetReadDeadline(time.Time{}) }() + var n int + var readErr error + if err := raw.Read(func(fd uintptr) bool { + var firstByte [1]byte + n, _, readErr = unix.Recvfrom(int(fd), firstByte[:], unix.MSG_PEEK) + return readErr != unix.EAGAIN && readErr != unix.EWOULDBLOCK + }); err != nil { + t.Fatal(err) + } + if n != 1 || readErr != nil { + t.Fatalf("daemon had no unread output: n=%d err=%v", n, readErr) + } +} + +// waitForDialerLog waits for the daemon to record its disconnect decision +// before another connection can turn that decision into a takeover. +func waitForDialerLog(t *testing.T, runDir, root string, matches func(string) bool) { + t.Helper() + deadline := time.NewTimer(3 * time.Second) + defer deadline.Stop() + poll := time.NewTicker(20 * time.Millisecond) + defer poll.Stop() + for { + if log := daemonLog(runDir, root); matches(log) { + return + } + select { + case <-poll.C: + case <-deadline.C: + t.Fatalf("daemon did not record the expected disconnect:\n%s", daemonLog(runDir, root)) + } + } +} + // A connection that ends with a reset rather than a close is a dialer gone // mid-output: the SSH session ended under it while the daemon still wrote, and // Linux reports a socket closed with unread data as reset. That is a dialer @@ -113,11 +160,14 @@ func TestDaemonSurvivesAResetConnection(t *testing.T) { sockPath := waitForSocket(t, runDir) first, readyA := readReady(t, sockPath) + defer first.Close() spawnOn(t, first, "tab", root, "while :; do echo tick; sleep 0.01; done") - // What the daemon sends meanwhile is left unread when the connection closes. - time.Sleep(300 * time.Millisecond) + waitForUnreadOutput(t, first) _ = first.Close() - time.Sleep(200 * time.Millisecond) + waitForDialerLog(t, runDir, root, func(log string) bool { + return strings.Contains(log, "dialer connection broke") || + (runtime.GOOS != "linux" && strings.Contains(log, "dialer disconnected cleanly")) + }) next, readyB := readReady(t, sockPath) defer next.Close() @@ -164,19 +214,20 @@ func TestDialerWithItsOutputClosedLeavesTheDaemonCleanly(t *testing.T) { if _, err := dialer.stdin.Write(append(spawn, '\n')); err != nil { t.Fatal(err) } - _ = dialer.nextLine(t) + for !strings.Contains(dialer.nextLine(t), `"event":"pty.data"`) { + } _ = dialer.stdout.Close() - time.Sleep(300 * time.Millisecond) + // The ping reply still has to be drained after the output pipe closes. + if _, err := dialer.stdin.Write([]byte(`{"id":"p","method":"ping"}` + "\n")); err != nil { + t.Fatal(err) + } _ = dialer.stdin.Close() - _ = dialer.exitCode(t, 5*time.Second) - - deadline := time.Now().Add(3 * time.Second) - for !strings.Contains(daemonLog(runDir, root), "dialer disconnected cleanly") { - if time.Now().After(deadline) { - t.Fatalf("the daemon did not see the dialer leave cleanly:\n%s", daemonLog(runDir, root)) - } - time.Sleep(20 * time.Millisecond) + if code := dialer.exitCode(t, 5*time.Second); code != 0 { + t.Fatalf("dialer exit code %d, want 0", code) } + waitForDialerLog(t, runDir, root, func(log string) bool { + return strings.Contains(log, "dialer disconnected cleanly") + }) if next, _ := readReady(t, sockPath); next != nil { _, _ = next.Write([]byte(`{"id":"bye","method":"agent.shutdown"}` + "\n")) _ = next.Close() @@ -272,7 +323,10 @@ func TestDaemonGreetsEachDialerWithReadyFirst(t *testing.T) { conn, _ := readReady(t, sockPath) spawnOn(t, conn, "tab", root, "yes") - time.Sleep(100 * time.Millisecond) + frames := newPtyFrames(conn) + if output, _ := frames.until(t, conn, 3*time.Second, func(text string, _ bool) bool { return text != "" }); output == "" { + t.Fatal("terminal never started writing") + } for i := 0; i < 60; i++ { next, first := readReady(t, sockPath) _ = conn.Close() From 3273a1cf8b99dec5633bb1b4c14c627f86184439 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:00:53 +0900 Subject: [PATCH 050/208] fix(chat): bound the retention of closed tab generations Co-Authored-By: Claude Opus 5.5 --- internal/chat/service.go | 64 +++++++++++++++++++++++++++++------ internal/chat/service_test.go | 52 ++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 10 deletions(-) diff --git a/internal/chat/service.go b/internal/chat/service.go index 55124f258..e0c6b189b 100644 --- a/internal/chat/service.go +++ b/internal/chat/service.go @@ -3,6 +3,7 @@ package chat import ( "bufio" "bytes" + "container/list" "context" "crypto/rand" "encoding/hex" @@ -29,8 +30,10 @@ type Service struct { mu sync.Mutex sink EventSink sessions map[tabKey]*session - closedTabs map[tabKey]map[string]struct{} - closed bool + closedTabs map[closedTabGeneration]struct{} + // closedOrder lets expiry and capacity discard the oldest closes first. + closedOrder list.List + closed bool } type tabKey struct { @@ -38,6 +41,22 @@ type tabKey struct { tabID string } +const ( + maxClosedTabGenerations = 4096 + // Covers a reconnect queue wait, an agent request, and login environment setup. + closedTabRetention = 2 * time.Minute +) + +type closedTabGeneration struct { + key tabKey + generation string +} + +type closedTabRecord struct { + closedTabGeneration + expiresAt time.Time +} + // session is one tab: its log, and the program running for it, if any. A // program that exits leaves the log, so the tab can still show the // conversation and start the program again on it. @@ -95,7 +114,7 @@ type process struct { // New constructs an empty service. func New() *Service { - return &Service{sessions: make(map[tabKey]*session), closedTabs: make(map[tabKey]map[string]struct{})} + return &Service{sessions: make(map[tabKey]*session), closedTabs: make(map[closedTabGeneration]struct{})} } // Register binds the chat.* methods onto the dispatcher. @@ -357,12 +376,7 @@ func (s *Service) CloseTab(_ context.Context, raw json.RawMessage) (any, error) } s.mu.Lock() if p.TabGeneration != "" { - closed := s.closedTabs[key] - if closed == nil { - closed = make(map[string]struct{}) - s.closedTabs[key] = closed - } - closed[p.TabGeneration] = struct{}{} + s.rememberClosedTabLocked(closedTabGeneration{key, p.TabGeneration}, time.Now()) } sess := s.sessions[key] s.mu.Unlock() @@ -479,10 +493,40 @@ func (s *Service) sessionFor(key tabKey, generation string) (*session, error) { // tabClosedLocked checks close intents even when they arrived before session creation. func (s *Service) tabClosedLocked(key tabKey, generation string) bool { - _, closed := s.closedTabs[key][generation] + s.expireClosedTabsLocked(time.Now()) + _, closed := s.closedTabs[closedTabGeneration{key, generation}] return s.closed || closed } +// rememberClosedTabLocked keeps a bounded window for rejecting late starts. +func (s *Service) rememberClosedTabLocked(tab closedTabGeneration, now time.Time) { + s.expireClosedTabsLocked(now) + if _, exists := s.closedTabs[tab]; exists { + return + } + if len(s.closedTabs) == maxClosedTabGenerations { + s.forgetClosedTabLocked(s.closedOrder.Front()) + } + s.closedTabs[tab] = struct{}{} + s.closedOrder.PushBack(closedTabRecord{tab, now.Add(closedTabRetention)}) +} + +// expireClosedTabsLocked purges expired generations without a background timer. +func (s *Service) expireClosedTabsLocked(now time.Time) { + for oldest := s.closedOrder.Front(); oldest != nil; oldest = s.closedOrder.Front() { + if now.Before(oldest.Value.(closedTabRecord).expiresAt) { + return + } + s.forgetClosedTabLocked(oldest) + } +} + +// forgetClosedTabLocked removes one generation from the index and expiry order. +func (s *Service) forgetClosedTabLocked(element *list.Element) { + record := s.closedOrder.Remove(element).(closedTabRecord) + delete(s.closedTabs, record.closedTabGeneration) +} + func staleTab(key tabKey) error { return proto.NewError("chat.tab-closed", "chat tab "+key.tabID+" is closed") } diff --git a/internal/chat/service_test.go b/internal/chat/service_test.go index a873a7026..3a1137494 100644 --- a/internal/chat/service_test.go +++ b/internal/chat/service_test.go @@ -679,6 +679,58 @@ func TestClosedTabGenerationRejectsLateStart(t *testing.T) { } } +func TestClosedTabGenerationsStayBounded(t *testing.T) { + useAttachRoot(t) + service := New() + defer service.Close() + ctx := context.Background() + const limit = maxClosedTabGenerations + closeTab := func(tabID, generation string) { + t.Helper() + raw, _ := json.Marshal(TabParams{WorkspaceID: "ws", TabID: tabID, TabGeneration: generation}) + if _, err := service.CloseTab(ctx, raw); err != nil { + t.Fatal(err) + } + } + for i := range limit + 1 { + closeTab(fmt.Sprintf("tab-%d", i), "first") + } + if got := len(service.closedTabs); got > limit { + t.Fatalf("recorded %d closed tabs, limit %d", got, limit) + } + for i := range limit + 1 { + closeTab("reopened", fmt.Sprintf("generation-%d", i)) + } + if got := len(service.closedTabs); got > limit { + t.Fatalf("recorded %d closed generations, limit %d", got, limit) + } + if got := service.closedOrder.Len(); got != len(service.closedTabs) { + t.Fatalf("expiry queue has %d records for %d closed generations", got, len(service.closedTabs)) + } + key := tabKey{workspaceID: "ws", tabID: "reopened"} + if _, err := service.sessionFor(key, fmt.Sprintf("generation-%d", limit)); err == nil { + t.Fatal("the latest closed generation could start") + } + if _, err := service.sessionFor(key, "generation-0"); err != nil { + t.Fatalf("the oldest generation was not evicted: %v", err) + } +} + +func TestClosedTabGenerationsExpire(t *testing.T) { + service := New() + key := tabKey{workspaceID: "ws", tabID: "tab"} + tab := closedTabGeneration{key, "old"} + service.mu.Lock() + service.rememberClosedTabLocked(tab, time.Now().Add(-closedTabRetention)) + service.mu.Unlock() + if _, err := service.sessionFor(key, tab.generation); err != nil { + t.Fatalf("the expired generation was not removed: %v", err) + } + if len(service.closedTabs) != 0 || service.closedOrder.Len() != 0 { + t.Fatal("the expired generation stayed in the index or expiry queue") + } +} + func TestStartCannotUseARemovedSession(t *testing.T) { for _, closeTab := range []bool{true, false} { name := "failed start" From 94f393200d7818e172e5c16e16c07e67a8816735 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:05:21 +0900 Subject: [PATCH 051/208] fix(workspace): release abandoned SSH browse sessions Co-Authored-By: Claude Opus 5.5 --- .../add-workspace/add-workspace-dialog.tsx | 7 + .../add-workspace/ssh-new-connection-view.tsx | 151 +++++++++++------- .../workspace/add-workspace/types.ts | 2 + .../workspace/ssh-new-connection-flow.test.ts | 48 +++++- 4 files changed, 145 insertions(+), 63 deletions(-) diff --git a/src/renderer/components/workspace/add-workspace/add-workspace-dialog.tsx b/src/renderer/components/workspace/add-workspace/add-workspace-dialog.tsx index bc604fa95..be0c262e3 100644 --- a/src/renderer/components/workspace/add-workspace/add-workspace-dialog.tsx +++ b/src/renderer/components/workspace/add-workspace/add-workspace-dialog.tsx @@ -59,6 +59,7 @@ export function AddWorkspaceDialog({ // Imperative handle to the directory picker — the footer "Add workspace" // button lives here in the shell and drives the picker's action through it. const pickerRef = useRef(null); + const cancelConnectRef = useRef<(() => void) | null>(null); // Open effect — reset + load SSH config hosts useEffect(() => { @@ -95,6 +96,7 @@ export function AddWorkspaceDialog({ // Handlers function closeAndAbort(): void { + cancelConnectRef.current?.(); onClose(); } @@ -152,6 +154,7 @@ export function AddWorkspaceDialog({ if (view === "ssh-server-list") { setView("main-list"); } else if (view === "ssh-new-connection") { + cancelConnectRef.current?.(); setPrefillProfile(null); setView("ssh-server-list"); } else if (view === "ssh-directory-picker") { @@ -233,6 +236,7 @@ export function AddWorkspaceDialog({ void) | null>; readonly view: ModalView; readonly pickerRef: React.RefObject; readonly browseSession: SshBrowseSession | WslBrowseSession | null; @@ -334,6 +339,7 @@ function ViewBody(props: ViewBodyProps): React.JSX.Element { const { view, pickerRef, + cancelConnectRef, browseSession, prefillProfile, onViewChange, @@ -396,6 +402,7 @@ function ViewBody(props: ViewBodyProps): React.JSX.Element { return ( void): void { export function SshNewConnectionView({ onConnected, + cancelConnectRef, configHosts, configHostsLoading, onConnectPhaseChange, @@ -117,7 +122,14 @@ export function SshNewConnectionView({ // 'success', 'error', or 'idle' (cancel), so "Connecting…" can never freeze // regardless of which await fails or when the component unmounts. // --------------------------------------------------------------------------- - const { state: connectState, run: runConnect, isPending } = useIpcAction(); + const { state: connectState, run: runConnect, cancel, isPending } = useIpcAction(); + useEffect(() => { + if (!cancelConnectRef) return; + cancelConnectRef.current = cancel; + return () => { + if (cancelConnectRef.current === cancel) cancelConnectRef.current = null; + }; + }, [cancelConnectRef, cancel]); // Bootstrap progress for the in-flight connect (agent upload/verify happens // inside openSshBrowseSession, before any sessionId exists — keyed by a @@ -292,13 +304,13 @@ export function SshNewConnectionView({ const capturedName = name.trim() || undefined; const profileId = crypto.randomUUID(); - runConnect(async (_signal) => { + runConnect(async (signal) => { // --- Stage 1: primary effect — establish SSH browse session --- // openBrowseSession is migrated to the IpcResult contract. // auth cancellation arrives as ipcErr("cancelled") so we throw an // AppError category:"cancelled" and the hook silently returns to idle. - // _signal is kept in the signature for forward compatibility (AbortSignal - // passthrough to openSshBrowseSession once it supports cancellation). + // Keep receiving the result after cancellation so a session created + // by main can be closed even when the view has already gone away. const result = await openSshBrowseSession({ host: capturedDest.host, user: capturedDest.user, @@ -326,63 +338,82 @@ export function SshNewConnectionView({ const sessionId = result.value.sessionId; const initialPath = result.value.initialPath; - // --- Stage 2: secondary effect — persist the connection profile --- - // Partial-failure policy: a failed save must NOT block the workspace flow. - // We run the save and inspect the result, but onConnected is called - // unconditionally as long as stage 1 succeeded. - const saveResult = await saveConnectionProfileResult({ - id: profileId, - host: capturedDest.host, - user: connectedUser, - port: capturedPort, - identityFile: capturedIdentityFile, - authMode: "interactive", - label: capturedName, - }); - - if (!saveResult.ok) { - // Save failed — build a retry callback that replays only the save step. - // The signal from this run() is no longer active after the function - // returns (the hook clears it in finally), so the retry is a fresh - // independent call not tied to any AbortController. - // - // "Retry save" re-runs only the secondary effect; it never re-connects - // or re-authenticates. The already-established session is untouched. - const retrySave = (): void => { - void saveConnectionProfileResult({ - id: profileId, - host: capturedDest.host, - user: connectedUser, - port: capturedPort, - identityFile: capturedIdentityFile, - authMode: "interactive", - label: capturedName, - }).then((retryResult) => { - if (!retryResult.ok) { - // Second attempt also failed — offer another retry via a fresh toast. - showSaveFailedToast(retrySave); - } - }); - }; - - // Non-blocking warning toast: the workspace flow proceeds immediately. - // The toast uses role="alert" (action toast) so it never auto-dismisses - // and the user can act on the "Retry save" button at their convenience. - showSaveFailedToast(retrySave); + let owned = true; + /** Release the browse session until the directory picker takes ownership. */ + const release = (): void => { + if (!owned) return; + owned = false; + void closeSshBrowseSession(sessionId); + }; + if (signal.aborted) { + release(); + return; } + signal.addEventListener("abort", release, { once: true }); + try { + // --- Stage 2: secondary effect — persist the connection profile --- + // Partial-failure policy: a failed save must NOT block the workspace flow. + // We run the save and inspect the result, but onConnected is called + // unconditionally as long as stage 1 succeeded. + const saveResult = await saveConnectionProfileResult({ + id: profileId, + host: capturedDest.host, + user: connectedUser, + port: capturedPort, + identityFile: capturedIdentityFile, + authMode: "interactive", + label: capturedName, + }); - // Complete the workspace flow regardless of save outcome. - // onConnected transitions the parent to the directory picker view. - onConnected({ - sessionId, - initialPath, - host: capturedDest.host, - user: connectedUser, - port: capturedPort, - identityFile: capturedIdentityFile, - profileId, - connectionProfileId: profileId, - }); + if (signal.aborted) return; + if (!saveResult.ok) { + // Save failed — build a retry callback that replays only the save step. + // The signal from this run() is no longer active after the function + // returns (the hook clears it in finally), so the retry is a fresh + // independent call not tied to any AbortController. + // + // "Retry save" re-runs only the secondary effect; it never re-connects + // or re-authenticates. The already-established session is untouched. + const retrySave = (): void => { + void saveConnectionProfileResult({ + id: profileId, + host: capturedDest.host, + user: connectedUser, + port: capturedPort, + identityFile: capturedIdentityFile, + authMode: "interactive", + label: capturedName, + }).then((retryResult) => { + if (!retryResult.ok) { + // Second attempt also failed — offer another retry via a fresh toast. + showSaveFailedToast(retrySave); + } + }); + }; + + // Non-blocking warning toast: the workspace flow proceeds immediately. + // The toast uses role="alert" (action toast) so it never auto-dismisses + // and the user can act on the "Retry save" button at their convenience. + showSaveFailedToast(retrySave); + } + + // Complete the workspace flow regardless of save outcome. + // onConnected transitions the parent to the directory picker view. + onConnected({ + sessionId, + initialPath, + host: capturedDest.host, + user: connectedUser, + port: capturedPort, + identityFile: capturedIdentityFile, + profileId, + connectionProfileId: profileId, + }); + owned = false; + } finally { + signal.removeEventListener("abort", release); + release(); + } }); } diff --git a/src/renderer/components/workspace/add-workspace/types.ts b/src/renderer/components/workspace/add-workspace/types.ts index 3433dd1fb..e3533dafc 100644 --- a/src/renderer/components/workspace/add-workspace/types.ts +++ b/src/renderer/components/workspace/add-workspace/types.ts @@ -96,6 +96,8 @@ export interface SshConnectionListViewProps { * All state is self-managed inside the view — not lifted to root. */ export interface SshNewConnectionViewProps { + /** Lets the dialog cancel synchronously when Back or Close is pressed. */ + readonly cancelConnectRef?: React.RefObject<(() => void) | null>; /** Callback after successful connect — transitions to directory picker. */ readonly onConnected: (params: SshBrowseSession) => void; /** ~/.ssh/config candidate list (pre-loaded by parent). */ diff --git a/tests/unit/renderer/components/workspace/ssh-new-connection-flow.test.ts b/tests/unit/renderer/components/workspace/ssh-new-connection-flow.test.ts index 414c85ef7..63a77b8dd 100644 --- a/tests/unit/renderer/components/workspace/ssh-new-connection-flow.test.ts +++ b/tests/unit/renderer/components/workspace/ssh-new-connection-flow.test.ts @@ -41,7 +41,7 @@ interface HookDispatcher { useState(initial: unknown): [unknown, (next: unknown) => void]; useCallback(cb: unknown, deps?: readonly unknown[]): unknown; useMemo(factory: () => unknown, deps?: readonly unknown[]): unknown; - useEffect(fn: () => void, deps?: readonly unknown[]): void; + useEffect(fn: () => undefined | (() => void), deps?: readonly unknown[]): void; useContext(ctx: unknown): unknown; useSyncExternalStore(subscribe: unknown, getSnapshot: () => unknown): unknown; } @@ -136,11 +136,13 @@ type FormElement = ReactElement<{ function mountView() { const refs: Array<{ current: unknown }> = []; const states: unknown[] = []; - let effects: Array<() => void> = []; + let effects: Array<() => undefined | (() => void)> = []; + let cleanups: Array<() => void> = []; let refCursor = 0; let stateCursor = 0; const phases: string[] = []; const onConnected = mock((_session: SshBrowseSession) => {}); + const cancelConnectRef = { current: null as (() => void) | null }; const dispatcher: HookDispatcher = { useRef(initial) { @@ -177,6 +179,7 @@ function mountView() { try { element = SshNewConnectionView({ onConnected, + cancelConnectRef, configHosts: [], configHostsLoading: false, onConnectPhaseChange: (phase) => phases.push(phase), @@ -185,13 +188,17 @@ function mountView() { } finally { reactInternals.H = previous; } - for (const fn of effects) fn(); + cleanups = effects.flatMap((fn) => fn() ?? []); return element; } return { render, + unmount: () => { + for (const cleanup of cleanups) cleanup(); + }, onConnected, + cancel: () => cancelConnectRef.current?.(), /** Submits the form from `form` (default: a fresh render). */ submit: (form: FormElement = render()) => form.props.onSubmit({ preventDefault: () => {} }), /** Phase reported to the parent by the latest render. */ @@ -302,3 +309,38 @@ describe("SSH connect flow — double-submit during in-flight connect", () => { expect(view.phase()).toBe("idle"); }); }); + +it("leaving before SSH browse completes closes the late session without saving or navigating", async () => { + const browse = Promise.withResolvers(); + openBrowseSession = () => browse.promise; + const view = mountView(); + view.submit(); + view.unmount(); + browse.resolve(ipcOk(SESSION)); + await new Promise((resolve) => setImmediate(resolve)); + + expect(callsTo("ssh.closeBrowseSession")).toEqual([ + { method: "ssh.closeBrowseSession", args: { sessionId: SESSION.sessionId } }, + ]); + expect(callsTo("connectionProfile.save")).toHaveLength(0); + expect(view.onConnected).not.toHaveBeenCalled(); +}); + +it("leaving during profile save releases the session and suppresses the obsolete result", async () => { + const saving = Promise.withResolvers(); + const save = Promise.withResolvers(); + saveProfile = () => { + saving.resolve(); + return save.promise; + }; + const view = mountView(); + view.submit(); + await saving.promise; + view.cancel(); + expect(callsTo("ssh.closeBrowseSession")).toHaveLength(1); + save.resolve(ipcErr("not-found", "profile unavailable")); + await save.promise; + await new Promise((resolve) => setImmediate(resolve)); + expect(view.onConnected).not.toHaveBeenCalled(); + expect(toastCalls).toHaveLength(0); +}); From 79f3b91d6517a65cff7730691df3cdf35b0aa29a Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:06:18 +0900 Subject: [PATCH 052/208] fix(git): report missing developer tools on macOS Co-Authored-By: Claude Opus 5.5 --- internal/git/info.go | 31 +++++++++++++++++++++++-- internal/git/info_test.go | 49 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/internal/git/info.go b/internal/git/info.go index dc0301b7c..01c3a17f8 100644 --- a/internal/git/info.go +++ b/internal/git/info.go @@ -95,7 +95,7 @@ func inspectGitCandidate(ctx context.Context, candidate string) (string, string, cmd.Env = append(cmd.Environ(), "GIT_TERMINAL_PROMPT=0") var stdout bytes.Buffer cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { + if err := runGitProbe(ctx, runtime.GOOS, cmd, (*exec.Cmd).Run); err != nil { return "", "", false } @@ -186,7 +186,7 @@ func runRevParse(ctx context.Context, cwd string) (topLevel, gitDir string, err cmd.Stdout = &stdout cmd.Stderr = &stderr - if runErr := cmd.Run(); runErr != nil { + if runErr := runGitProbe(ctx, runtime.GOOS, cmd, (*exec.Cmd).Run); runErr != nil { return "", "", runErr } @@ -210,6 +210,33 @@ func runRevParse(ctx context.Context, cwd string) (topLevel, gitDir string, err return logical, rebasePath(gd, tl, logical), nil } +// runGitProbe checks Apple's Git launcher for an active developer directory +// before running it. On a fresh Mac starting the launcher itself can prompt +// to install Command Line Tools. Third-party Git works independently. +func runGitProbe(ctx context.Context, goos string, cmd *exec.Cmd, run func(*exec.Cmd) error) error { + if cmd.Err != nil { + return cmd.Err + } + if goos == "darwin" { + path := filepath.Clean(cmd.Path) + if resolved, err := filepath.EvalSymlinks(path); err == nil { + path = resolved + } + if path == "/usr/bin/git" { + probe := exec.CommandContext(ctx, "/usr/bin/xcode-select", "--print-path") + probe.Env = cmd.Environ() + if err := run(probe); err != nil { + var exit *exec.ExitError + if ctx.Err() == nil && errors.As(err, &exit) { + return exec.ErrNotFound + } + return err + } + } + } + return run(cmd) +} + // logicalTopLevel returns the repository root git reports — with symlinks // resolved, so /private/tmp/repo on macOS for a workspace opened at /tmp/repo // — as reached from cwd by the path cwd was given in: /tmp/repo. Workspace diff --git a/internal/git/info_test.go b/internal/git/info_test.go index aee091877..04bbe4f2e 100644 --- a/internal/git/info_test.go +++ b/internal/git/info_test.go @@ -3,12 +3,61 @@ package git import ( "context" "encoding/json" + "errors" "os" + "os/exec" "path/filepath" "strings" "testing" ) +// TestGitProbeSkipsTheMacStubWithoutDeveloperTools simulates xcode-select on +// a fresh Mac. The probe must report Git missing before launching the stub. +func TestGitProbeSkipsTheMacStubWithoutDeveloperTools(t *testing.T) { + ctx := context.Background() + for _, args := range [][]string{{"--version"}, {"rev-parse", "--show-toplevel"}} { + cmd := exec.CommandContext(ctx, "/usr/bin/git", args...) + cmd.Env = append(cmd.Environ(), "DEVELOPER_DIR=/missing") + err := runGitProbe(ctx, "darwin", cmd, func(actual *exec.Cmd) error { + if actual.Path != "/usr/bin/xcode-select" || len(actual.Args) != 2 || actual.Args[1] != "--print-path" { + t.Fatalf("unexpected command %q", actual.Args) + } + if !strings.Contains(strings.Join(actual.Env, "\n"), "DEVELOPER_DIR=/missing") { + t.Fatal("probe used a different developer directory") + } + return &exec.ExitError{} + }) + if !errors.Is(err, exec.ErrNotFound) { + t.Fatalf("probe did not report Git missing for %q", args) + } + } +} + +// TestGitProbePreservesRepoErrors verifies that an installed Git's errors +// still reach Detect, including on a Mac using a third-party Git binary. +func TestGitProbePreservesRepoErrors(t *testing.T) { + ctx := context.Background() + notRepo := errors.New("not a git repository") + for _, path := range []string{"/usr/bin/git", "/opt/homebrew/bin/git"} { + cmd := exec.CommandContext(ctx, path, "rev-parse") + var calls []string + err := runGitProbe(ctx, "darwin", cmd, func(actual *exec.Cmd) error { + calls = append(calls, actual.Path) + if actual == cmd { + return notRepo + } + return nil + }) + want := []string{path} + if path == "/usr/bin/git" { + want = append([]string{"/usr/bin/xcode-select"}, path) + } + if strings.Join(calls, ",") != strings.Join(want, ",") || !errors.Is(err, notRepo) { + t.Fatalf("probe %s ran %v and returned %v, want %v and the Git error", path, calls, err, want) + } + } +} + // --------------------------------------------------------------------------- // git.info tests // --------------------------------------------------------------------------- From 160c5a536cb0d5a464d2b8a081ccce0485d00cc5 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:08:00 +0900 Subject: [PATCH 053/208] fix(terminal): discard queued input after a failed write Co-Authored-By: Claude Opus 5.5 --- src/main/features/pty/ipc.ts | 17 ++++-- .../services/error-surface/surface-error.ts | 1 + src/renderer/services/terminal/pty-client.ts | 61 ++++++++++++++----- src/shared/i18n/locales/en/errors.json | 3 + src/shared/i18n/locales/ko/errors.json | 3 + .../services/pty-client-write-order.test.ts | 48 ++++++++++++--- 6 files changed, 104 insertions(+), 29 deletions(-) diff --git a/src/main/features/pty/ipc.ts b/src/main/features/pty/ipc.ts index 1d8b6144c..cd5641d6a 100644 --- a/src/main/features/pty/ipc.ts +++ b/src/main/features/pty/ipc.ts @@ -344,11 +344,18 @@ export function registerPtyChannel(options: PtyChannelOptions): void { write: async (args: unknown) => { const { workspaceId, tabId, data } = validateArgs(c.write.args, args); options.onInput?.(workspaceId, tabId, data); - // write/resize/ack/kill are fire-and-forget from the renderer and no-op - // when the workspace is already gone — agentHost.call returns undefined - // in that case. Return ipcOk so the router stays silent on either path. - await agentHost.call("write", { workspaceId, tabId, data }); - return ipcOk(undefined); + try { + const sent = await agentHost.call("write", { workspaceId, tabId, data }); + // A held session or removed workspace intentionally drops input. + // Cancel the renderer's queued suffix as well. + if (sent === undefined) return ipcErr("cancelled", "Terminal input was skipped"); + return ipcOk(undefined); + } catch (error) { + return ipcErr("terminal-input-failed", String(error), { + category: "failed", + code: "terminal-input-failed", + }); + } }, resize: async (args: unknown) => { diff --git a/src/renderer/services/error-surface/surface-error.ts b/src/renderer/services/error-surface/surface-error.ts index fdbb9e34e..f50872207 100644 --- a/src/renderer/services/error-surface/surface-error.ts +++ b/src/renderer/services/error-surface/surface-error.ts @@ -162,6 +162,7 @@ function buildInvalidInputMessage(error: AppError): string { /** Friendly message for failed errors with fs / git code awareness. */ function buildFailedMessage(error: AppError): string { + if (error.code === "terminal-input-failed") return i18next.t("errors:terminal.inputFailed"); if (error.domain === "fs" && error.code) { return fsCodeToUserMessage(error.code) ?? i18next.t("errors:generic.failed"); } diff --git a/src/renderer/services/terminal/pty-client.ts b/src/renderer/services/terminal/pty-client.ts index 835d19aab..88f97e9bf 100644 --- a/src/renderer/services/terminal/pty-client.ts +++ b/src/renderer/services/terminal/pty-client.ts @@ -1,13 +1,18 @@ +import { AppErrorSchema, appErrorFailed } from "../../../shared/error/app-error"; import { TERMINAL_FLOW_CONTROL } from "../../../shared/pty/flow-control"; import type { ShellChoice } from "../../../shared/pty/shell"; import { ipcCallResult, ipcListen, unwrapIpcResult } from "../../ipc/client"; +import { surfaceError } from "../error-surface/surface-error"; import type { PtyClient, PtyClientOptions, SpawnedSession, TerminalDimensions } from "./types"; const pendingAckBytesBySessionKey = new Map(); const liveSessions = new Set(); const spawnPromisesBySessionKey = new Map>(); /** Input waiting for the session's write in flight; present while one is. */ -const queuedInputBySessionKey = new Map(); +interface InputQueue { + pending: string; +} +const queuedInputBySessionKey = new Map(); /** Input to type once the session's shell is ready; see `queueStartupInput`. */ const startupInputBySessionKey = new Map(); const textEncoder = new TextEncoder(); @@ -85,26 +90,53 @@ export function spawnSession( export function writeSession(workspaceId: string, tabId: string, data: string): void { const key = sessionKey(workspaceId, tabId); const queued = queuedInputBySessionKey.get(key); - if (queued !== undefined) { - queuedInputBySessionKey.set(key, queued + data); + if (queued) { + queued.pending += data; return; } - queuedInputBySessionKey.set(key, ""); - void sendInput(key, workspaceId, tabId, data); + const queue = { pending: "" }; + queuedInputBySessionKey.set(key, queue); + void sendInput(key, queue, workspaceId, tabId, data); } -async function sendInput(key: string, workspaceId: string, tabId: string, data: string) { +/** Drain a write queue only while it still belongs to the current session. */ +async function sendInput( + key: string, + queue: InputQueue, + workspaceId: string, + tabId: string, + data: string, +): Promise { let next = data; - while (next.length > 0) { - try { - await ipcCallResult("pty", "write", { workspaceId, tabId, data: next }); - } catch { - // A failed write is visible to the user; the input after it still goes out. + try { + while (next.length > 0) { + const result = await ipcCallResult("pty", "write", { workspaceId, tabId, data: next }); + if (queuedInputBySessionKey.get(key) !== queue) return; + if (!result.ok) { + if (result.kind === "cancelled") return; + const error = AppErrorSchema.safeParse(result); + surfaceError( + error.success + ? error.data + : appErrorFailed(result.message, { + code: "terminal-input-failed", + }), + { surface: "toast" }, + ); + return; + } + next = queue.pending; + queue.pending = ""; + } + } catch (error) { + if (queuedInputBySessionKey.get(key) === queue) { + surfaceError(appErrorFailed(String(error), { code: "terminal-input-failed" }), { + surface: "toast", + }); } - next = queuedInputBySessionKey.get(key) ?? ""; - queuedInputBySessionKey.set(key, ""); + } finally { + if (queuedInputBySessionKey.get(key) === queue) queuedInputBySessionKey.delete(key); } - queuedInputBySessionKey.delete(key); } interface StartupInput { @@ -199,6 +231,7 @@ export function forgetSession(workspaceId: string, tabId: string): void { liveSessions.delete(key); spawnPromisesBySessionKey.delete(key); pendingAckBytesBySessionKey.delete(key); + queuedInputBySessionKey.delete(key); dropStartupInput(key); } diff --git a/src/shared/i18n/locales/en/errors.json b/src/shared/i18n/locales/en/errors.json index 8f38e0370..cb6c2aa51 100644 --- a/src/shared/i18n/locales/en/errors.json +++ b/src/shared/i18n/locales/en/errors.json @@ -24,6 +24,9 @@ "failed": "The operation failed.", "bug": "Something went wrong. Check the log for details." }, + "terminal": { + "inputFailed": "Terminal input could not be sent. Check the terminal before typing again." + }, "open": { "TOO_LARGE": "File too large to open (max {{maxMb}} MB).", "failed": "Failed to open file." diff --git a/src/shared/i18n/locales/ko/errors.json b/src/shared/i18n/locales/ko/errors.json index 2425eb44b..379d1f109 100644 --- a/src/shared/i18n/locales/ko/errors.json +++ b/src/shared/i18n/locales/ko/errors.json @@ -24,6 +24,9 @@ "failed": "작업에 실패했습니다.", "bug": "오류가 발생했습니다. 로그를 확인하세요." }, + "terminal": { + "inputFailed": "터미널 입력을 보내지 못했습니다. 다시 입력하기 전에 터미널을 확인하세요." + }, "open": { "TOO_LARGE": "파일이 너무 커서 열 수 없습니다 (최대 {{maxMb}} MB).", "failed": "파일을 열지 못했습니다." diff --git a/tests/unit/renderer/services/pty-client-write-order.test.ts b/tests/unit/renderer/services/pty-client-write-order.test.ts index b3faf3176..f12fff2fd 100644 --- a/tests/unit/renderer/services/pty-client-write-order.test.ts +++ b/tests/unit/renderer/services/pty-client-write-order.test.ts @@ -8,7 +8,7 @@ import { beforeEach, describe, expect, it, mock } from "bun:test"; interface WriteCall { readonly tabId: string; readonly data: string; - settle(fail?: boolean): void; + settle(outcome?: "rejected" | "failed"): void; } const writes: WriteCall[] = []; @@ -20,8 +20,12 @@ mock.module("../../../../src/renderer/ipc/client", () => ({ writes.push({ tabId: args.tabId, data: args.data, - settle: (fail) => - fail ? reject(new Error("agent gone")) : resolve({ ok: true, value: undefined }), + settle: (outcome) => { + if (outcome === "rejected") reject(new Error("agent gone")); + else if (outcome === "failed") + resolve({ ok: false, kind: "terminal-input-failed", message: "PTY closed" }); + else resolve({ ok: true, value: undefined }); + }, }); }); }), @@ -29,10 +33,12 @@ mock.module("../../../../src/renderer/ipc/client", () => ({ unwrapIpcResult: (result: { value: unknown }) => result.value, })); -const { writeSession } = await import("../../../../src/renderer/services/terminal/pty-client"); +const { forgetSession, writeSession } = await import( + "../../../../src/renderer/services/terminal/pty-client" +); /** Lets the settled write's continuation run. */ -const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); +const flush = () => new Promise((resolve) => setImmediate(resolve)); beforeEach(() => { writes.length = 0; @@ -66,12 +72,34 @@ describe("writeSession", () => { for (const write of writes) write.settle(); }); - it("sends the input after a write that failed", async () => { - writeSession("ws", "tab-d", "a"); - writeSession("ws", "tab-d", "b"); - writes[0].settle(true); + for (const outcome of ["failed", "rejected"] as const) { + it(`drops queued Enter after a ${outcome} write, then accepts newly typed input`, async () => { + writeSession("ws", `tab-${outcome}`, "한"); + writeSession("ws", `tab-${outcome}`, "\r"); + writes[0].settle(outcome); + await flush(); + expect(writes.map((w) => w.data)).toEqual(["한"]); + + writeSession("ws", `tab-${outcome}`, "new"); + expect(writes.map((w) => w.data)).toEqual(["한", "new"]); + writes[1].settle(); + }); + } + + it("keeps pending input for a reopened session separate from the previous write", async () => { + writeSession("ws", "reopen", "old"); + writeSession("ws", "reopen", "old suffix"); + forgetSession("ws", "reopen"); + + writeSession("ws", "reopen", "new"); + writeSession("ws", "reopen", "new suffix"); + expect(writes.map((w) => w.data)).toEqual(["old", "new"]); + writes[0].settle("rejected"); await flush(); - expect(writes.map((w) => w.data)).toEqual(["a", "b"]); + expect(writes.map((w) => w.data)).toEqual(["old", "new"]); writes[1].settle(); + await flush(); + expect(writes.map((w) => w.data)).toEqual(["old", "new", "new suffix"]); + writes[2].settle(); }); }); From 15173d1ca3747a427062d818eb2077121e1ba215 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:50:57 +0900 Subject: [PATCH 054/208] refactor(workspace): move activation into state operations Co-Authored-By: Claude Opus 5.5 --- .../components/workbench/task-switcher.tsx | 2 +- src/renderer/services/agent-sessions/actions.ts | 2 +- src/renderer/services/cli/actions.ts | 3 ++- src/renderer/services/cli/note-actions.ts | 2 +- src/renderer/services/cli/placement.ts | 2 +- src/renderer/services/workspace/tasks.ts | 16 +--------------- .../state/operations/workspace-selection.ts | 16 ++++++++++++++++ 7 files changed, 23 insertions(+), 20 deletions(-) create mode 100644 src/renderer/state/operations/workspace-selection.ts diff --git a/src/renderer/components/workbench/task-switcher.tsx b/src/renderer/components/workbench/task-switcher.tsx index e62ff6cf9..d4fe83d83 100644 --- a/src/renderer/components/workbench/task-switcher.tsx +++ b/src/renderer/components/workbench/task-switcher.tsx @@ -14,7 +14,7 @@ import { portsLabel } from "../../../shared/pty/ports"; import type { WorkspaceMeta } from "../../../shared/types/workspace"; import { showAgentList } from "../../services/agent-sessions/actions"; import { useCodexWorkspaceStatus } from "../../services/agent-sessions/use-codex-status"; -import { activateWorkspace } from "../../services/workspace/tasks"; +import { activateWorkspace } from "../../state/operations/workspace-selection"; import { selectWorkspaceAggregateStatus, useClaudeStatusStore, diff --git a/src/renderer/services/agent-sessions/actions.ts b/src/renderer/services/agent-sessions/actions.ts index 8ae1178dc..262b705e7 100644 --- a/src/renderer/services/agent-sessions/actions.ts +++ b/src/renderer/services/agent-sessions/actions.ts @@ -14,6 +14,7 @@ import { useLayoutStore } from "@/state/stores/layout/store"; import { useTaskUIStore } from "@/state/stores/task-ui"; import { useUIStore } from "@/state/stores/ui"; import type { WorkspaceMeta } from "../../../shared/types/workspace"; +import { activateWorkspace } from "../../state/operations/workspace-selection"; import { showInAgentView } from "../agent-view/show"; import { existingCodexController } from "../chat/codex-controller"; import { existingChatController } from "../chat/controller"; @@ -22,7 +23,6 @@ import { groupOf } from "../cli/placement"; import { requestTabFocus } from "../tab-focus"; import { openTerminal } from "../terminal/open-terminal"; import { getTerminalController } from "../terminal/terminal-registry"; -import { activateWorkspace } from "../workspace/tasks"; import { typeText } from "./typed-input"; interface SessionRef { diff --git a/src/renderer/services/cli/actions.ts b/src/renderer/services/cli/actions.ts index c41430dd7..78d58e67e 100644 --- a/src/renderer/services/cli/actions.ts +++ b/src/renderer/services/cli/actions.ts @@ -25,6 +25,7 @@ import { hasProfile, PROFILE_AGENTS } from "../../../shared/agent-profiles/profi import type { CliUiOp } from "../../../shared/cli/ui"; import { untitledCacheUriFor } from "../../../shared/fs/workspace-uri"; import { sameShellChoice } from "../../../shared/pty/shell"; +import { activateWorkspace } from "../../state/operations/workspace-selection"; import { holdsInAgentView, showBesideCaller } from "../agent-view/show"; import { classifyUrl } from "../browser/url-classifier"; import { existingChatController } from "../chat/controller"; @@ -43,7 +44,7 @@ import { closeTerminal } from "../terminal/open-terminal"; import { queueStartupInput } from "../terminal/pty-client"; import { getTerminalController, whenTerminalController } from "../terminal/terminal-registry"; import type { TerminalController } from "../terminal/types"; -import { activateWorkspace, removeTask, startTask, taskStartOf } from "../workspace/tasks"; +import { removeTask, startTask, taskStartOf } from "../workspace/tasks"; import { type CliUiHandler, UiRequestError } from "./handler"; import type { LayoutOp } from "./layout-actions"; import { findTabs, groupOf, openTab, showOpenTab } from "./placement"; diff --git a/src/renderer/services/cli/note-actions.ts b/src/renderer/services/cli/note-actions.ts index efea52ef1..1d147daf9 100644 --- a/src/renderer/services/cli/note-actions.ts +++ b/src/renderer/services/cli/note-actions.ts @@ -7,6 +7,7 @@ import type { CliRecorder, CliUiOp } from "../../../shared/cli/ui"; import { type ToastInput, watchToasts } from "../../components/ui/toast"; import { openOrRevealNoteTab } from "../../state/operations/tabs"; +import { activateWorkspace } from "../../state/operations/workspace-selection"; import { pauseRecording, recorderElapsedMs, @@ -16,7 +17,6 @@ import { useRecorderStore, } from "../notes/recorder"; import { voiceAvailabilityNow, voiceLanguage } from "../voice/availability"; -import { activateWorkspace } from "../workspace/tasks"; import { type CliUiHandler, UiRequestError } from "./handler"; type NoteOp = Extract; diff --git a/src/renderer/services/cli/placement.ts b/src/renderer/services/cli/placement.ts index e86406a95..cd828202c 100644 --- a/src/renderer/services/cli/placement.ts +++ b/src/renderer/services/cli/placement.ts @@ -14,9 +14,9 @@ import { allLeaves } from "@/state/stores/layout/helpers"; import { useLayoutStore } from "@/state/stores/layout/store"; import { type CreateTabArgs, type Tab, useTabsStore } from "@/state/stores/tabs"; import type { CliPlacement } from "../../../shared/cli/ui"; +import { activateWorkspace } from "../../state/operations/workspace-selection"; import { holdsInAgentView, isShownInAgentView, showBesideCaller } from "../agent-view/show"; import { requestTabFocus } from "../tab-focus"; -import { activateWorkspace } from "../workspace/tasks"; export interface TabPlace { readonly groupId: string; diff --git a/src/renderer/services/workspace/tasks.ts b/src/renderer/services/workspace/tasks.ts index 838d8de68..ec076f83e 100644 --- a/src/renderer/services/workspace/tasks.ts +++ b/src/renderer/services/workspace/tasks.ts @@ -5,36 +5,22 @@ */ import type { RelaySender } from "../../../shared/chat/relay"; -import { createLogger } from "../../../shared/log/renderer"; import type { ChatAgent, TaskAgent } from "../../../shared/sessions/task-agent"; import type { WorkspaceMeta, WorkspaceTask } from "../../../shared/types/workspace"; import { ipcCallResult } from "../../ipc/client"; -import { useActiveStore } from "../../state/stores/active"; -import { useAgentViewStore } from "../../state/stores/agent-view"; +import { activateWorkspace } from "../../state/operations/workspace-selection"; import { useWorkspacesStore } from "../../state/stores/workspaces"; import { openAgentTab } from "../chat/agent-tab"; import { openTerminal } from "../terminal/open-terminal"; import { queueStartupInput } from "../terminal/pty-client"; import { quoteShellArgument } from "../terminal/shell-quote"; -const log = createLogger("tasks"); - /** Why a task operation failed: the IPC error kind and its message. */ export interface TaskFailure { readonly kind: string; readonly message: string; } -/** Activates a workspace here and tells main, which connects an SSH one. */ -export function activateWorkspace(id: string): void { - // Asked to show a workspace, the window shows the workspaces. - useAgentViewStore.getState().setMode("workspace"); - useActiveStore.getState().setActiveWorkspaceId(id); - void ipcCallResult("workspace", "activate", { id }).then((result) => { - if (!result.ok) log.warn(`workspace activate failed: ${result.message}`); - }); -} - /** * The line a terminal types to start an agent: the command, then the prompt * as one argument when there is one. Null when the command is empty. diff --git a/src/renderer/state/operations/workspace-selection.ts b/src/renderer/state/operations/workspace-selection.ts new file mode 100644 index 000000000..596f25f41 --- /dev/null +++ b/src/renderer/state/operations/workspace-selection.ts @@ -0,0 +1,16 @@ +import { createLogger } from "../../../shared/log/renderer"; +import { ipcCallResult } from "../../ipc/client"; +import { useActiveStore } from "../stores/active"; +import { useAgentViewStore } from "../stores/agent-view"; + +const log = createLogger("tasks"); + +/** Activates a workspace here and tells main, which connects an SSH one. */ +export function activateWorkspace(id: string): void { + // Asked to show a workspace, the window shows the workspaces. + useAgentViewStore.getState().setMode("workspace"); + useActiveStore.getState().setActiveWorkspaceId(id); + void ipcCallResult("workspace", "activate", { id }).then((result) => { + if (!result.ok) log.warn(`workspace activate failed: ${result.message}`); + }); +} From 9aac954614473f201d7ee9620497e8172df00e89 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:58:30 +0900 Subject: [PATCH 055/208] fix(workspace): persist the latest explicit selection Co-Authored-By: Claude Opus 5.5 --- src/main/features/claude/hook-handler.ts | 8 +- src/main/features/claude/index.ts | 4 +- src/main/features/cli/index.ts | 6 +- src/main/features/pty/ipc.ts | 4 +- src/main/features/pty/osc-notification.ts | 10 +-- src/main/features/workspace/ipc.ts | 33 ++++++- src/main/features/workspace/manager.ts | 27 +++--- src/renderer/app.tsx | 64 +++++--------- src/renderer/commands/domains/workspace.ts | 17 ++-- .../components/agent-view/agent-pane.tsx | 11 +-- src/renderer/components/files/panel.tsx | 54 ++++-------- src/renderer/components/workspace/panel.tsx | 12 +-- src/renderer/state/notification-click.ts | 8 +- .../state/operations/git-error-toasts.ts | 3 +- .../state/operations/workspace-selection.ts | 42 +++++++-- src/shared/ipc/contract.ts | 5 +- tests/unit/main/pty/ipc-shell-choice.test.ts | 2 +- .../manager-reattach-lifecycle.test.ts | 88 ++++++++++++++++++- .../operations/workspace-selection.test.ts | 63 +++++++++++++ 19 files changed, 304 insertions(+), 157 deletions(-) create mode 100644 tests/unit/renderer/state/operations/workspace-selection.test.ts diff --git a/src/main/features/claude/hook-handler.ts b/src/main/features/claude/hook-handler.ts index c16b80be7..c99da584f 100644 --- a/src/main/features/claude/hook-handler.ts +++ b/src/main/features/claude/hook-handler.ts @@ -103,9 +103,9 @@ export interface HookHandlerDeps { */ broadcastFn?: (channel: string, event: string, args: unknown) => void; /** - * Workspace activation callback — called when a notification is clicked. + * Connects the workspace so the clicked notification can reveal its tab. */ - activateWorkspace?: (workspaceId: string) => Promise; + connectWorkspace?: (workspaceId: string) => Promise; /** App window focus callback — called when a notification is clicked. */ focusMainWindow?: () => void; /** @@ -362,8 +362,8 @@ function fireOsNotification( const n = new NotificationCtor({ title, body }); n.on("click", () => { deps.focusMainWindow?.(); - deps.activateWorkspace?.(workspaceId)?.catch((err: unknown) => { - log.warn(`activateWorkspace failed: ${(err as Error).message}`); + deps.connectWorkspace?.(workspaceId)?.catch((err: unknown) => { + log.warn(`connectWorkspace failed: ${(err as Error).message}`); }); broadcastFn("pty", "notificationClick", { workspaceId, tabId }); }); diff --git a/src/main/features/claude/index.ts b/src/main/features/claude/index.ts index 71f99b82c..747623d03 100644 --- a/src/main/features/claude/index.ts +++ b/src/main/features/claude/index.ts @@ -28,7 +28,7 @@ export interface SetupClaudeFeatureOptions { tryGetAgentChannel( id: string, ): Promise; - activate(id: string): Promise; + connect(id: string): Promise; }; /** BrowserWindow.getFocusedWindow — for test injection. */ getFocusedWindow?: () => import("electron").BrowserWindow | null; @@ -131,7 +131,7 @@ export function setupClaudeFeature(options: SetupClaudeFeatureOptions): SetupCla electronNotificationCtor: options.electronNotificationCtor, broadcastFn, notificationsEnabled: options.notificationsEnabled, - activateWorkspace: (id) => workspaceManager.activate(id), + connectWorkspace: (id) => workspaceManager.connect(id), focusMainWindow: () => { const win = getActiveAppWindow(); if (!win) return; diff --git a/src/main/features/cli/index.ts b/src/main/features/cli/index.ts index 0a8ff9ae5..35e0e0dc5 100644 --- a/src/main/features/cli/index.ts +++ b/src/main/features/cli/index.ts @@ -78,7 +78,7 @@ export interface SetupCliFeatureOptions { ): WorkspaceMeta; getName(id: string): string | null; tryGetAgentChannel(id: string): Promise; - activate(id: string): Promise; + connect(id: string): Promise; }; claudeBroker: ClaudeStatusBroker; /** The agents of Claude sessions, for nexus agent. */ @@ -224,8 +224,8 @@ export function setupCliFeature(options: SetupCliFeatureOptions): CliFeature { const reveal = (workspaceId: string, tabId: string) => { options.focusWindow(); - workspaceManager.activate(workspaceId).catch((error: unknown) => { - log.warn(`activating ${workspaceId} failed: ${(error as Error).message}`); + workspaceManager.connect(workspaceId).catch((error: unknown) => { + log.warn(`connecting ${workspaceId} failed: ${(error as Error).message}`); }); options.broadcast("pty", "notificationClick", { workspaceId, tabId }); }; diff --git a/src/main/features/pty/ipc.ts b/src/main/features/pty/ipc.ts index 1d8b6144c..869608f40 100644 --- a/src/main/features/pty/ipc.ts +++ b/src/main/features/pty/ipc.ts @@ -49,7 +49,7 @@ export interface PtyChannelOptions { * so the shim is skipped. */ workspaceManager?: WorkspaceNameLookup & { - activate(id: string): Promise; + connect(id: string): Promise; getAgentChannel(workspaceId: string): Promise; getWrapperBinDir(workspaceId: string): string | null; getWrapperAgentBin(workspaceId: string): string | null; @@ -120,7 +120,7 @@ export function registerPtyChannel(options: PtyChannelOptions): void { getFocusedWindow: getFocusedAppWindow, isActiveTab: options.isActiveTab, notificationsEnabled: options.notificationsEnabled, - activateWorkspace: wm ? (id) => wm.activate(id) : undefined, + connectWorkspace: wm ? (id) => wm.connect(id) : undefined, focusMainWindow: () => { const win = getActiveAppWindow(); if (!win) return; diff --git a/src/main/features/pty/osc-notification.ts b/src/main/features/pty/osc-notification.ts index 757518893..6431eda94 100644 --- a/src/main/features/pty/osc-notification.ts +++ b/src/main/features/pty/osc-notification.ts @@ -48,8 +48,8 @@ export interface OscNotificationDispatcherDeps { isActiveTab?: (workspaceId: string, tabId: string) => boolean; /** Settings' OS notifications toggle, read at each notification. */ notificationsEnabled?: () => boolean; - /** Called on notification click to activate the workspace in main. */ - activateWorkspace?: (workspaceId: string) => Promise; + /** Called on notification click to connect the workspace. */ + connectWorkspace?: (workspaceId: string) => Promise; /** Called on notification click to bring the app window to the foreground. */ focusMainWindow?: () => void; /** Injected in tests to avoid real Electron Notification. */ @@ -186,9 +186,9 @@ export class OscNotificationDispatcher { // 1. Bring the app window to the foreground. this.deps.focusMainWindow?.(); - // 2. Activate the workspace in main (fire-and-forget). - this.deps.activateWorkspace?.(workspaceId)?.catch((err) => { - log.warn(`activateWorkspace failed: ${(err as Error).message}`); + // 2. Bring the workspace online for the tab being revealed. + this.deps.connectWorkspace?.(workspaceId)?.catch((err) => { + log.warn(`connectWorkspace failed: ${(err as Error).message}`); }); // 3. Tell the renderer to reveal the workspace + tab. diff --git a/src/main/features/workspace/ipc.ts b/src/main/features/workspace/ipc.ts index d2b910e4e..aeac0d607 100644 --- a/src/main/features/workspace/ipc.ts +++ b/src/main/features/workspace/ipc.ts @@ -132,10 +132,8 @@ export function registerWorkspaceChannel( manager.remove(id); return ipcOk(undefined); }, - activate: (args: unknown) => { - const { id } = validateArgs(c.activate.args, args); - return manager.activate(id); - }, + activate: workspaceConnectionHandler(manager, "activate"), + connect: workspaceConnectionHandler(manager, "connect"), testSsh: testSshHandler(dependencies.createSshChannel, dependencies.sshBootstrap), }, listen: { @@ -148,6 +146,33 @@ export function registerWorkspaceChannel( }); } +/** Report connection and selection outcomes through the IPC result envelope. */ +function workspaceConnectionHandler(manager: WorkspaceManager, action: "activate" | "connect") { + return async (args: unknown) => { + const { id } = validateArgs(c[action].args, args); + if (manager.getName(id) === null) { + return ipcErr("not-found", `Workspace not found: ${id}`, { category: "failed" }); + } + try { + await manager[action](id); + return ipcOk(undefined); + } catch (error) { + const code = sshErrorCodeFromError(error); + if (isSshAuthCancellation(error) || isAbortError(error) || code === "ssh.auth-cancelled") { + return ipcErr("cancelled", "Workspace connection cancelled", { category: "cancelled" }); + } + if (code !== undefined) { + return ipcErr("connection-failed", messageForSshErrorCode(code), { + category: "failed", + domain: "ssh", + code, + }); + } + return ipcErr("connection-failed", String(error), { category: "bug" }); + } + }; +} + /** * Builds the SSH workspace validation handler with an injectable channel * factory so unit tests can exercise lifecycle behavior without OpenSSH. diff --git a/src/main/features/workspace/manager.ts b/src/main/features/workspace/manager.ts index cda4364ae..7d9766184 100644 --- a/src/main/features/workspace/manager.ts +++ b/src/main/features/workspace/manager.ts @@ -397,6 +397,7 @@ export class WorkspaceManager { */ private readonly degradedRecoveryTimers = new Map(); private activeId: string | null = null; + private selectionVersion = 0; constructor( globalStorage: GlobalStorage, @@ -1273,19 +1274,25 @@ export class WorkspaceManager { return undefined; } + /** + * Record a user's selection before connecting. Readiness can finish in + * any order, so only the latest selection can update recency afterward. + */ async activate(id: string): Promise { - const ctx = this.contexts.get(id); - if (!ctx) { - throw new Error(`workspace not found: ${id}`); - } + const ctx = this.requireContext(id); + this.stateService.setState({ lastActiveWorkspaceId: id }); + this.activeId = id; + const version = ++this.selectionVersion; await this.ensureProviderReady(ctx); - this.activeId = id; - this.stateService.setState({ lastActiveWorkspaceId: id }); - // Explicit activation counts as "opening" the workspace — bump recency so - // it sorts to the top of the list on the next load. Startup restoration - // does not route through activate(), so it never reorders the list. - this.touchLastOpened(id); + if (version === this.selectionVersion && this.contexts.get(id) === ctx) { + this.touchLastOpened(id); + } + } + + /** Bring a workspace online for its existing views without changing selection. */ + async connect(id: string): Promise { + await this.ensureProviderReady(this.requireContext(id)); } async ensureRemoteLspServer( diff --git a/src/renderer/app.tsx b/src/renderer/app.tsx index 0dd5cb05d..356d686d4 100644 --- a/src/renderer/app.tsx +++ b/src/renderer/app.tsx @@ -40,6 +40,7 @@ import { LOOK_AREA_ATTR } from "./services/chat/look-area"; import { initializeEditorServices } from "./services/editor"; import { rehydrateLspForWorkspace } from "./services/editor/model/cache"; import { countUnsavedBuffers } from "./services/editor/save/unsaved-guard"; +import { activateWorkspace, focusWorkspace } from "./state/operations/workspace-selection"; import { useActiveStore } from "./state/stores/active"; import { useAddWorkspaceUIStore } from "./state/stores/add-workspace-ui"; import { useAgentViewStore } from "./state/stores/agent-view"; @@ -146,62 +147,43 @@ export function App() { // When the active workspace disappears (deleted, etc.), fall back to its // parent for a task, else to the first workspace, or null. useEffect(() => { + if (useActiveStore.getState().activeWorkspaceId !== activeWorkspaceId) return; if (activeWorkspaceId && !workspaces.some((w) => w.id === activeWorkspaceId)) { const parentId = activeParentIdRef.current; const next = (parentId !== null && workspaces.some((w) => w.id === parentId) ? parentId : visibleWorkspaces(workspaces)[0]?.id) ?? null; - setActiveWorkspaceId(next); - if (next) { - // Fire-and-forget: UI is already updated; notify main of workspace switch. - void ipcCallResult("workspace", "activate", { id: next }).then((result) => { - if (!result.ok) log.warn(`workspace activate failed: ${result.message}`); - }); - } + if (next) activateWorkspace(next, "preserve"); + else focusWorkspace(null, "preserve"); } - }, [workspaces, activeWorkspaceId, setActiveWorkspaceId]); + }, [workspaces, activeWorkspaceId]); // Read from the stores when called, so it stays the same function across // switches and the sidebar's rows are not handed a new one each time. - const handleSelectWorkspace = useCallback( - (id: string) => { - // The sidebar row stands for the workspace and its tasks; clicking the - // row the active task belongs to keeps that task. - const activeWorkspaceId = useActiveStore.getState().activeWorkspaceId; - const workspaces = useWorkspacesStore.getState().workspaces; - if ( - activeWorkspaceId !== null && - activeWorkspaceId !== id && - rootWorkspaceId(workspaces, activeWorkspaceId) === id - ) { - return; - } - setActiveWorkspaceId(id); - // Fire-and-forget: UI is already updated; notify main of workspace switch. - void ipcCallResult("workspace", "activate", { id }).then((result) => { - if (!result.ok) log.warn(`workspace activate failed: ${result.message}`); - }); - }, - [setActiveWorkspaceId], - ); + const handleSelectWorkspace = useCallback((id: string) => { + // The sidebar row stands for the workspace and its tasks; clicking the + // row the active task belongs to keeps that task. + const activeWorkspaceId = useActiveStore.getState().activeWorkspaceId; + const workspaces = useWorkspacesStore.getState().workspaces; + if ( + activeWorkspaceId !== null && + activeWorkspaceId !== id && + rootWorkspaceId(workspaces, activeWorkspaceId) === id + ) { + return; + } + activateWorkspace(id, "preserve"); + }, []); const handleAddWorkspace = useCallback(() => { openAddWorkspace(); }, [openAddWorkspace]); - const handleWorkspaceCreated = useCallback( - async (meta: WorkspaceMeta) => { - useAgentViewStore.getState().setMode("workspace"); - setActiveWorkspaceId(meta.id); - // Fire-and-forget: UI is already updated; notify main of new workspace activation. - void ipcCallResult("workspace", "activate", { id: meta.id }).then((result) => { - if (!result.ok) log.warn(`workspace activate failed: ${result.message}`); - }); - // Tab seeding is handled by on first mount. - }, - [setActiveWorkspaceId], - ); + const handleWorkspaceCreated = useCallback(async (meta: WorkspaceMeta) => { + activateWorkspace(meta.id); + // Tab seeding is handled by on first mount. + }, []); const handleCloseAddWorkspace = useCallback(() => { closeAddWorkspace(); diff --git a/src/renderer/commands/domains/workspace.ts b/src/renderer/commands/domains/workspace.ts index f230af19c..db4e0da5d 100644 --- a/src/renderer/commands/domains/workspace.ts +++ b/src/renderer/commands/domains/workspace.ts @@ -1,6 +1,7 @@ import { COMMANDS } from "../../../shared/keybindings/commands"; import { registerCommand } from "../../commands/registry"; import { goToNextWaiting } from "../../services/agent-sessions/use-inbox"; +import { activateWorkspace } from "../../state/operations/workspace-selection"; import { useActiveStore } from "../../state/stores/active"; import { useAddWorkspaceUIStore } from "../../state/stores/add-workspace-ui"; import { useTaskUIStore } from "../../state/stores/task-ui"; @@ -16,22 +17,13 @@ import { * existing `compareSortKey` order). Wraps at both ends so ⌘⌃↑ from * the first workspace lands on the last, and vice-versa. * - * No-op when there is at most one workspace, or when the active id is - * absent from the list (e.g. mid-removal); we fall back to the first - * row in that case so the shortcut still feels responsive. A task counts - * as its parent's row, so the step starts there. + * If the selection is missing from the list, start at the natural end + * for the direction. A task counts as its parent's row. */ export function cycleActiveWorkspace(delta: 1 | -1): void { const all = useWorkspacesStore.getState().workspaces; const workspaces = visibleWorkspaces(all); if (workspaces.length === 0) return; - if (workspaces.length === 1) { - // Still set it explicitly so a fresh boot with no active id picks - // up the only available workspace on the very first keystroke. - useActiveStore.getState().setActiveWorkspaceId(workspaces[0].id); - return; - } - const activeId = useActiveStore.getState().activeWorkspaceId; const rowId = activeId !== null ? rootWorkspaceId(all, activeId) : null; const currentIndex = rowId !== null ? workspaces.findIndex((w) => w.id === rowId) : -1; @@ -44,7 +36,8 @@ export function cycleActiveWorkspace(delta: 1 | -1): void { nextIndex = (currentIndex + delta + workspaces.length) % workspaces.length; } - useActiveStore.getState().setActiveWorkspaceId(workspaces[nextIndex].id); + const next = workspaces[nextIndex].id; + if (next !== activeId) activateWorkspace(next, "preserve"); } export function registerWorkspaceCommands(): Array<() => void> { diff --git a/src/renderer/components/agent-view/agent-pane.tsx b/src/renderer/components/agent-view/agent-pane.tsx index 87f591dc1..4bf281668 100644 --- a/src/renderer/components/agent-view/agent-pane.tsx +++ b/src/renderer/components/agent-view/agent-pane.tsx @@ -38,8 +38,7 @@ import { } from "@/state/stores/workspaces"; import { cn } from "@/utils/cn"; import { COMMANDS } from "../../../shared/keybindings/commands"; -import { createLogger } from "../../../shared/log/renderer"; -import { ipcCallResult } from "../../ipc/client"; +import { retryWorkspaceConnection } from "../../state/operations/workspace-selection"; import { StateGlyph, stateLabel } from "../agent-list/session-status"; import { AgentMark } from "../agent-list/status-view"; import { Button } from "../ui/button"; @@ -63,8 +62,6 @@ import { EndedBar } from "./ended-bar"; import { RemoteSessionPane } from "./remote-pane"; import { DeviceChip, RemoteTabLabel } from "./remote-sessions"; -const log = createLogger("agent-view"); - function update(change: (layout: AgentLayout) => AgentLayout): void { useAgentViewStore.getState().update(change); } @@ -642,11 +639,7 @@ function OfflinePane({ workspaceId }: { workspaceId: string }) { workspace.location.kind === "ssh" ? `${workspace.location.user ? `${workspace.location.user}@` : ""}${workspace.location.host}` : workspace.location.distro; - const connect = () => { - void ipcCallResult("workspace", "activate", { id: workspaceId }).then((result) => { - if (!result.ok) log.warn(`activate failed: ${result.message}`); - }); - }; + const connect = () => retryWorkspaceConnection(workspaceId); return (
Promise<{ ok: boolean; message?: string }>; - onError: (message: string) => void; - }, -): Promise { - const result = await deps.callActivate(workspaceId); - if (!result.ok) { - deps.onError(i18next.t("files:panel.reconnectError")); - } -} - // Memo: kept while hidden, it would render again with each of the app's. export const FilesPanel = memo(function FilesPanel() { const { t } = useTranslation("files"); @@ -98,19 +72,23 @@ export const FilesPanel = memo(function FilesPanel() { activeWorkspace !== null && activeWorkspace.location.kind !== "local" && !workspaceOnline; // Whether a reconnect is in progress — used to disable the Reconnect button and change its label. - const [isReconnecting, setIsReconnecting] = useState(false); + const reconnect = useIpcAction(); + const isReconnecting = reconnect.state.status === "loading"; + const connectionError = reconnect.state.status === "error" ? reconnect.state.error : null; + useEffect(() => { + if (connectionError) surfaceError(connectionError, { surface: "toast" }); + }, [connectionError]); // Bumped by each click on the Search button so the panel focuses its input, // whether the click mounts it or it is already showing. const [searchFocusRequest, setSearchFocusRequest] = useState(0); const handleReconnect = (): void => { if (!activeWorkspace || isReconnecting) return; - setIsReconnecting(true); - void reconnectWorkspace(activeWorkspace.id, { - callActivate: (id) => ipcCallResult("workspace", "activate", { id }), - onError: (message) => showToast({ kind: "error", message }), - }).finally(() => { - setIsReconnecting(false); + void reconnect.run(async (signal) => { + const result = await connectWorkspace(activeWorkspace.id, signal); + if (result.ok) return; + const error = AppErrorSchema.safeParse(result); + throw error.success ? error.data : appErrorFailed(result.message); }); }; diff --git a/src/renderer/components/workspace/panel.tsx b/src/renderer/components/workspace/panel.tsx index 11b46d5db..2783530fe 100644 --- a/src/renderer/components/workspace/panel.tsx +++ b/src/renderer/components/workspace/panel.tsx @@ -2,9 +2,8 @@ import { memo, useCallback, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { openTerminal } from "@/services/terminal"; import { cn } from "@/utils/cn"; -import { createLogger } from "../../../shared/log/renderer"; import type { WorkspaceMeta } from "../../../shared/types/workspace"; -import { ipcCallResult } from "../../ipc/client"; +import { retryWorkspaceConnection } from "../../state/operations/workspace-selection"; import { useLayoutStore } from "../../state/stores/layout"; import { type Tab, useTabsStore } from "../../state/stores/tabs"; import { useTerminalDeathStore } from "../../state/stores/terminal-deaths"; @@ -27,8 +26,6 @@ import { WorkspaceTerminalStatusBanner, } from "./terminal-status-banner"; -const log = createLogger("workspace-panel"); - // --------------------------------------------------------------------------- // Props // --------------------------------------------------------------------------- @@ -107,10 +104,9 @@ export const WorkspacePanel = memo(function WorkspacePanel({ [workspace.id], ); - function handleConnect() { - void ipcCallResult("workspace", "activate", { id: workspace.id }).then((result) => { - if (!result.ok) log.warn(`activate failed: ${result.message}`); - }); + /** Retry the connection for this workspace's existing panel. */ + function handleConnect(): void { + retryWorkspaceConnection(workspace.id); } if (showOfflinePlaceholder) { diff --git a/src/renderer/state/notification-click.ts b/src/renderer/state/notification-click.ts index 4b8366d80..c49c9945f 100644 --- a/src/renderer/state/notification-click.ts +++ b/src/renderer/state/notification-click.ts @@ -1,9 +1,9 @@ // Renderer-side handler for OS notification clicks emitted by the main process. -// Activates the target workspace and reveals the specific tab in the layout. +// Reveals the tab in the current view or its workspace. import { ipcListen } from "../ipc/client"; import { showInAgentView } from "../services/agent-view/show"; -import { useActiveStore } from "./stores/active"; +import { focusWorkspace } from "./operations/workspace-selection"; import { useAgentViewStore } from "./stores/agent-view"; import { allLeaves } from "./stores/layout/helpers"; import { useLayoutStore } from "./stores/layout/store"; @@ -24,11 +24,9 @@ export function startNotificationClickListener(): () => void { showInAgentView(workspaceId, tabId); return; } - agentView.setMode("workspace"); } - // Activate the workspace in the renderer store. - useActiveStore.getState().setActiveWorkspaceId(workspaceId); + focusWorkspace(workspaceId, "workspace"); // Reveal the tab in whichever leaf group contains it. const layout = useLayoutStore.getState().byWorkspace[workspaceId]; diff --git a/src/renderer/state/operations/git-error-toasts.ts b/src/renderer/state/operations/git-error-toasts.ts index fc65960c3..d15156450 100644 --- a/src/renderer/state/operations/git-error-toasts.ts +++ b/src/renderer/state/operations/git-error-toasts.ts @@ -15,6 +15,7 @@ import { useGitStore } from "../stores/git"; import { gitErrorPlacement, summarizeGitError } from "../stores/git/error-placement"; import type { GitStoreError } from "../stores/git/types"; import { FILES_PANEL_MODE_DEFAULT, useUIStore } from "../stores/ui"; +import { focusWorkspace } from "./workspace-selection"; type Unsubscribe = () => void; @@ -80,7 +81,7 @@ function isSourceControlVisible(workspaceId: string): boolean { } function revealSourceControl(workspaceId: string): void { - useActiveStore.getState().setActiveWorkspaceId(workspaceId); + focusWorkspace(workspaceId, "preserve"); const ui = useUIStore.getState(); if (ui.filesPanelHidden) ui.toggleFilesPanel(); ui.setFilesPanelMode(workspaceId, "git"); diff --git a/src/renderer/state/operations/workspace-selection.ts b/src/renderer/state/operations/workspace-selection.ts index 596f25f41..04a14ea59 100644 --- a/src/renderer/state/operations/workspace-selection.ts +++ b/src/renderer/state/operations/workspace-selection.ts @@ -3,14 +3,40 @@ import { ipcCallResult } from "../../ipc/client"; import { useActiveStore } from "../stores/active"; import { useAgentViewStore } from "../stores/agent-view"; -const log = createLogger("tasks"); +const log = createLogger("workspace-selection"); -/** Activates a workspace here and tells main, which connects an SSH one. */ -export function activateWorkspace(id: string): void { - // Asked to show a workspace, the window shows the workspaces. - useAgentViewStore.getState().setMode("workspace"); +type WorkspaceView = "workspace" | "preserve"; + +/** Show a workspace in this window for a reveal or a restored selection. */ +export function focusWorkspace(id: string | null, view: WorkspaceView): void { + if (view === "workspace") useAgentViewStore.getState().setMode("workspace"); useActiveStore.getState().setActiveWorkspaceId(id); - void ipcCallResult("workspace", "activate", { id }).then((result) => { - if (!result.ok) log.warn(`workspace activate failed: ${result.message}`); - }); +} + +/** Apply the user's workspace selection and send it to main for persistence and connection. */ +export function activateWorkspace(id: string, view: WorkspaceView = "workspace"): void { + focusWorkspace(id, view); + void ipcCallResult("workspace", "activate", { id }) + .then((result) => { + if (!result.ok && result.kind !== "cancelled") { + log.warn(`Workspace activation failed: ${result.message}`); + } + }) + .catch((error: unknown) => log.warn(`Workspace activation failed: ${String(error)}`)); +} + +/** Connect the workspace being shown, independently of the selection. */ +export function connectWorkspace(id: string, signal?: AbortSignal) { + return ipcCallResult("workspace", "connect", { id }, { signal }); +} + +/** Retry from a panel that already displays connection status. */ +export function retryWorkspaceConnection(id: string): void { + void connectWorkspace(id) + .then((result) => { + if (!result.ok && result.kind !== "cancelled") { + log.warn(`Workspace connection failed: ${result.message}`); + } + }) + .catch((error: unknown) => log.warn(`Workspace connection failed: ${String(error)}`)); } diff --git a/src/shared/ipc/contract.ts b/src/shared/ipc/contract.ts index 76ae5faed..4f5cdfd5e 100644 --- a/src/shared/ipc/contract.ts +++ b/src/shared/ipc/contract.ts @@ -614,8 +614,11 @@ export const ipcContract = { update: call(WorkspaceUpdateArgsSchema, WorkspaceMetaSchema), reorder: call(WorkspaceReorderArgsSchema, WorkspaceMetaSchema), remove: call(WorkspaceIdSchema, z.void()), + /** Select and connect the workspace the user chose. */ activate: call(WorkspaceIdSchema, z.void()), - /** The active workspace: the one restored at launch or last activated; null with none. */ + /** Connect a workspace already shown in a view. */ + connect: call(WorkspaceIdSchema, z.void()), + /** The restored or most recently selected workspace; null with none. */ active: call(z.void(), WorkspaceIdPrimitive.nullable()), testSsh: call(WorkspaceTestSshArgsSchema, WorkspaceTestSshResultSchema), }, diff --git a/tests/unit/main/pty/ipc-shell-choice.test.ts b/tests/unit/main/pty/ipc-shell-choice.test.ts index 082eb32dc..6a2fc4b19 100644 --- a/tests/unit/main/pty/ipc-shell-choice.test.ts +++ b/tests/unit/main/pty/ipc-shell-choice.test.ts @@ -108,7 +108,7 @@ function setup(opts: { }); const wm: PtyChannelOptions["workspaceManager"] = { getName: () => "ws", - activate: async () => {}, + connect: async () => {}, getAgentChannel: async () => agent, getWrapperBinDir: () => opts.wrapper?.binDir ?? null, getWrapperAgentBin: () => null, diff --git a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts index 99a593e77..d1bca67ea 100644 --- a/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts +++ b/tests/unit/main/workspace/manager-reattach-lifecycle.test.ts @@ -138,22 +138,104 @@ function makeManager(overrides?: { overrides?.ptyReleaseHeld ?? ((_id) => {}), ); - return { manager, globalDb, broadcasts }; + return { manager, globalDb, broadcasts, stateService }; } -function makeSshMeta(manager: ReturnType["manager"]) { +function makeSshMeta( + manager: ReturnType["manager"], + remotePath = "/home/user/project", +) { return manager.create({ location: { kind: "ssh" as const, host: "test.example.com", user: "user", - remotePath: "/home/user/project", + remotePath, authMode: "interactive" as const, }, name: "test-ssh", }); } +test("a slow SSH connection cannot replace the most recently selected workspace", async () => { + const slow = new StubChannel(); + const fast = new StubChannel(); + fast.resolveChannel(); + const slowSpawned = Promise.withResolvers(); + const { manager, stateService } = makeManager({ + sshBootstrap: async ({ remotePath }) => ({ + remoteCommand: remotePath, + remoteHome: "/home/user", + remoteBinDir: "/home/user/.nexus-code/bin", + platform: { os: "linux", arch: "amd64" }, + uploaded: false, + }), + sshChannelFactory: ({ remoteCommand }) => { + if (remoteCommand.endsWith("/slow")) { + slowSpawned.resolve(); + return slow; + } + return fast; + }, + }); + const a = makeSshMeta(manager, "/home/user/slow"); + const b = makeSshMeta(manager, "/home/user/fast"); + const lastOpenedAt = "2000-01-01T00:00:00.000Z"; + manager.update(a.id, { lastOpenedAt }); + let earlier: Promise | undefined; + try { + await manager.getAgentChannel(b.id); + earlier = manager.activate(a.id); + await slowSpawned.promise; + expect(stateService.getState().lastActiveWorkspaceId).toBe(a.id); + await manager.activate(b.id); + slow.resolveChannel(); + await earlier; + + expect(manager.getActiveId()).toBe(b.id); + expect(stateService.getState().lastActiveWorkspaceId).toBe(b.id); + expect(manager.list().find((workspace) => workspace.id === a.id)?.lastOpenedAt).toBe( + lastOpenedAt, + ); + } finally { + slow.resolveChannel(); + await earlier; + manager.close(); + } +}); + +test("connecting a background SSH workspace leaves the recorded selection and its recency alone", async () => { + const { manager, stateService } = makeManager({ + sshBootstrap: async () => ({ + remoteCommand: "exec agent", + remoteHome: "/home/user", + remoteBinDir: "/home/user/.nexus-code/bin", + platform: { os: "linux", arch: "amd64" }, + uploaded: false, + }), + sshChannelFactory: () => { + const channel = new StubChannel(); + channel.resolveChannel(); + return channel; + }, + }); + const selected = makeSshMeta(manager, "/home/user/selected"); + const background = makeSshMeta(manager, "/home/user/background"); + const lastOpenedAt = "2000-01-01T00:00:00.000Z"; + manager.update(background.id, { lastOpenedAt }); + try { + await manager.activate(selected.id); + await manager.connect(background.id); + + expect(await manager.peekAgentChannel(background.id)).not.toBeNull(); + expect(manager.getActiveId()).toBe(selected.id); + expect(stateService.getState().lastActiveWorkspaceId).toBe(selected.id); + expect(manager.list().find(({ id }) => id === background.id)?.lastOpenedAt).toBe(lastOpenedAt); + } finally { + manager.close(); + } +}); + // --------------------------------------------------------------------------- // Acceptance 3: degraded → "unstable" broadcast // --------------------------------------------------------------------------- diff --git a/tests/unit/renderer/state/operations/workspace-selection.test.ts b/tests/unit/renderer/state/operations/workspace-selection.test.ts new file mode 100644 index 000000000..34d001eb5 --- /dev/null +++ b/tests/unit/renderer/state/operations/workspace-selection.test.ts @@ -0,0 +1,63 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { cycleActiveWorkspace } from "../../../../../src/renderer/commands/domains/workspace"; +import { useActiveStore } from "../../../../../src/renderer/state/stores/active"; +import { useWorkspacesStore } from "../../../../../src/renderer/state/stores/workspaces"; +import type { WorkspaceMeta } from "../../../../../src/shared/types/workspace"; + +const originalWindow = globalThis.window; +const local: WorkspaceMeta = { + id: crypto.randomUUID(), + name: "Local", + location: { kind: "local", rootPath: "/repo" }, + rootPath: "/repo", + colorTone: "default", + pinned: false, + tabs: [], + sortOrder: 1, + pinnedSortOrder: 0, +}; +const ssh: WorkspaceMeta = { + ...local, + id: crypto.randomUUID(), + name: "SSH", + location: { kind: "ssh", host: "example.invalid", remotePath: "/remote" }, + rootPath: "/remote", + sortOrder: 2, +}; + +/** Drives workspace IPC without constructing a window or opening a connection. */ +function setWorkspaceIpc(call: (method: string, body: unknown) => Promise): void { + Object.assign(globalThis, { + window: { + ipc: { + call: (channel: string, method: string, body: unknown) => + channel === "workspace" ? call(method, body) : Promise.resolve(undefined), + }, + }, + }); +} + +beforeEach(() => { + useWorkspacesStore.getState().setAll([]); + useActiveStore.getState().setActiveWorkspaceId(null); +}); + +afterEach(() => { + useWorkspacesStore.getState().setAll([]); + useActiveStore.getState().setActiveWorkspaceId(null); + Object.assign(globalThis, { window: originalWindow }); +}); + +test("the workspace cycling shortcut selects and connects a disconnected SSH workspace", () => { + let requested: unknown; + setWorkspaceIpc(async (method, body) => { + if (method === "activate") requested = body; + }); + useWorkspacesStore.getState().setAll([local, ssh]); + useActiveStore.getState().setActiveWorkspaceId(local.id); + + cycleActiveWorkspace(1); + + expect(useActiveStore.getState().activeWorkspaceId).toBe(ssh.id); + expect(requested).toEqual({ id: ssh.id }); +}); From 94e9703ee9c40a7f7ad0902f0b9a0751192cfc68 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 19:58:55 +0900 Subject: [PATCH 056/208] fix(workbench): wait for workspace restoration before releasing CLI requests Co-Authored-By: Claude Opus 5.5 --- src/renderer/app.tsx | 18 +--- src/renderer/bootstrap.ts | 55 +++++------ src/renderer/services/cli/ui-requests.ts | 20 +--- .../renderer/services/cli/ui-requests.test.ts | 22 ++--- .../operations/workspace-selection.test.ts | 92 +++++++++++++++++++ 5 files changed, 138 insertions(+), 69 deletions(-) diff --git a/src/renderer/app.tsx b/src/renderer/app.tsx index 356d686d4..ff6e1287b 100644 --- a/src/renderer/app.tsx +++ b/src/renderer/app.tsx @@ -2,7 +2,7 @@ import { useMonaco } from "@monaco-editor/react"; import { useCallback, useEffect, useRef } from "react"; import { createLogger } from "../shared/log/renderer"; import type { WorkspaceMeta } from "../shared/types/workspace"; -import { bootstrapAppState, bootstrapClaudeStatus, bootstrapWorkspaces } from "./bootstrap"; +import { bootstrapClaudeStatus, bootstrapWorkbench } from "./bootstrap"; import { useCommandBridge } from "./commands/use-command-bridge"; import { AgentSidebar } from "./components/agent-view/agent-sidebar"; import { AgentView } from "./components/agent-view/agent-view"; @@ -61,9 +61,7 @@ export function App() { // Picked one by one: the whole store would render the app, every // workspace's tabs below it, for each connection status and progress. const workspaces = useWorkspacesStore((s) => s.workspaces); - const setAll = useWorkspacesStore((s) => s.setAll); const activeWorkspaceId = useActiveStore((s) => s.activeWorkspaceId); - const setActiveWorkspaceId = useActiveStore((s) => s.setActiveWorkspaceId); const settingsOpen = useSettingsUIStore((s) => s.settingsOpen); const settingsInitialActiveId = useSettingsUIStore((s) => s.initialActiveId); const closeSettings = useSettingsUIStore((s) => s.closeSettings); @@ -93,22 +91,12 @@ export function App() { initializeEditorServices(monaco); }, [monaco]); - // Boot: hydrate UI state (sidebar width, files panel) and layout/tabs from persisted app state. - useEffect(() => { - bootstrapAppState(); - }, []); - - // Boot: Claude 세션 상태 snapshot 로드 및 status broadcast 구독 설정. + // Restore the tabs and workspace selection before opening the CLI gate. useEffect(() => { + void bootstrapWorkbench(); void bootstrapClaudeStatus(); }, []); - // Boot: load workspaces from main, activate first. - // biome-ignore lint/correctness/useExhaustiveDependencies: boot-once effect; store setters are stable - useEffect(() => { - bootstrapWorkspaces(setAll, setActiveWorkspaceId); - }, []); - // Mark the active workspace as mounted (one-way; lazy-mount + persist). useEffect(() => { if (!activeWorkspaceId) return; diff --git a/src/renderer/bootstrap.ts b/src/renderer/bootstrap.ts index bfe9e4ef4..76e2c21c1 100644 --- a/src/renderer/bootstrap.ts +++ b/src/renderer/bootstrap.ts @@ -7,12 +7,11 @@ import { createLogger } from "../shared/log/renderer"; import { lspSettingsFromState } from "../shared/lsp/settings"; -import type { WorkspaceMeta } from "../shared/types/workspace"; import { ipcCallResult, ipcListen, mustSucceed } from "./ipc/client"; import { startTabActivityPolling } from "./services/agent-sessions/activity-poll"; import { startSessionEvents } from "./services/agent-sessions/session-events"; import { startAgentViewPruning, tabExists } from "./services/agent-view/show"; -import { markCliUiReady, startCliUiListener } from "./services/cli/ui-requests"; +import { startCliUiListener } from "./services/cli/ui-requests"; import { startClaudeActiveContextSync } from "./state/claude-active-context-sync"; import { startNoteRemovalListener } from "./state/note-removal"; import { startNotificationClickListener } from "./state/notification-click"; @@ -26,7 +25,9 @@ import { initLspStatusSync } from "./state/operations/lsp-status"; import { initPortsSync } from "./state/operations/ports"; import { hydrateReleaseNotesSeen } from "./state/operations/release-notes"; import { initUpdatesSubscriptions } from "./state/operations/updates"; +import { focusWorkspace } from "./state/operations/workspace-selection"; import { hydrateLayoutSnapshots, registerStatePersistence } from "./state/persistence"; +import { useActiveStore } from "./state/stores/active"; import { useAgentCliStore } from "./state/stores/agent-cli"; import { useAgentListViewStore } from "./state/stores/agent-list-view"; import { loadProfilesHome, useAgentProfilesStore } from "./state/stores/agent-profiles"; @@ -49,7 +50,7 @@ import { useUIStore } from "./state/stores/ui"; import { useUpdatesStore } from "./state/stores/updates"; import { useVoiceStore } from "./state/stores/voice"; import { useWindowOpacityStore } from "./state/stores/window-opacity"; -import { restoredWorkspace } from "./state/stores/workspaces"; +import { restoredWorkspace, useWorkspacesStore } from "./state/stores/workspaces"; import { startTerminalExitListener } from "./state/terminal-exit"; import { initializeWorkspaceLifecycle } from "./state/workspace-cleanup"; @@ -92,7 +93,7 @@ function installGlobalFileDropGuard(): void { }); } -export async function bootstrapAppState(): Promise { +async function bootstrapAppState(): Promise { // Install the central workspace:removed listener before any async I/O — // registered cleanup functions sit in memory regardless, but the listener // itself must be live before the first user-initiated workspace removal. @@ -102,12 +103,9 @@ export async function bootstrapAppState(): Promise { // installGlobalFileDropGuard for the file:// navigation hazard it prevents. installGlobalFileDropGuard(); - // Wire the OS notification click → workspace activate + tab reveal listener. + // Reveal the tab a clicked OS notification points to. startNotificationClickListener(); - // Answer the nexus CLI's requests; they wait until the tabs are restored. - startCliUiListener(); - // Mark terminal tabs dead on PTY exit even while their view is unmounted. startTerminalExitListener(); @@ -280,7 +278,6 @@ export async function bootstrapAppState(): Promise { startAgentViewPruning(); registerStatePersistence(); - markCliUiReady(); // Dev-only console helper for testing window transparency before a settings // UI exists. `__setWindowOpacity(0.5)` dual-writes localStorage + appState @@ -298,26 +295,32 @@ export async function bootstrapAppState(): Promise { } /** - * Load the workspace list from main, push it into the store, and - * restore the active workspace selection. - * - * Does NOT call workspace:activate at startup. Main's init() is the source - * of truth for the restored active workspace and its conditional auto-connect - * (key-only SSH and local connect automatically; interactive SSH restores in - * the disconnected state), so the selection is the workspace main restored. - * Calling activate here would both trigger a connection and wrongly bump the - * recency list on every app launch. + * Load the workspace list and restore the selection main recorded. Main + * owns startup connection policy, including interactive SSH workspaces + * that wait for a user to connect. */ -export async function bootstrapWorkspaces( - setAll: (list: WorkspaceMeta[]) => void, - setActiveWorkspaceId: (id: string | null) => void, -): Promise { - // Bootstrap is an initialization path — no recovery possible if workspace list is unavailable. +export async function bootstrapWorkspaces(): Promise { const list = mustSucceed(await ipcCallResult("workspace", "list", undefined)); - setAll(list); + useWorkspacesStore.getState().setAll(list); const active = await ipcCallResult("workspace", "active", undefined); - const selected = restoredWorkspace(list, active.ok ? active.value : null); - if (selected) setActiveWorkspaceId(selected.id); + + // The sidebar can already be used while the active-ID reply is pending. + if (useActiveStore.getState().activeWorkspaceId !== null) return; + const currentList = useWorkspacesStore.getState().workspaces; + const selected = restoredWorkspace(currentList, active.ok ? active.value : null); + if (selected) focusWorkspace(selected.id, "preserve"); +} + +/** + * Restore tabs before the workspace can mount and seed a terminal. CLI + * requests can arrive throughout startup and wait for both restorations. + */ +export function bootstrapWorkbench( + hydrateAppState: () => Promise = bootstrapAppState, +): Promise { + const ready = hydrateAppState().then(bootstrapWorkspaces); + startCliUiListener(ready); + return ready; } /** diff --git a/src/renderer/services/cli/ui-requests.ts b/src/renderer/services/cli/ui-requests.ts index 000496912..d5efedf9b 100644 --- a/src/renderer/services/cli/ui-requests.ts +++ b/src/renderer/services/cli/ui-requests.ts @@ -105,16 +105,6 @@ const handlers: { [K in CliUiOp]: CliUiHandler } = { ...viewHandlers, }; -let markReady: () => void = () => {}; -const ready = new Promise((resolve) => { - markReady = resolve; -}); - -/** Lets requests through once the tabs and layouts have been restored. */ -export function markCliUiReady(): void { - markReady(); -} - /** Removes the cli:uiRequest listener installed last, if it is still there. */ let stopListening: (() => void) | null = null; @@ -123,24 +113,24 @@ import.meta.hot?.dispose(() => stopListening?.()); /** * Installs the cli:uiRequest listener, in place of one installed before. - * Requests wait until markCliUiReady, since before it the stores are empty. + * Requests wait until startup restores layouts and the workspace list and selection. * Returns the unlisten function. * * A request leaves the keyboard where it was: one that splits the group of * the terminal it came from would otherwise leave that terminal without * focus (see ../keep-focus). */ -export function startCliUiListener(): () => void { +export function startCliUiListener(ready: Promise): () => void { // One listener, however often the app boots: a second would carry out // each request again, typing or sending twice. The dev build's hot reload // boots the app again with each edit. stopListening?.(); const stop = ipcListen("cli", "uiRequest", ({ requestId, op, args }) => { void (async () => { - await ready; - const handler = handlers[op as CliUiOp] as CliUiHandler | undefined; - const held = focusHolder(); try { + await ready; + const handler = handlers[op as CliUiOp] as CliUiHandler | undefined; + const held = focusHolder(); if (!handler) throw new UiRequestError(`unknown request ${op}`); const value = await handler(args as never).finally(() => restoreFocus(held)); await ipcCallResult("cli", "uiRespond", { requestId, ok: true, value }); diff --git a/tests/unit/renderer/services/cli/ui-requests.test.ts b/tests/unit/renderer/services/cli/ui-requests.test.ts index c8331dab4..d1e3f6ab7 100644 --- a/tests/unit/renderer/services/cli/ui-requests.test.ts +++ b/tests/unit/renderer/services/cli/ui-requests.test.ts @@ -32,7 +32,7 @@ afterAll(() => { globals.document = originalDocument; }); -const { listTabs, markCliUiReady, startCliUiListener } = await import( +const { listTabs, startCliUiListener } = await import( "../../../../../src/renderer/services/cli/ui-requests" ); const { useTabsStore } = await import("../../../../../src/renderer/state/stores/tabs"); @@ -61,12 +61,11 @@ async function answerTo(requestId: string, op: string, args: unknown): Promise { - startCliUiListener(); - startCliUiListener(); - const stop = startCliUiListener(); + startCliUiListener(Promise.resolve()); + startCliUiListener(Promise.resolve()); + const stop = startCliUiListener(Promise.resolve()); expect(listeners.size).toBe(1); - markCliUiReady(); for (const listener of listeners) listener({ requestId: "r1", op: "no.such.op", args: {} }); await new Promise((resolve) => setTimeout(resolve, 0)); const answers = calls.filter(([channel, method]) => channel === "cli" && method === "uiRespond"); @@ -76,8 +75,8 @@ test("a request is carried out once, however often the app boots", async () => { stop(); expect(listeners.size).toBe(0); // A stop from before leaves the listener installed after it. - const older = startCliUiListener(); - startCliUiListener(); + const older = startCliUiListener(Promise.resolve()); + startCliUiListener(Promise.resolve()); older(); expect(listeners.size).toBe(1); }); @@ -120,8 +119,7 @@ test("a terminal not started yet, its workspace not opened, says so in the tabs' test("a terminal not started yet is started behind the view, and read once it has", async () => { const ws = "ws-later"; const tab = useTabsStore.getState().createTab(ws, { type: "terminal", props: { cwd: "/" } }); - startCliUiListener(); - markCliUiReady(); + startCliUiListener(Promise.resolve()); let unregister = () => {}; try { const answer = answerTo("r-later", "terminal.read", { @@ -150,8 +148,7 @@ test("a terminal not started yet is started behind the view, and read once it ha test("a terminal its view has registered is typed into only once its shell is ready", async () => { const ws = "ws-opening"; const tab = useTabsStore.getState().createTab(ws, { type: "terminal", props: { cwd: "/" } }); - startCliUiListener(); - markCliUiReady(); + startCliUiListener(Promise.resolve()); const typed: string[] = []; let open = (_ready: boolean) => {}; // Its fonts still loading, or its shell not at its prompt: input would be lost. @@ -189,8 +186,7 @@ test("a tab that is not a terminal is not waited for", async () => { const tab = useTabsStore .getState() .createTab(ws, { type: "editor", props: { workspaceId: ws, filePath: "/a.ts" } }); - startCliUiListener(); - markCliUiReady(); + startCliUiListener(Promise.resolve()); try { expect( await answerTo("r-editor", "terminal.read", { workspaceId: ws, tabId: tab.id, lines: 5 }), diff --git a/tests/unit/renderer/state/operations/workspace-selection.test.ts b/tests/unit/renderer/state/operations/workspace-selection.test.ts index 34d001eb5..a6f2bdb72 100644 --- a/tests/unit/renderer/state/operations/workspace-selection.test.ts +++ b/tests/unit/renderer/state/operations/workspace-selection.test.ts @@ -1,10 +1,15 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; +import { bootstrapWorkbench, bootstrapWorkspaces } from "../../../../../src/renderer/bootstrap"; import { cycleActiveWorkspace } from "../../../../../src/renderer/commands/domains/workspace"; import { useActiveStore } from "../../../../../src/renderer/state/stores/active"; +import { useAgentViewStore } from "../../../../../src/renderer/state/stores/agent-view"; import { useWorkspacesStore } from "../../../../../src/renderer/state/stores/workspaces"; import type { WorkspaceMeta } from "../../../../../src/shared/types/workspace"; const originalWindow = globalThis.window; +const globals = globalThis as { document?: unknown }; +const originalDocument = globals.document; +let previousView = useAgentViewStore.getState().mode; const local: WorkspaceMeta = { id: crypto.randomUUID(), name: "Local", @@ -38,6 +43,8 @@ function setWorkspaceIpc(call: (method: string, body: unknown) => Promise { + previousView = useAgentViewStore.getState().mode; + useAgentViewStore.setState({ mode: "workspace" }); useWorkspacesStore.getState().setAll([]); useActiveStore.getState().setActiveWorkspaceId(null); }); @@ -46,6 +53,8 @@ afterEach(() => { useWorkspacesStore.getState().setAll([]); useActiveStore.getState().setActiveWorkspaceId(null); Object.assign(globalThis, { window: originalWindow }); + globals.document = originalDocument; + useAgentViewStore.setState({ mode: previousView }); }); test("the workspace cycling shortcut selects and connects a disconnected SSH workspace", () => { @@ -61,3 +70,86 @@ test("the workspace cycling shortcut selects and connects a disconnected SSH wor expect(useActiveStore.getState().activeWorkspaceId).toBe(ssh.id); expect(requested).toEqual({ id: ssh.id }); }); + +test("startup restores the remembered workspace away from the first row without connecting it", async () => { + const calls: string[] = []; + setWorkspaceIpc(async (method) => { + calls.push(method); + return method === "list" ? [local, ssh] : ssh.id; + }); + + await bootstrapWorkspaces(); + + expect(useActiveStore.getState().activeWorkspaceId).toBe(ssh.id); + expect(calls).toEqual(["list", "active"]); +}); + +test("a workspace selected while startup waits for the last active ID stays selected", async () => { + const active = Promise.withResolvers(); + const requested = Promise.withResolvers(); + setWorkspaceIpc(async (method) => { + if (method === "list") return [local, ssh]; + if (method === "active") { + requested.resolve(); + return active.promise; + } + }); + const restoring = bootstrapWorkspaces(); + await requested.promise; + cycleActiveWorkspace(-1); + expect(useActiveStore.getState().activeWorkspaceId).toBe(ssh.id); + active.resolve(local.id); + await restoring; + + expect(useActiveStore.getState().activeWorkspaceId).toBe(ssh.id); +}); + +test("a CLI workspace request waits for app state, the workspace list, and the restored selection", async () => { + globals.document = { activeElement: null, body: null }; + const appState = Promise.withResolvers(); + const workspaceList = Promise.withResolvers(); + const active = Promise.withResolvers(); + const listRequested = Promise.withResolvers(); + const activeRequested = Promise.withResolvers(); + const responded = Promise.withResolvers(); + const selections: unknown[] = []; + let onRequest: ((args: unknown) => void) | undefined; + Object.assign(globalThis, { + window: { + ipc: { + call: async (channel: string, method: string, body: unknown) => { + if (channel === "cli" && method === "uiRespond") responded.resolve(body); + if (channel !== "workspace") return; + if (method === "list") { + listRequested.resolve(); + return workspaceList.promise; + } + if (method === "active") { + activeRequested.resolve(); + return active.promise; + } + if (method === "activate") selections.push(body); + }, + listen: (channel: string, event: string, callback: (args: unknown) => void) => { + if (channel === "cli" && event === "uiRequest") onRequest = callback; + return () => {}; + }, + }, + }, + }); + + const starting = bootstrapWorkbench(() => appState.promise); + onRequest?.({ requestId: "boot-show", op: "workspace.show", args: { workspaceId: ssh.id } }); + appState.resolve(); + await listRequested.promise; + expect(selections).toEqual([]); + workspaceList.resolve([local, ssh]); + await activeRequested.promise; + expect(selections).toEqual([]); + active.resolve(local.id); + + await starting; + expect(await responded.promise).toMatchObject({ requestId: "boot-show", ok: true }); + expect(selections).toEqual([{ id: ssh.id }]); + expect(useActiveStore.getState().activeWorkspaceId).toBe(ssh.id); +}); From 812af3b6c3dabec361999be72b8b7753f894ddc7 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:10:41 +0900 Subject: [PATCH 057/208] fix(hooks): stop print children when their recorder dies Co-Authored-By: Claude Opus 5.5 --- cmd/agent/main.go | 3 + internal/hookclient/print.go | 6 + internal/hookclient/print_child_darwin.go | 151 ++++++++++++++++++ .../hookclient/print_child_helper_other.go | 6 + internal/hookclient/print_child_linux.go | 15 ++ internal/hookclient/print_child_other.go | 10 ++ internal/hookclient/print_child_unix_test.go | 76 +++++++++ 7 files changed, 267 insertions(+) create mode 100644 internal/hookclient/print_child_darwin.go create mode 100644 internal/hookclient/print_child_helper_other.go create mode 100644 internal/hookclient/print_child_linux.go create mode 100644 internal/hookclient/print_child_other.go create mode 100644 internal/hookclient/print_child_unix_test.go diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 1dd52f95a..fd7bbb9aa 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -37,6 +37,9 @@ func main() { // What the agent was started with stays with it: on Linux it brings // along Chromium's descriptors, which would reach every terminal. inheritfd.CloseOnExec() + if code, handled := hookclient.PrintChildHelper(os.Args[1:]); handled { + os.Exit(code) + } // hook 서브커맨드 분기 — PTY/FS/Git/LSP 서비스 init 전에 처리해 빠른 시작을 보장한다. // Claude Code는 hook 이벤트 발생 시 `agent hook ` 형태로 호출한다. diff --git a/internal/hookclient/print.go b/internal/hookclient/print.go index 953ef4d3d..a30c99a86 100644 --- a/internal/hookclient/print.go +++ b/internal/hookclient/print.go @@ -225,6 +225,12 @@ func runPrint( } } cmd := nodeshim.Command(claude, args...) + releaseChild, err := preparePrintChild(cmd) + if err != nil { + fmt.Fprintf(stderr, "nexus: %v\n", err) + return 127, 0 + } + defer releaseChild() cmd.Stdin = stdin cmd.Stderr = stderr // A json or stream-json run's output tells of the run, and a text run's diff --git a/internal/hookclient/print_child_darwin.go b/internal/hookclient/print_child_darwin.go new file mode 100644 index 000000000..d84e23af2 --- /dev/null +++ b/internal/hookclient/print_child_darwin.go @@ -0,0 +1,151 @@ +package hookclient + +import ( + "fmt" + "io" + "os" + "os/exec" + "strconv" + "syscall" + + "golang.org/x/sys/unix" +) + +const printChildArg = "--print-child" +const printWatcherArg = "--print-child-watch" + +// preparePrintChild passes a pipe whose writer belongs only to the recorder. +// The bootstrap arms the watcher before replacing itself with Claude, so the +// recorder keeps the real child's PID, wait status and terminal process group. +func preparePrintChild(cmd *exec.Cmd) (func(), error) { + if cmd.Err != nil { + return nil, cmd.Err + } + self, err := os.Executable() + if err != nil { + return nil, err + } + read, write, err := os.Pipe() + if err != nil { + return nil, err + } + cmd.Args = append([]string{self, printChildArg, cmd.Path}, cmd.Args...) + cmd.Path = self + cmd.ExtraFiles = []*os.File{read} + return func() { + _ = read.Close() + _ = write.Close() + }, nil +} + +// PrintChildHelper handles the private child bootstrap and watcher commands. +func PrintChildHelper(args []string) (int, bool) { + if len(args) == 0 { + return 0, false + } + switch args[0] { + case printChildArg: + if len(args) < 3 { + return 2, true + } + if err := execWatchedPrintChild(args[1], args[2:]); err != nil { + fmt.Fprintf(os.Stderr, "nexus: %v\n", err) + return 127, true + } + case printWatcherArg: + if len(args) != 2 { + return 2, true + } + pid, err := strconv.Atoi(args[1]) + if err != nil || pid <= 1 { + return 2, true + } + if err := watchPrintChild(pid); err != nil { + fmt.Fprintf(os.Stderr, "nexus: print child watcher: %v\n", err) + return 1, true + } + default: + return 0, false + } + return 0, true +} + +// execWatchedPrintChild waits for the watcher to arm before exec'ing Claude. +// Only the watcher leaves the terminal session and its foreground signals. +func execWatchedPrintChild(path string, args []string) error { + parent := os.NewFile(3, "print recorder lifetime") + defer parent.Close() + unix.CloseOnExec(int(parent.Fd())) + self, err := os.Executable() + if err != nil { + return err + } + ready, readyWrite, err := os.Pipe() + if err != nil { + return err + } + defer ready.Close() + watcher, err := os.StartProcess(self, []string{self, printWatcherArg, strconv.Itoa(os.Getpid())}, &os.ProcAttr{ + Files: []*os.File{parent, readyWrite, os.Stderr}, + Sys: &syscall.SysProcAttr{Setsid: true}, + }) + _ = readyWrite.Close() + if err != nil { + return err + } + var armed [1]byte + if _, err := io.ReadFull(ready, armed[:]); err != nil { + _, _ = watcher.Wait() + return fmt.Errorf("arm print child watcher: %w", err) + } + _ = watcher.Release() + return syscall.Exec(path, args, os.Environ()) +} + +// watchPrintChild waits for the recorder's pipe to close or for Claude to +// exit. The process filter keeps the watcher from outliving a completed run. +func watchPrintChild(pid int) error { + if os.Getppid() != pid { + return nil + } + queue, err := unix.Kqueue() + if err != nil { + return err + } + defer unix.Close(queue) + filters := []unix.Kevent_t{ + {Ident: uint64(os.Stdin.Fd()), Filter: unix.EVFILT_READ, Flags: unix.EV_ADD}, + {Ident: uint64(pid), Filter: unix.EVFILT_PROC, Flags: unix.EV_ADD, Fflags: unix.NOTE_EXIT}, + } + if _, err := unix.Kevent(queue, filters, nil, nil); err != nil { + return err + } + if _, err := os.Stdout.Write([]byte{1}); err != nil { + return err + } + _ = os.Stdout.Close() + + var events [2]unix.Kevent_t + for { + n, err := unix.Kevent(queue, nil, events[:], nil) + if err == unix.EINTR { + continue + } + if err != nil { + return err + } + for _, event := range events[:n] { + if event.Filter == unix.EVFILT_PROC { + return nil + } + } + for _, event := range events[:n] { + if event.Filter == unix.EVFILT_READ && event.Flags&unix.EV_EOF != 0 { + if os.Getppid() == pid { + _ = unix.Kill(pid, unix.SIGKILL) + } + return nil + } + } + } +} diff --git a/internal/hookclient/print_child_helper_other.go b/internal/hookclient/print_child_helper_other.go new file mode 100644 index 000000000..b15a31bd3 --- /dev/null +++ b/internal/hookclient/print_child_helper_other.go @@ -0,0 +1,6 @@ +//go:build !darwin + +package hookclient + +// PrintChildHelper handles the macOS-only print child and watcher entrypoints. +func PrintChildHelper([]string) (int, bool) { return 0, false } diff --git a/internal/hookclient/print_child_linux.go b/internal/hookclient/print_child_linux.go new file mode 100644 index 000000000..074bca77b --- /dev/null +++ b/internal/hookclient/print_child_linux.go @@ -0,0 +1,15 @@ +package hookclient + +import ( + "os/exec" + "runtime" + "syscall" +) + +// preparePrintChild binds Claude to the thread that starts it. Keep that +// thread alive until the child has been waited for. +func preparePrintChild(cmd *exec.Cmd) (func(), error) { + runtime.LockOSThread() + cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL} + return runtime.UnlockOSThread, nil +} diff --git a/internal/hookclient/print_child_other.go b/internal/hookclient/print_child_other.go new file mode 100644 index 000000000..134e8bcb6 --- /dev/null +++ b/internal/hookclient/print_child_other.go @@ -0,0 +1,10 @@ +//go:build !darwin && !linux + +package hookclient + +import "os/exec" + +// preparePrintChild leaves process setup to the existing platform supervision. +func preparePrintChild(*exec.Cmd) (func(), error) { + return func() {}, nil +} diff --git a/internal/hookclient/print_child_unix_test.go b/internal/hookclient/print_child_unix_test.go new file mode 100644 index 000000000..fd5dae336 --- /dev/null +++ b/internal/hookclient/print_child_unix_test.go @@ -0,0 +1,76 @@ +//go:build darwin || linux + +package hookclient + +import ( + "bufio" + "errors" + "io" + "os" + "os/exec" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +// TestMain dispatches the private bootstrap for child processes of the test binary. +func TestMain(m *testing.M) { + if code, handled := PrintChildHelper(os.Args[1:]); handled { + os.Exit(code) + } + os.Exit(m.Run()) +} + +// TestPrintWrapperKillStopsChild uses an idle process with no hook server or +// pipe writes after startup, so only wrapper-death handling can stop it. +func TestPrintWrapperKillStopsChild(t *testing.T) { + if os.Getenv("NEXUS_TEST_PRINT_PARENT_DEATH") == "1" { + os.Exit(RunPrint([]string{"/bin/sh", "-c", `printf '%s\n' "$$"; exec /bin/sleep 60`})) + } + + read, write, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer read.Close() + cmd := exec.Command(os.Args[0], "-test.run=^TestPrintWrapperKillStopsChild$") + cmd.Env = append(os.Environ(), "NEXUS_TEST_PRINT_PARENT_DEATH=1", envAgentSocket+"=") + cmd.Stdout, cmd.Stderr = write, os.Stderr + err = cmd.Start() + _ = write.Close() + if err != nil { + t.Fatal(err) + } + defer func() { + _ = cmd.Process.Kill() + _ = cmd.Wait() + }() + _ = read.SetReadDeadline(time.Now().Add(5 * time.Second)) + out := bufio.NewReader(read) + line, err := out.ReadString('\n') + if err != nil { + t.Fatal(err) + } + pid, err := strconv.Atoi(strings.TrimSpace(line)) + if err != nil || pid <= 1 { + t.Fatalf("invalid test child pid %q", line) + } + ended := false + defer func() { + if !ended { + _ = syscall.Kill(pid, syscall.SIGKILL) + } + }() + + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + _ = cmd.Wait() + _ = read.SetReadDeadline(time.Now().Add(time.Second)) + if _, err := out.ReadByte(); !errors.Is(err, io.EOF) { + t.Fatalf("child survived killing its wrapper: %v", err) + } + ended = true +} From 8776e2dda4690be901dc343113909bc3ef64f843 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:12:45 +0900 Subject: [PATCH 058/208] fix(git): normalize Apple launcher paths as POSIX Co-Authored-By: Claude Opus 5.5 --- internal/git/info.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/internal/git/info.go b/internal/git/info.go index 01c3a17f8..178c0fd24 100644 --- a/internal/git/info.go +++ b/internal/git/info.go @@ -7,6 +7,7 @@ import ( "errors" "os" "os/exec" + "path" "path/filepath" "runtime" "strings" @@ -218,11 +219,14 @@ func runGitProbe(ctx context.Context, goos string, cmd *exec.Cmd, run func(*exec return cmd.Err } if goos == "darwin" { - path := filepath.Clean(cmd.Path) - if resolved, err := filepath.EvalSymlinks(path); err == nil { - path = resolved + const appleGit = "/usr/bin/git" + candidate := path.Clean(filepath.ToSlash(cmd.Path)) + if candidate != appleGit { + if resolved, err := filepath.EvalSymlinks(cmd.Path); err == nil { + candidate = path.Clean(filepath.ToSlash(resolved)) + } } - if path == "/usr/bin/git" { + if candidate == appleGit { probe := exec.CommandContext(ctx, "/usr/bin/xcode-select", "--print-path") probe.Env = cmd.Environ() if err := run(probe); err != nil { From 2731be9f904af1b8ed892416d9d377a61f4fd14a Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:13:01 +0900 Subject: [PATCH 059/208] fix(browser): scope runtime events to the current view Co-Authored-By: Claude Opus 5.5 --- src/main/features/browser/ipc.ts | 146 ++++++++++++------ .../workspace/content/browser-view.tsx | 28 +++- src/renderer/state/operations/browser.ts | 60 ++++--- src/shared/ipc/contract.ts | 37 ++++- .../main/features/browser/registry.test.ts | 36 ++++- .../renderer/state/operations/browser.test.ts | 66 +++++++- .../state/stores/tabs/new-tab-types.test.ts | 5 +- 7 files changed, 289 insertions(+), 89 deletions(-) diff --git a/src/main/features/browser/ipc.ts b/src/main/features/browser/ipc.ts index d910a45dc..8b9c41301 100644 --- a/src/main/features/browser/ipc.ts +++ b/src/main/features/browser/ipc.ts @@ -1,12 +1,6 @@ /** * Browser tab IPC channel — bridges renderer commands to BrowserTabRegistry - * and broadcasts WebContents lifecycle events back to all renderer windows. - * - * BROADCASTS - * ---------- - * Every browser.* event (navigated, loadingChanged, loadFailureChanged, titleUpdated) is - * sent via the shared `broadcast` helper so all open renderer windows receive - * it. The renderer is responsible for filtering by tabId. + * and routes WebContents lifecycle events to the renderer that created the view. * * SECURITY * -------- @@ -24,9 +18,9 @@ */ import { ipcContract } from "../../../shared/ipc/contract"; -import { ipcOk } from "../../../shared/ipc/result"; +import { ipcErr, ipcOk } from "../../../shared/ipc/result"; import { COMMANDS } from "../../../shared/keybindings/commands"; -import { broadcast, register, validateArgs } from "../../infra/ipc-router"; +import { broadcast, type CallContext, register, validateArgs } from "../../infra/ipc-router"; import type { GlobalStorage } from "../../infra/storage/global-storage"; import type { WorkspaceStorage } from "../../infra/storage/workspace-storage"; import { getActiveAppWindow } from "../window/app-windows"; @@ -67,7 +61,12 @@ export interface BrowserChannelDeps { * directly; URL focus needs the renderer, so it is bounced over IPC. App * commands (tabs, groups, workspaces…) run in the app window. */ -function runBrowserCommand(registry: BrowserTabRegistry, command: string, tabId: string): void { +function runBrowserCommand( + registry: BrowserTabRegistry, + command: string, + tabId: string, + focusUrl: () => void, +): void { switch (command) { case COMMANDS.browserReload: registry.reload({ tabId }); @@ -82,7 +81,7 @@ function runBrowserCommand(registry: BrowserTabRegistry, command: string, tabId: registry.goForward({ tabId }); break; case COMMANDS.browserFocusUrl: - broadcast("browser", "focusUrl", { tabId }); + focusUrl(); break; default: { // As if the key had been pressed in the app window: that window takes @@ -99,13 +98,36 @@ export function registerBrowserChannel( registry: BrowserTabRegistry, channelDeps?: BrowserChannelDeps, ): void { + type Owner = { viewId: string; sender: NonNullable }; + const owners = new Map(); + + /** Publish current-generation events directly to the view's renderer. */ + function sendViewEvent( + tabId: string, + event: string, + payload: Record, + owner = owners.get(tabId), + ): void { + if (!owner || owners.get(tabId) !== owner || owner.sender.isDestroyed()) return; + owner.sender.send("ipc:event", "browser", event, { ...payload, tabId, viewId: owner.viewId }); + } + + /** Resolve a request from the owning renderer, optionally for a particular generation. */ + function ownsView(tabId: string, ctx: CallContext | undefined, viewId?: string): boolean { + const owner = owners.get(tabId); + return ( + owner !== undefined && + owner.sender.id === ctx?.sender?.id && + (viewId === undefined || viewId === owner.viewId) + ); + } + registry.onLoadFailure((tabId, failure) => { - broadcast("browser", "loadFailureChanged", { tabId, failure }); + sendViewEvent(tabId, "loadFailureChanged", { failure }); }); registry.onRefused((tabId, url, error) => { const { kind, reason } = error as { kind?: unknown; reason?: unknown }; - broadcast("browser", "refused", { - tabId, + sendViewEvent(tabId, "refused", { url, kind: typeof kind === "string" ? kind : "failed", message: typeof reason === "string" ? reason : error.message, @@ -113,21 +135,45 @@ export function registerBrowserChannel( }); register("browser", { call: { - create: (args: unknown) => { - const { tabId, workspaceId, url, partition } = validateArgs(c.create.args, args); - registry.create({ tabId, workspaceId, url, partition }); + create: (args: unknown, ctx) => { + const { tabId, viewId, workspaceId, url, partition } = validateArgs(c.create.args, args); + if (!ctx?.sender) return ipcErr("not-found", "Browser renderer is unavailable"); + const previous = owners.get(tabId); + if (previous && previous.sender.id !== ctx.sender.id && !previous.sender.isDestroyed()) { + return ipcErr("conflict", "Browser tab is open in another window"); + } + // Dispose the old generation before allowing the new one to emit. + owners.delete(tabId); + if (registry.get(tabId)) registry.destroy({ tabId }); + const owner = { viewId, sender: ctx.sender }; + owners.set(tabId, owner); + try { + registry.create({ tabId, workspaceId, url, partition }); + } catch (error) { + owners.delete(tabId); + return ipcErr("browser-create-failed", String(error), { category: "bug" }); + } // Wire WebContents lifecycle events for broadcasts. // The entry was just created so it MUST be present. const entry = registry.get(tabId); - if (!entry) return ipcOk(undefined); // Should never happen; guard for safety. + if (!entry) { + owners.delete(tabId); + return ipcErr("browser-create-failed", "Browser view was not created", { + category: "bug", + }); + } const wc = entry.view.webContents; + wc.once("destroyed", () => { + if (owners.get(tabId) === owner) owners.delete(tabId); + }); + const emit = (event: string, value: Record) => + sendViewEvent(tabId, event, value, owner); noticeDownloads(wc.session, (_from, file) => broadcast("browser", "downloaded", { file })); wc.on("did-navigate", (_event, navUrl, _httpResponseCode, _httpStatusText) => { - broadcast("browser", "navigated", { - tabId, + emit("navigated", { url: navUrl, canGoBack: wc.navigationHistory.canGoBack(), canGoForward: wc.navigationHistory.canGoForward(), @@ -136,8 +182,7 @@ export function registerBrowserChannel( wc.on("did-navigate-in-page", (_event, navUrl, isMainFrame) => { if (!isMainFrame) return; - broadcast("browser", "navigated", { - tabId, + emit("navigated", { url: navUrl, canGoBack: wc.navigationHistory.canGoBack(), canGoForward: wc.navigationHistory.canGoForward(), @@ -145,23 +190,22 @@ export function registerBrowserChannel( }); wc.on("did-start-loading", () => { - broadcast("browser", "loadingChanged", { tabId, isLoading: true }); + emit("loadingChanged", { isLoading: true }); }); wc.on("did-stop-loading", () => { - broadcast("browser", "loadingChanged", { tabId, isLoading: false }); + emit("loadingChanged", { isLoading: false }); }); wc.on("page-title-updated", (_event, title) => { - broadcast("browser", "titleUpdated", { tabId, title }); + emit("titleUpdated", { title }); }); // page-favicon-updated: fires when Chromium finds favicon URL candidates. // If the page does not declare link rel="icon", the fallback `/favicon.ico` is tried. // The renderer shows the first candidate as the tab icon (the default Globe if none). wc.on("page-favicon-updated", (_event, favicons: string[]) => { - broadcast("browser", "faviconUpdated", { - tabId, + emit("faviconUpdated", { favicons: favicons.filter(isLoadableFaviconUrl), }); }); @@ -173,7 +217,7 @@ export function registerBrowserChannel( // behaviour of every other panel type). Fires only on focus *gain*, so // it does not spam on repeated clicks inside an already-focused view. wc.on("focus", () => { - broadcast("browser", "focused", { tabId }); + emit("focused", {}); }); // Intercept keystrokes that land while the PAGE has focus — they @@ -182,65 +226,75 @@ export function registerBrowserChannel( // browser command. (The docked DevTools view is covered by the // registry's DevTools key interceptor wired above.) installBrowserKeyInterceptor(wc, tabId, (command, t) => - runBrowserCommand(registry, command, t), + runBrowserCommand(registry, command, t, () => emit("focusUrl", {})), ); return ipcOk(undefined); }, - destroy: (args: unknown) => { - const { tabId } = validateArgs(c.destroy.args, args); + destroy: (args: unknown, ctx) => { + const { tabId, viewId } = validateArgs(c.destroy.args, args); + if (!ownsView(tabId, ctx, viewId)) return ipcOk(undefined); + owners.delete(tabId); registry.destroy({ tabId }); return ipcOk(undefined); }, - setBounds: (args: unknown) => { - const { tabId, x, y, width, height } = validateArgs(c.setBounds.args, args); + setBounds: (args: unknown, ctx) => { + const { tabId, viewId, x, y, width, height } = validateArgs(c.setBounds.args, args); + if (!ownsView(tabId, ctx, viewId)) return ipcOk(undefined); registry.setBounds({ tabId, x, y, width, height }); return ipcOk(undefined); }, - setActive: (args: unknown) => { - const { tabId, active } = validateArgs(c.setActive.args, args); + setActive: (args: unknown, ctx) => { + const { tabId, viewId, active } = validateArgs(c.setActive.args, args); + if (!ownsView(tabId, ctx, viewId)) return ipcOk(undefined); registry.setActive({ tabId, active }); return ipcOk(undefined); }, - navigate: (args: unknown) => { + navigate: (args: unknown, ctx) => { const { tabId, url } = validateArgs(c.navigate.args, args); + if (!ownsView(tabId, ctx)) return ipcOk(undefined); registry.navigate({ tabId, url }); return ipcOk(undefined); }, - goBack: (args: unknown) => { + goBack: (args: unknown, ctx) => { const { tabId } = validateArgs(c.goBack.args, args); + if (!ownsView(tabId, ctx)) return ipcOk(undefined); registry.goBack({ tabId }); return ipcOk(undefined); }, - goForward: (args: unknown) => { + goForward: (args: unknown, ctx) => { const { tabId } = validateArgs(c.goForward.args, args); + if (!ownsView(tabId, ctx)) return ipcOk(undefined); registry.goForward({ tabId }); return ipcOk(undefined); }, - reload: (args: unknown) => { + reload: (args: unknown, ctx) => { const { tabId, ignoreCache } = validateArgs(c.reload.args, args); + if (!ownsView(tabId, ctx)) return ipcOk(undefined); registry.reload({ tabId, ignoreCache }); return ipcOk(undefined); }, - openDevTools: (args: unknown) => { + openDevTools: (args: unknown, ctx) => { const { tabId } = validateArgs(c.openDevTools.args, args); + if (!ownsView(tabId, ctx)) return ipcOk(undefined); const { open } = registry.openDevTools({ tabId }); // Tell the renderer to show/hide the splitter and start/stop // reporting setDevToolsBounds for this tab. - broadcast("browser", "devtoolsToggled", { tabId, open }); + sendViewEvent(tabId, "devtoolsToggled", { open }); return ipcOk(undefined); }, - setDevToolsBounds: (args: unknown) => { - const { tabId, x, y, width, height } = validateArgs(c.setDevToolsBounds.args, args); + setDevToolsBounds: (args: unknown, ctx) => { + const { tabId, viewId, x, y, width, height } = validateArgs(c.setDevToolsBounds.args, args); + if (!ownsView(tabId, ctx, viewId)) return ipcOk(undefined); registry.setDevToolsBounds({ tabId, x, y, width, height }); return ipcOk(undefined); }, @@ -248,9 +302,11 @@ export function registerBrowserChannel( suspendAll: async (args: unknown) => { const { captureSnapshot } = validateArgs(c.suspendAll.args, args); // Capture before hiding so the renderer can show the last frame under the overlay. + const capturing = new Map(owners); const snapshots = await registry.suspendAll({ captureSnapshot }); for (const { tabId, dataUrl } of snapshots) { - broadcast("browser", "snapshot", { kind: "set", tabId, dataUrl }); + const owner = capturing.get(tabId); + if (owner) sendViewEvent(tabId, "snapshot", { kind: "set", dataUrl }, owner); } return ipcOk(undefined); }, @@ -258,7 +314,7 @@ export function registerBrowserChannel( resumeAll: (args: unknown) => { validateArgs(c.resumeAll.args, args); for (const tabId of registry.resumeAll()) { - broadcast("browser", "snapshot", { kind: "cleared", tabId }); + sendViewEvent(tabId, "snapshot", { kind: "cleared" }); } return ipcOk(undefined); }, diff --git a/src/renderer/components/workspace/content/browser-view.tsx b/src/renderer/components/workspace/content/browser-view.tsx index c5d3af513..0d80380c1 100644 --- a/src/renderer/components/workspace/content/browser-view.tsx +++ b/src/renderer/components/workspace/content/browser-view.tsx @@ -59,7 +59,11 @@ import { UrlBar } from "@/components/editor/browser/url-bar"; import { EmptyState } from "@/components/ui/empty-state"; import { IconButton } from "@/components/ui/icon-button"; import { ipcCallResult } from "@/ipc/client"; -import { resolveInitialBrowserUrl } from "@/state/operations/browser"; +import { + beginBrowserView, + endBrowserView, + resolveInitialBrowserUrl, +} from "@/state/operations/browser"; import { useBrowserRuntimeStore } from "@/state/stores/browser-runtime"; import { cn } from "@/utils/cn"; @@ -125,8 +129,8 @@ export function BrowserTabView({ // updates both regions so a splitter drag still emits a single IPC pair // per paint cycle. const rafIdRef = useRef(null); - // Whether browser.create has been sent for this tabId. - const createdRef = useRef(false); + // The generation of the native view owned by this mount. + const viewIdRef = useRef(null); // User-controlled height of the inline DevTools region. Per-tab-mount; // does not survive a tab close. const [devtoolsHeight, setDevtoolsHeight] = useState(DEFAULT_DEVTOOLS_HEIGHT); @@ -169,12 +173,13 @@ export function BrowserTabView({ // ------------------------------------------------------------------------- // biome-ignore lint/correctness/useExhaustiveDependencies: tabId/workspaceId/partition are stable for lifetime useEffect(() => { - if (createdRef.current) return; - createdRef.current = true; + const viewId = beginBrowserView(workspaceId, tabId); + viewIdRef.current = viewId; const url = resolveInitialBrowserUrl({ initialUrl, lastUrl, partition }) ?? BLANK_TAB_URL; void ipcCallResult("browser", "create", { tabId, + viewId, workspaceId, url, partition, @@ -186,8 +191,9 @@ export function BrowserTabView({ cancelAnimationFrame(rafIdRef.current); rafIdRef.current = null; } - void ipcCallResult("browser", "destroy", { tabId }); - useBrowserRuntimeStore.getState().removeRuntime(tabId); + endBrowserView(tabId, viewId); + viewIdRef.current = null; + void ipcCallResult("browser", "destroy", { tabId, viewId }); }; }, []); @@ -196,6 +202,8 @@ export function BrowserTabView({ // ------------------------------------------------------------------------- const sendBounds = useCallback(() => { rafIdRef.current = null; + const viewId = viewIdRef.current; + if (viewId === null) return; const pageEl = placeholderRef.current; if (pageEl !== null) { @@ -206,6 +214,7 @@ export function BrowserTabView({ // — Chromium handles HiDPI scaling internally. void ipcCallResult("browser", "setBounds", { tabId, + viewId, x: rect.left, y: rect.top, width: rect.width, @@ -218,6 +227,7 @@ export function BrowserTabView({ const rect = dtEl.getBoundingClientRect(); void ipcCallResult("browser", "setDevToolsBounds", { tabId, + viewId, x: rect.left, y: rect.top, width: rect.width, @@ -242,7 +252,9 @@ export function BrowserTabView({ // Active state: browser.setActive // ------------------------------------------------------------------------- useEffect(() => { - void ipcCallResult("browser", "setActive", { tabId, active: isActive }); + const viewId = viewIdRef.current; + if (viewId === null) return; + void ipcCallResult("browser", "setActive", { tabId, viewId, active: isActive }); // On (re)activation the main process re-attaches the view and re-applies its // cached bounds. If the surrounding layout shifted while this tab was hidden // (e.g. the sidebar was toggled) those cached bounds are stale — re-measure. diff --git a/src/renderer/state/operations/browser.ts b/src/renderer/state/operations/browser.ts index 765698394..8813888bd 100644 --- a/src/renderer/state/operations/browser.ts +++ b/src/renderer/state/operations/browser.ts @@ -33,6 +33,7 @@ import { loopbackPort } from "../../../shared/pty/ports"; import { isNavigationSchemeAllowed } from "../../../shared/security/navigation-allowlist"; import { showToast } from "../../components/ui/toast"; import { ipcListen } from "../../ipc/client"; +import type { ListenArg, ListenEvents } from "../../ipc/types"; import { useBrowserRuntimeStore } from "../stores/browser-runtime"; import { useLayoutStore } from "../stores/layout/store"; import type { BrowserTabProps } from "../stores/tabs"; @@ -43,6 +44,35 @@ import { showForwardFailure } from "./ports"; // IPC subscriptions // --------------------------------------------------------------------------- +const browserViews = new Map(); + +/** Start a renderer-owned generation before requesting its native view. */ +export function beginBrowserView(workspaceId: string, tabId: string): string { + const viewId = crypto.randomUUID(); + browserViews.set(tabId, { workspaceId, viewId }); + return viewId; +} + +/** Drop the runtime when its view goes away, even if IPC replies are still queued. */ +export function endBrowserView(tabId: string, viewId: string): void { + if (browserViews.get(tabId)?.viewId !== viewId) return; + browserViews.delete(tabId); + useBrowserRuntimeStore.getState().removeRuntime(tabId); +} + +/** Deliver page events only to the mounted view that requested this generation. */ +function listenToView, "downloaded">>( + event: E, + receive: (payload: ListenArg<"browser", E>, workspaceId: string) => void, +): () => void { + return ipcListen("browser", event, (payload) => { + const view = browserViews.get(payload.tabId); + if (!view || view.viewId !== payload.viewId) return; + const tab = useTabsStore.getState().byWorkspace[view.workspaceId]?.[payload.tabId]; + if (tab?.type === "browser") receive(payload, view.workspaceId); + }); +} + type Unsubscribe = () => void; let activeUnsubs: Unsubscribe[] = []; @@ -60,26 +90,25 @@ export function initBrowserRuntimeSubscriptions(): void { activeUnsubs = []; activeUnsubs.push( - ipcListen("browser", "navigated", ({ tabId, url, canGoBack, canGoForward }) => { + listenToView("navigated", ({ tabId, url, canGoBack, canGoForward }, workspaceId) => { useBrowserRuntimeStore.getState().setRuntime(tabId, { currentUrl: url, canGoBack, canGoForward, }); // Capture the committed URL before layout persistence takes its snapshot. - const workspaceId = findWorkspaceForTab(tabId); - if (workspaceId) useTabsStore.getState().setBrowserLastUrl(workspaceId, tabId, url); + useTabsStore.getState().setBrowserLastUrl(workspaceId, tabId, url); }), ); activeUnsubs.push( - ipcListen("browser", "loadingChanged", ({ tabId, isLoading }) => { + listenToView("loadingChanged", ({ tabId, isLoading }) => { useBrowserRuntimeStore.getState().setRuntime(tabId, { isLoading }); }), ); activeUnsubs.push( - ipcListen("browser", "loadFailureChanged", ({ tabId, failure }) => { + listenToView("loadFailureChanged", ({ tabId, failure }) => { useBrowserRuntimeStore.getState().setRuntime(tabId, { loadFailure: failure, ...(failure ? { isLoading: false } : {}), @@ -89,29 +118,24 @@ export function initBrowserRuntimeSubscriptions(): void { // A local address of an SSH workspace whose port could not be forwarded. activeUnsubs.push( - ipcListen("browser", "refused", ({ tabId, url, kind, message }) => { - const workspaceId = findWorkspaceForTab(tabId); - if (!workspaceId) return; + listenToView("refused", ({ url, kind, message }, workspaceId) => { showForwardFailure(workspaceId, loopbackPort(url) ?? 0, kind, message); }), ); activeUnsubs.push( - ipcListen("browser", "titleUpdated", ({ tabId, title }) => { + listenToView("titleUpdated", ({ tabId, title }, workspaceId) => { useBrowserRuntimeStore.getState().setRuntime(tabId, { title }); // Sync processTitle onto the tab too — so the tab name follows the page title like Chrome. // If the user set customTitle via renameTab, the display stays as is. - const workspaceId = findWorkspaceForTab(tabId); - if (workspaceId) { - useTabsStore.getState().setProcessTitle(workspaceId, tabId, title); - } + useTabsStore.getState().setProcessTitle(workspaceId, tabId, title); }), ); // page-favicon-updated → browser-runtime store. Uses only the first entry of the candidate array. // If null or an empty array, faviconUrl is cleared so TabItem returns to the default Globe icon. activeUnsubs.push( - ipcListen("browser", "faviconUpdated", ({ tabId, favicons }) => { + listenToView("faviconUpdated", ({ tabId, favicons }) => { const next = favicons && favicons.length > 0 ? favicons[0] : null; useBrowserRuntimeStore.getState().setRuntime(tabId, { faviconUrl: next }); }), @@ -124,7 +148,7 @@ export function initBrowserRuntimeSubscriptions(): void { // `cleared` event clears the cache when the modal closes and the native // view is shown again. activeUnsubs.push( - ipcListen("browser", "snapshot", (payload) => { + listenToView("snapshot", (payload) => { if (payload.kind === "set") { useBrowserRuntimeStore.getState().setRuntime(payload.tabId, { snapshot: payload.dataUrl }); } else { @@ -138,7 +162,7 @@ export function initBrowserRuntimeSubscriptions(): void { // ResizeObserver that sends `setDevToolsBounds`; when it returns to false // the region unmounts and the page region reclaims the full content area. activeUnsubs.push( - ipcListen("browser", "devtoolsToggled", ({ tabId, open }) => { + listenToView("devtoolsToggled", ({ tabId, open }) => { useBrowserRuntimeStore.getState().setRuntime(tabId, { devtoolsOpen: open }); }), ); @@ -149,7 +173,7 @@ export function initBrowserRuntimeSubscriptions(): void { // group that owns the tab so clicking a browser panel behaves like clicking // any other panel. activeUnsubs.push( - ipcListen("browser", "focused", ({ tabId }) => { + listenToView("focused", ({ tabId }) => { activateGroupForTab(tabId); }), ); @@ -158,7 +182,7 @@ export function initBrowserRuntimeSubscriptions(): void { // focus, so it was caught by the main key interceptor and bounced here — // focus the address bar for that tab (mirrors the in-renderer command). activeUnsubs.push( - ipcListen("browser", "focusUrl", ({ tabId }) => { + listenToView("focusUrl", ({ tabId }) => { useBrowserRuntimeStore.getState().requestUrlFocus(tabId); }), ); diff --git a/src/shared/ipc/contract.ts b/src/shared/ipc/contract.ts index 76ae5faed..efa2b5a5d 100644 --- a/src/shared/ipc/contract.ts +++ b/src/shared/ipc/contract.ts @@ -1805,6 +1805,7 @@ export const ipcContract = { create: call( z.object({ tabId: z.string().uuid(), + viewId: z.string().uuid(), workspaceId: WorkspaceIdPrimitive, url: z.string().url(), partition: z.string().min(1), @@ -1812,7 +1813,7 @@ export const ipcContract = { z.void(), ), /** Destroy the WebContentsView and release all resources for `tabId`. */ - destroy: call(z.object({ tabId: z.string().uuid() }), z.void()), + destroy: call(z.object({ tabId: z.string().uuid(), viewId: z.string().uuid() }), z.void()), /** * Resize/reposition the view. * @@ -1825,6 +1826,7 @@ export const ipcContract = { setBounds: call( z.object({ tabId: z.string().uuid(), + viewId: z.string().uuid(), x: z.number(), y: z.number(), width: z.number(), @@ -1833,7 +1835,10 @@ export const ipcContract = { z.void(), ), /** Attach (active=true) or detach (active=false) the view. */ - setActive: call(z.object({ tabId: z.string().uuid(), active: z.boolean() }), z.void()), + setActive: call( + z.object({ tabId: z.string().uuid(), viewId: z.string().uuid(), active: z.boolean() }), + z.void(), + ), /** Navigate the tab to `url`. */ navigate: call(z.object({ tabId: z.string().uuid(), url: z.string().url() }), z.void()), goBack: call(z.object({ tabId: z.string().uuid() }), z.void()), @@ -1866,6 +1871,7 @@ export const ipcContract = { setDevToolsBounds: call( z.object({ tabId: z.string().uuid(), + viewId: z.string().uuid(), x: z.number(), y: z.number(), width: z.number(), @@ -1909,17 +1915,21 @@ export const ipcContract = { navigated: listen( z.object({ tabId: z.string().uuid(), + viewId: z.string().uuid(), url: z.string(), canGoBack: z.boolean(), canGoForward: z.boolean(), }), ), /** Emitted when the loading spinner should be shown or hidden. */ - loadingChanged: listen(z.object({ tabId: z.string().uuid(), isLoading: z.boolean() })), + loadingChanged: listen( + z.object({ tabId: z.string().uuid(), viewId: z.string().uuid(), isLoading: z.boolean() }), + ), /** The main frame's last load failure, cleared on successful navigation. */ loadFailureChanged: listen( z.object({ tabId: z.string().uuid(), + viewId: z.string().uuid(), failure: z.object({ url: z.string(), description: z.string() }).nullable(), }), ), @@ -1930,13 +1940,16 @@ export const ipcContract = { refused: listen( z.object({ tabId: z.string().uuid(), + viewId: z.string().uuid(), url: z.string(), kind: z.string(), message: z.string(), }), ), /** Emitted when the page title changes. */ - titleUpdated: listen(z.object({ tabId: z.string().uuid(), title: z.string() })), + titleUpdated: listen( + z.object({ tabId: z.string().uuid(), viewId: z.string().uuid(), title: z.string() }), + ), /** * Emitted when the page advertises favicon(s). * @@ -1948,6 +1961,7 @@ export const ipcContract = { faviconUpdated: listen( z.object({ tabId: z.string().uuid(), + viewId: z.string().uuid(), favicons: z.array(z.string()).nullable(), }), ), @@ -1968,9 +1982,14 @@ export const ipcContract = { z.object({ kind: z.literal("set"), tabId: z.string().uuid(), + viewId: z.string().uuid(), dataUrl: z.string(), }), - z.object({ kind: z.literal("cleared"), tabId: z.string().uuid() }), + z.object({ + kind: z.literal("cleared"), + tabId: z.string().uuid(), + viewId: z.string().uuid(), + }), ]), ), /** @@ -1978,7 +1997,9 @@ export const ipcContract = { * docked-DevTools state so the renderer can show / hide its splitter * region and start / stop reporting `setDevToolsBounds`. */ - devtoolsToggled: listen(z.object({ tabId: z.string().uuid(), open: z.boolean() })), + devtoolsToggled: listen( + z.object({ tabId: z.string().uuid(), viewId: z.string().uuid(), open: z.boolean() }), + ), /** * Emitted when the tab's WebContentsView gains focus (e.g. the user * clicks anywhere in the page). @@ -1992,7 +2013,7 @@ export const ipcContract = { * activate the group that owns `tabId` whenever the page itself is * clicked, matching the behaviour of every other panel type. */ - focused: listen(z.object({ tabId: z.string().uuid() })), + focused: listen(z.object({ tabId: z.string().uuid(), viewId: z.string().uuid() })), /** * Emitted when the browser URL-focus shortcut (browser.focusUrl, * ⌘L by default) fires while the page itself has focus. Because the @@ -2002,7 +2023,7 @@ export const ipcContract = { * focus the address bar. The other browser shortcuts act in main * directly; only URL focus needs a renderer round-trip. */ - focusUrl: listen(z.object({ tabId: z.string().uuid() })), + focusUrl: listen(z.object({ tabId: z.string().uuid(), viewId: z.string().uuid() })), /** * A download the user started in a browser tab is done, saved as * `file` where downloads go. One a nexus command started is told in diff --git a/tests/unit/main/features/browser/registry.test.ts b/tests/unit/main/features/browser/registry.test.ts index f51fe03b9..3212e4aa1 100644 --- a/tests/unit/main/features/browser/registry.test.ts +++ b/tests/unit/main/features/browser/registry.test.ts @@ -61,8 +61,10 @@ const { registerBrowserChannel } = await import("../../../../../src/main/feature const { CdpBrowserDriver } = await import("../../../../../src/main/features/cli/browser/driver"); const tabId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; +const viewId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; const createArgs = { tabId, + viewId, workspaceId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", partition: "persist:test", url: "https://example.com", @@ -79,7 +81,7 @@ describe("browser visibility IPC", () => { } function setActive(active: boolean) { - return call("setActive", { tabId, active }); + return call("setActive", { tabId, viewId, active }); } function snapshots() { @@ -112,13 +114,37 @@ describe("browser visibility IPC", () => { resetInMemoryIpc(); }); + test("a browser view only sends events to its owner and survives an older generation's destroy", async () => { + const other = createIpcPair(); + Object.defineProperty(other.sender, "id", { value: nextContentsId++ }); + page.webContents.emit("focus"); + expect(pair.sender.sent).toContainEqual({ + channel: "ipc:event", + args: ["browser", "focused", { tabId, viewId }], + }); + expect(other.sender.sent).toEqual([]); + + const replacement = crypto.randomUUID(); + await call("create", { ...createArgs, viewId: replacement }); + await call("destroy", { tabId, viewId }); + await other.window.ipc.call("browser", "destroy", { tabId, viewId: replacement }); + const current = registry.get(tabId)?.view as unknown as FakeWebContentsView; + expect(current).toBeDefined(); + expect(current).not.toBe(page); + current.webContents.emit("focus"); + expect(pair.sender.sent.at(-1)).toEqual({ + channel: "ipc:event", + args: ["browser", "focused", { tabId, viewId: replacement }], + }); + }); + test("restores a detached page and DevTools when they attach after resume", async () => { await call("openDevTools", { tabId }); const devTools = registry.get(tabId)!.devtoolsView as unknown as FakeWebContentsView; await call("suspendAll", { captureSnapshot: true }); expect(page.visible).toBe(false); expect(devTools.visible).toBe(false); - expect(snapshots()).toEqual([{ kind: "set", tabId, dataUrl: expect.any(String) }]); + expect(snapshots()).toEqual([{ kind: "set", tabId, viewId, dataUrl: expect.any(String) }]); await setActive(false); await call("resumeAll", {}); @@ -128,7 +154,7 @@ describe("browser visibility IPC", () => { expect(attached).toEqual(new Set([page, devTools])); expect(page.visible).toBe(true); expect(devTools.visible).toBe(true); - expect(snapshots().at(-1)).toEqual({ kind: "cleared", tabId }); + expect(snapshots().at(-1)).toEqual({ kind: "cleared", tabId, viewId }); }); test("restores DevTools reopened after it was closed while suspended", async () => { @@ -178,7 +204,7 @@ describe("browser visibility IPC", () => { const capture = Promise.withResolvers(); page.webContents.capturePage.mockReturnValueOnce(capture.promise); const suspended = call("suspendAll", { captureSnapshot: true }); - await call("destroy", { tabId }); + await call("destroy", { tabId, viewId }); await call("create", createArgs); await setActive(true); capture.resolve(image); @@ -200,7 +226,7 @@ describe("browser visibility IPC", () => { expect(registry.get(tabId)?.loadFailure).toEqual(failure); expect(pair.sender.sent).toContainEqual({ channel: "ipc:event", - args: ["browser", "loadFailureChanged", { tabId, failure }], + args: ["browser", "loadFailureChanged", { tabId, viewId, failure }], }); expect(page.visible).toBe(false); diff --git a/tests/unit/renderer/state/operations/browser.test.ts b/tests/unit/renderer/state/operations/browser.test.ts index 23c1f352e..e39f71841 100644 --- a/tests/unit/renderer/state/operations/browser.test.ts +++ b/tests/unit/renderer/state/operations/browser.test.ts @@ -24,8 +24,9 @@ import { describe, expect, it } from "bun:test"; // Imports (after shims) // --------------------------------------------------------------------------- -import { resolveInitialBrowserUrl } from "../../../../../src/renderer/state/operations/browser"; -import type { BrowserTabProps } from "../../../../../src/renderer/state/stores/tabs"; +import * as browserOperations from "../../../../../src/renderer/state/operations/browser"; +import { useBrowserRuntimeStore } from "../../../../../src/renderer/state/stores/browser-runtime"; +import { type BrowserTabProps, useTabsStore } from "../../../../../src/renderer/state/stores/tabs"; // --------------------------------------------------------------------------- // resolveInitialBrowserUrl @@ -37,14 +38,71 @@ describe("resolveInitialBrowserUrl", () => { } it("returns null for a javascript: scheme", () => { - const result = resolveInitialBrowserUrl(makeProps("javascript:alert(1)")); + const result = browserOperations.resolveInitialBrowserUrl(makeProps("javascript:alert(1)")); expect(result).toBeNull(); }); it("does not fall back to initialUrl when lastUrl fails validation", () => { - const result = resolveInitialBrowserUrl( + const result = browserOperations.resolveInitialBrowserUrl( makeProps("javascript:void(0)", "https://fallback.example.com"), ); expect(result).toBeNull(); }); }); + +it("ignores events from a closed browser generation and accepts the reopened view's events", () => { + const workspaceId = crypto.randomUUID(); + const tab = useTabsStore.getState().createTab(workspaceId, { + type: "browser", + props: { initialUrl: "", lastUrl: "", partition: "persist:test" }, + }); + const originalWindow = globalThis.window; + const listeners = new Map void>(); + Object.assign(globalThis, { + window: { + ipc: { + listen: (_channel: string, event: string, callback: (payload: unknown) => void) => { + listeners.set(event, callback); + return () => listeners.delete(event); + }, + }, + }, + }); + const nav = (viewId: string, url: string) => + listeners.get("navigated")?.({ + tabId: tab.id, + viewId, + url, + canGoBack: false, + canGoForward: false, + }); + const current = () => useBrowserRuntimeStore.getState().runtimes.get(tab.id); + try { + browserOperations.initBrowserRuntimeSubscriptions(); + const first = browserOperations.beginBrowserView(workspaceId, tab.id); + nav(first, "https://old.example"); + expect(current()?.currentUrl).toBe("https://old.example"); + browserOperations.endBrowserView(tab.id, first); + + listeners.get("snapshot")?.({ + kind: "set", + tabId: tab.id, + viewId: first, + dataUrl: "old snapshot", + }); + expect(current()).toBeUndefined(); + + const second = browserOperations.beginBrowserView(workspaceId, tab.id); + nav(second, "https://new.example"); + nav(first, "https://stale.example"); + expect(current()?.currentUrl).toBe("https://new.example"); + expect(useTabsStore.getState().byWorkspace[workspaceId]?.[tab.id]).toMatchObject({ + props: { lastUrl: "https://new.example" }, + }); + browserOperations.endBrowserView(tab.id, second); + } finally { + useBrowserRuntimeStore.getState().removeRuntime(tab.id); + useTabsStore.getState().closeAllForWorkspace(workspaceId); + Object.assign(globalThis, { window: originalWindow }); + } +}); diff --git a/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts b/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts index a1bb19fec..8ccf1d0cf 100644 --- a/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts +++ b/tests/unit/renderer/state/stores/tabs/new-tab-types.test.ts @@ -30,7 +30,7 @@ mock.module("electron", () => ({ const originalWindow = globalThis.window; let listeners = new Map void>(); const { registerWindowChannel } = await import("../../../../../../src/main/features/window/ipc"); -const { initBrowserRuntimeSubscriptions } = await import( +const { initBrowserRuntimeSubscriptions, beginBrowserView, endBrowserView } = await import( "../../../../../../src/renderer/state/operations/browser" ); const { closeTab } = await import("../../../../../../src/renderer/state/operations/tabs"); @@ -321,8 +321,10 @@ test("closing flushes queued tab, split and browser URL changes after an older s }).id, ); const url = "https://example.com/latest"; + const viewId = beginBrowserView(workspaceId, browser); listeners.get("browser.navigated")?.({ tabId: browser, + viewId, url, canGoBack: true, canGoForward: false, @@ -352,6 +354,7 @@ test("closing flushes queued tab, split and browser URL changes after an older s await closed.promise; expect(saves).toBe(2); expect(warnings).toEqual([]); + endBrowserView(browser, viewId); unregisterStatePersistence(); registerAppStateChannel(new StateService(stateFile), { From 5e0be52b808cb479b52093b9ce2948ccb02863b7 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:16:13 +0900 Subject: [PATCH 060/208] fix(pty): coalesce concurrent spawns for a tab Co-Authored-By: Claude Opus 5.5 --- internal/pty/hangup_test.go | 114 ++++++++++++++++++++---------------- internal/pty/service.go | 86 +++++++++++++++++---------- 2 files changed, 121 insertions(+), 79 deletions(-) diff --git a/internal/pty/hangup_test.go b/internal/pty/hangup_test.go index d970241f6..3d7b2825d 100644 --- a/internal/pty/hangup_test.go +++ b/internal/pty/hangup_test.go @@ -13,6 +13,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "syscall" "testing" "time" @@ -220,60 +221,75 @@ while :; do sleep 1; done requireGone(t, job, 2*time.Second, "the background job") } -// zombieChildren lists this process's children that ended and were never -// waited for. -func zombieChildren(t *testing.T) []string { - t.Helper() - out, err := exec.Command("ps", "-A", "-o", "pid=,ppid=,stat=").Output() - if err != nil { - t.Fatalf("ps: %v", err) - } - self := strconv.Itoa(os.Getpid()) - var zombies []string - for _, line := range strings.Split(string(out), "\n") { - fields := strings.Fields(line) - if len(fields) == 3 && fields[1] == self && strings.HasPrefix(fields[2], "Z") { - zombies = append(zombies, fields[0]) - } - } - return zombies +// spawnWaitContext signals once the second request has reached its wait. +type spawnWaitContext struct { + context.Context + waiting func() +} + +// Done exposes the wait barrier and the context's original cancellation. +func (c spawnWaitContext) Done() <-chan struct{} { + c.waiting() + return c.Context.Done() } -// Two spawns of one tab racing each other start two shells; the one that -// loses is killed, and must be waited for too or it stays a zombie of the -// daemon. Not parallel: other tests' shells are briefly zombies as they end. -func TestRacingSpawnsOfATabLeaveNoZombie(t *testing.T) { +// TestRacingSpawnsOfATabForkOnlyOnce checks that overlapping requests +// share the shell even before it has been published in the session map. +func TestRacingSpawnsOfATabForkOnlyOnce(t *testing.T) { service, _ := newTestService(t) - for i := 0; i < 5; i++ { - params := mustJSON(t, SpawnParams{ - WorkspaceID: testWorkspaceID, TabID: fmt.Sprintf("race-%d", i), Cwd: t.TempDir(), - Shell: "/bin/sh", Args: []string{"-c", "sleep 30"}, Cols: 80, Rows: 24, - }) - start := make(chan struct{}) - var wg sync.WaitGroup - for j := 0; j < 2; j++ { - wg.Add(1) - go func() { - defer wg.Done() - <-start - if _, err := service.Spawn(context.Background(), params); err != nil { - t.Errorf("spawn: %v", err) - } - }() + first, duplicate, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + var starts atomic.Int32 + service.startPTY = func(spec spawnSpec) (*terminal, *child, error) { + if starts.Add(1) != 1 { + close(duplicate) + return nil, nil, errors.New("a second shell was started") } - close(start) - wg.Wait() + close(first) + <-release + return startTerminal(spec) } - deadline := time.Now().Add(2 * time.Second) - for { - zombies := zombieChildren(t) - if len(zombies) == 0 { - return - } - if time.Now().After(deadline) { - t.Fatalf("shells never waited for: %v", zombies) - } - time.Sleep(50 * time.Millisecond) + params := mustJSON(t, SpawnParams{ + WorkspaceID: testWorkspaceID, TabID: "racing-spawns", Cwd: t.TempDir(), + Shell: "/bin/sh", Args: []string{"-c", "exec /bin/sleep 60"}, Cols: 80, Rows: 24, + }) + type response struct { + value any + err error + } + var calls sync.WaitGroup + spawn := func(ctx context.Context) <-chan response { + done := make(chan response, 1) + calls.Add(1) + go func() { + defer calls.Done() + value, err := service.Spawn(ctx, params) + done <- response{value, err} + }() + return done + } + defer func() { unblock(); calls.Wait() }() + + owner := spawn(context.Background()) + select { + case <-first: + case <-time.After(2 * time.Second): + t.Fatal("first request never attempted to start a shell") + } + waiting := make(chan struct{}) + joined := spawn(spawnWaitContext{context.Background(), sync.OnceFunc(func() { close(waiting) })}) + select { + case <-waiting: + case <-duplicate: + t.Fatal("second request forked a shell for an already starting tab") + case <-time.After(2 * time.Second): + t.Fatal("second request neither started nor joined the first") + } + + unblock() + a, b := <-owner, <-joined + if a.err != nil || b.err != nil || a.value != b.value || starts.Load() != 1 { + t.Fatalf("spawns returned %+v and %+v with %d starts", a, b, starts.Load()) } } diff --git a/internal/pty/service.go b/internal/pty/service.go index 1a21db4ea..51d595b0a 100644 --- a/internal/pty/service.go +++ b/internal/pty/service.go @@ -12,7 +12,6 @@ import ( "strings" "sync" "sync/atomic" - "syscall" "time" "github.com/nexus-code/nexus-code/internal/dispatch" @@ -24,11 +23,22 @@ type Service struct { mu sync.Mutex output *outputSink sessions map[tabKey]*session + startPTY func(spawnSpec) (*terminal, *child, error) + spawning map[tabKey]*pendingSpawn + starts sync.WaitGroup + closed bool // closedTabs are the tabs a kill came for while they had no session, // and when: see Kill. closedTabs map[tabKey]time.Time } +// pendingSpawn publishes one shell startup result to concurrent callers. +type pendingSpawn struct { + done chan struct{} + result SpawnResult + err error +} + // outputSink identifies a connection and captures its event destination. // The pointer distinguishes successive sink installations, and the host's // Done channel identifies the connection that dispatched a replay or ACK. @@ -153,6 +163,8 @@ func New() *Service { output: &outputSink{ctx: context.Background()}, sessions: make(map[tabKey]*session), closedTabs: make(map[tabKey]time.Time), + startPTY: startTerminal, + spawning: make(map[tabKey]*pendingSpawn), } } @@ -186,6 +198,11 @@ func (s *Service) SetEventSink(ctx context.Context, sink EventSink) { // Close ends every PTY session, as closing each tab does, and returns once // their shells are gone: hung up, or killed hangupGrace later. func (s *Service) Close() { + s.mu.Lock() + s.closed = true + s.mu.Unlock() + s.starts.Wait() + s.mu.Lock() sessions := make([]*session, 0, len(s.sessions)) for key, session := range s.sessions { @@ -204,7 +221,7 @@ func (s *Service) Close() { } // Spawn starts one shell process under a PTY and begins forwarding output events. -func (s *Service) Spawn(_ context.Context, raw json.RawMessage) (any, error) { +func (s *Service) Spawn(ctx context.Context, raw json.RawMessage) (any, error) { var p SpawnParams if err := decodeParams(raw, &p, "pty.spawn params must include workspaceId, tabId, cwd, cols, and rows"); err != nil { return nil, err @@ -220,19 +237,49 @@ func (s *Service) Spawn(_ context.Context, raw json.RawMessage) (any, error) { return nil, err } - if existing := s.lookup(key); existing != nil { + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return nil, requestFailed("PTY service is closed") + } + if starting := s.spawning[key]; starting != nil { + s.mu.Unlock() + select { + case <-starting.done: + return starting.result, starting.err + case <-ctx.Done(): + return nil, ctx.Err() + } + } + if existing := s.sessions[key]; existing != nil { + s.mu.Unlock() // The session outlived its previous client (an app restart or a window // reload). Fit it to the new client, which replays it to redraw the // screen. Best-effort: a session that is exiting reports exit anyway. _ = existing.resize(p.Cols, p.Rows) return SpawnResult{PID: existing.child.Pid, Attached: true}, nil } + attempt := &pendingSpawn{done: make(chan struct{})} + s.spawning[key] = attempt + s.starts.Add(1) + s.mu.Unlock() + defer s.starts.Done() + attempt.result, attempt.err = s.spawnSession(key, p) + s.mu.Lock() + delete(s.spawning, key) + close(attempt.done) + s.mu.Unlock() + return attempt.result, attempt.err +} + +// spawnSession starts and registers a shell for a reserved tab. +func (s *Service) spawnSession(key tabKey, p SpawnParams) (SpawnResult, error) { shell := strings.TrimSpace(p.Shell) if shell == "" { shell = defaultShell() } - master, child, err := startTerminal(spawnSpec{ + master, child, err := s.startPTY(spawnSpec{ shell: shell, args: p.Args, dir: p.Cwd, @@ -241,7 +288,7 @@ func (s *Service) Spawn(_ context.Context, raw json.RawMessage) (any, error) { rows: p.Rows, }) if err != nil { - return nil, requestFailed("failed to spawn PTY: %s", err) + return SpawnResult{}, requestFailed("failed to spawn PTY: %s", err) } session := newSession(s, key, child, master) @@ -250,12 +297,7 @@ func (s *Service) Spawn(_ context.Context, raw json.RawMessage) (any, error) { session.lastRows = p.Rows session.sizeMu.Unlock() - stored, closed := s.storeSession(key, session) - if stored != session { - // Another spawn of the tab, racing this one, got there first. - session.discard() - return SpawnResult{PID: stored.child.Pid}, nil - } + closed := s.storeSession(key, session) go session.readLoop() go session.waitLoop() @@ -649,18 +691,6 @@ func (s *session) stop() <-chan struct{} { return s.stopDone } -// discard ends the shell of a session no tab took, as another spawn of the -// tab won: it never ran anything of the user's, so it is killed outright. -// Nothing else waits for it, so this does, or it stays a zombie. -func (s *session) discard() { - s.stopOnce.Do(func() { - _ = s.child.signalGroup(syscall.SIGKILL) - s.stopReading() - close(s.stopDone) - }) - go func() { _, _ = s.child.wait() }() -} - // stopReading wakes any paused reader and closes the PTY master. func (s *session) stopReading() { s.service.mu.Lock() @@ -818,20 +848,16 @@ func writeFull(writer io.Writer, data []byte) error { return nil } -// storeSession inserts a session unless another goroutine already claimed -// the key, and reports whether a kill for the tab came first (see Kill). -func (s *Service) storeSession(key tabKey, session *session) (stored *session, closed bool) { +// storeSession publishes the tab's reserved shell and reports an early kill. +func (s *Service) storeSession(key tabKey, session *session) (closed bool) { s.mu.Lock() defer s.mu.Unlock() - if existing := s.sessions[key]; existing != nil { - return existing, false - } s.sessions[key] = session if at, ok := s.closedTabs[key]; ok { delete(s.closedTabs, key) closed = time.Since(at) <= closedTabMemory } - return session, closed + return closed } // lookup returns the active session for key, if any. From 647c3da17813ae3d974f870e7021958ffbb0b37b Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:16:13 +0900 Subject: [PATCH 061/208] test(notifications): match the asker subprocess deadline Co-Authored-By: Claude Opus 5.5 --- .../platform/desktop-notifications.test.ts | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/tests/unit/main/infra/platform/desktop-notifications.test.ts b/tests/unit/main/infra/platform/desktop-notifications.test.ts index 8560b9b72..2173901ad 100644 --- a/tests/unit/main/infra/platform/desktop-notifications.test.ts +++ b/tests/unit/main/infra/platform/desktop-notifications.test.ts @@ -204,13 +204,24 @@ describe("askNotificationService", () => { describe("runAsker", () => { const node = process.execPath; - - test("tells a command that ran, failed, or is not there", async () => { - expect(await runAsker(node, ["-e", ""], 10_000)).toEqual({ ended: "ok" }); - const failed = await runAsker(node, ["-e", "console.error('no bus'); process.exit(1)"], 10_000); - expect(failed).toEqual({ ended: "failed", detail: `${node}: no bus` }); - expect(await runAsker("nexus-no-such-command", [], 10_000)).toEqual({ ended: "missing" }); - }); + const commandTimeoutMs = 10_000; + + test( + "tells a command that ran, failed, or is not there", + async () => { + expect(await runAsker(node, ["-e", ""], commandTimeoutMs)).toEqual({ ended: "ok" }); + const failed = await runAsker( + node, + ["-e", "console.error('no bus'); process.exit(1)"], + commandTimeoutMs, + ); + expect(failed).toEqual({ ended: "failed", detail: `${node}: no bus` }); + expect(await runAsker("nexus-no-such-command", [], commandTimeoutMs)).toEqual({ + ended: "missing", + }); + }, + 2 * commandTimeoutMs + 1_000, + ); test("kills a command that does not end in time", async () => { const started = Date.now(); From 30900e225818585d76d784f792f7f96e9c363cd8 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:07:48 +0900 Subject: [PATCH 062/208] fix(chat): wait for required startup acknowledgements Co-Authored-By: Claude Opus 5.5 --- .../services/chat/codex-controller.ts | 144 ++++++++++++------ src/renderer/services/chat/controller.ts | 70 ++++++--- src/renderer/services/chat/program-startup.ts | 39 +++++ .../chat/codex-before-handshake.test.ts | 63 ++++++++ .../services/chat/controller-mode.test.ts | 71 +++++++-- .../chat/controller-open-to-read.test.ts | 26 +++- 6 files changed, 333 insertions(+), 80 deletions(-) create mode 100644 src/renderer/services/chat/program-startup.ts diff --git a/src/renderer/services/chat/codex-controller.ts b/src/renderer/services/chat/codex-controller.ts index 99e09a92b..b0ceab09d 100644 --- a/src/renderer/services/chat/codex-controller.ts +++ b/src/renderer/services/chat/codex-controller.ts @@ -61,6 +61,7 @@ import { wantPlanUsage, } from "./plan-usage"; import { lastMessageId, sameProfile, withMove } from "./profile-moves"; +import { ProgramStartup, stopChatProgram } from "./program-startup"; import type { ListedSession } from "./sessions"; import { type ChatTabState, @@ -187,6 +188,15 @@ function turnIdOf(result: Record): string | undefined { return typeof id === "string" ? id : undefined; } +/** Requires the thread a start, resume or fork claimed to establish. */ +function requireThreadId(result: Record, expected?: string): string { + const id = (result.thread as { id?: unknown } | null)?.id; + if (typeof id !== "string" || !id || (expected !== undefined && id !== expected)) { + throw new Error("Codex did not return the requested thread"); + } + return id; +} + let counter = 0; /** Ids no earlier run of the app has used, so a replayed log does not match them. */ @@ -209,6 +219,9 @@ export class CodexController { private readonly live = new LiveLines(); private flushTimer: ReturnType | null = null; private opening: Promise | null = null; + private readonly startup = new ProgramStartup(() => + stopChatProgram(this.target.workspaceId, this.target.tabId), + ); /** A started program's handshake and thread, which a message waits for. */ private ready: Promise = Promise.resolve(false); /** The handshake of the program this controller started, until it settles. */ @@ -298,6 +311,10 @@ export class CodexController { } private async doOpen(): Promise { + if (this.startup.failed) { + await this.start({}); + return; + } this.flushNow(); this.update((prev) => ({ ...prev, @@ -332,7 +349,17 @@ export class CodexController { await this.start({}); } - private async start( + /** Shares the startup through initialization and thread acquisition. */ + private start( + options: { resetLog?: boolean }, + catalogOnly = false, + forkSettings?: ReturnType, + ): Promise { + return this.startup.run(() => this.startProgram(options, catalogOnly, forkSettings)); + } + + /** Spawns Codex, getting the required protocol acknowledgements before marking it ready. */ + private async startProgram( options: { resetLog?: boolean }, catalogOnly = false, forkSettings?: ReturnType, @@ -342,6 +369,8 @@ export class CodexController { this.update((prev) => ({ ...prev, phase: "starting", error: undefined })); let result: Awaited>; try { + await this.startup.prepare(); + if (this.disposed) return false; result = await startCodex({ workspaceId, tabId, @@ -363,21 +392,17 @@ export class CodexController { return false; } if (!isSupportedCodex(result.version)) { - await ipcCallResult("chat", "stop", { workspaceId, tabId }).catch(() => {}); - this.update((prev) => ({ - ...prev, - phase: "failed", - version: result.version, - error: "old-version", - })); - return false; + this.update((prev) => ({ ...prev, version: result.version })); + return this.rejectStartup("old-version"); } this.canonicalCwd = result.canonicalCwd; - this.update((prev) => ({ ...prev, phase: "ready", version: result.version })); + this.update((prev) => ({ ...prev, version: result.version })); if (result.attached) { // A program this controller started a moment ago, whose start line has // not come yet: its handshake still decides. this.ready = this.handshaking ?? Promise.resolve(this.model.threadId !== undefined); + this.startup.failed = false; + this.update((prev) => ({ ...prev, phase: "ready" })); this.readRateLimits(); void this.availableCollaborationModes(); this.showPicks(); @@ -385,42 +410,62 @@ export class CodexController { } this.collaborationProbe = undefined; const introduced = this.introduce(); - this.introduced = introduced; - if (catalogOnly) return introduced; - const handshake = this.handshake(introduced, forkSettings) - .then((ok) => { - if (ok) this.showPicks(); - return ok; - }) + this.introduced = introduced.then( + () => true, + () => false, + ); + const handshake = (catalogOnly ? introduced : this.handshake(introduced, forkSettings)) + .then( + async () => { + if (this.disposed) return false; + this.flushNow(); + if (this.model.process === "exited") + return this.rejectStartup("Codex exited during startup"); + this.startup.failed = false; + this.update((prev) => ({ ...prev, phase: "ready" })); + if (!catalogOnly) this.showPicks(); + return true; + }, + (error: Error) => this.rejectStartup(error.message), + ) .finally(() => { if (this.handshaking === handshake) this.handshaking = null; }); this.handshaking = handshake; this.ready = handshake; - return true; + return handshake; } - /** Introduces the app to the program, which takes no other request before. */ - private async introduce(): Promise { + /** Records required startup failure and detaches from the failed program. */ + private async rejectStartup(message: string): Promise { + if (this.disposed) return false; + log.warn(`Codex startup failed: ${message}`); + this.limitsReadable = false; try { - await this.request("initialize", { - clientInfo: { name: "nexus-code", title: "NexusCode", version: __APP_VERSION__ }, - capabilities: { experimentalApi: true }, // thread/settings/update for /fast - }); - await this.write({ method: "initialized" }); - return true; - } catch (err) { - log.warn(`initialize failed: ${(err as Error).message}`); - return false; + await this.startup.reject(); + } catch (error) { + log.warn(`Codex startup cleanup failed: ${(error as Error).message}`); } + this.flushNow(); + this.update((prev) => ({ ...prev, phase: "failed", error: message })); + return false; + } + + /** Introduces the app to the program, which takes no other request before. */ + private async introduce(): Promise { + await this.request("initialize", { + clientInfo: { name: "nexus-code", title: "NexusCode", version: __APP_VERSION__ }, + capabilities: { experimentalApi: true }, // thread/settings/update for /fast + }); + await this.write({ method: "initialized" }); } /** Once the program knows the app, starts the tab's thread or goes on with the one it had. */ private async handshake( - introduced: Promise, + introduced: Promise, forkSettings?: ReturnType, ): Promise { - if (!(await introduced)) return false; + await introduced; void this.request("account/read", {}).catch(() => {}); void this.request("model/list", {}).catch(() => {}); void this.probeCollaborationModes(); @@ -436,8 +481,7 @@ export class CodexController { : undefined; const staged = await this.stage(fork); const forked = await this.forkThread(fork, settings); - const id = (forked.thread as { id?: unknown } | undefined)?.id; - const copy = typeof id === "string" ? id : undefined; + const copy = requireThreadId(forked); this.readGoal(copy); // The copy is called as the tab it came from was; one from another // profile keeps the name it had there, which Codex does not copy. @@ -454,36 +498,31 @@ export class CodexController { } catch (err) { const message = (err as Error).message; log.warn(`thread ${fork.threadId} not forked: ${message}`); - this.update((prev) => ({ ...prev, phase: "failed", error: message })); - return false; + throw err; } } if (threadId) { + let resumed: Record | undefined; try { // The log shows what came before already; a new log asks for it. - await this.request("thread/resume", { + resumed = await this.request("thread/resume", { threadId, cwd, excludeTurns: this.model.items.length > 0, }); - this.readGoal(threadId); - return true; } catch (err) { const message = (err as Error).message; log.warn(`thread ${threadId} not resumed: ${message}`); - if (this.resumingSelection) { - this.update((prev) => ({ ...prev, phase: "failed", error: message })); - return false; - } + if (this.resumingSelection) throw err; + } + if (resumed) { + requireThreadId(resumed, threadId); + this.readGoal(threadId); + return true; } } - try { - await this.request("thread/start", threadStartParams(this.target, this.next)); - return true; - } catch (err) { - log.warn(`thread/start failed: ${(err as Error).message}`); - return false; - } + requireThreadId(await this.request("thread/start", threadStartParams(this.target, this.next))); + return true; } private async forkThread( @@ -1747,7 +1786,12 @@ export class CodexController { * opens (its list of threads, its defaults) would come before that. */ private async ensureRunning(): Promise { - if (this.opening) await this.opening; + if (this.disposed) return false; + if (this.opening) { + await this.opening; + if (this.state.phase === "failed") return false; + } + if (this.startup.pending) return this.startup.pending; // The program's start line may wait for the next frame: a message sent as // the tab opens (a new task's, the CLI's) would start it again. this.flushNow(); diff --git a/src/renderer/services/chat/controller.ts b/src/renderer/services/chat/controller.ts index 66f876c3d..b79ca286a 100644 --- a/src/renderer/services/chat/controller.ts +++ b/src/renderer/services/chat/controller.ts @@ -46,6 +46,7 @@ import { } from "./model"; import { planUsageKeyFor, registerPlanSource, wantPlanUsage } from "./plan-usage"; import { lastMessageId, sameProfile, withMove } from "./profile-moves"; +import { ProgramStartup, stopChatProgram } from "./program-startup"; import { effortToApply, remoteAtStartup } from "./settings-defaults"; import { type ChatTabState, @@ -245,6 +246,9 @@ export class ChatController { private modePicks = 0; /** A started program's initialize, and the flags given again after it. */ private initializing: Promise = Promise.resolve(); + private readonly startup = new ProgramStartup(() => + stopChatProgram(this.target.workspaceId, this.target.tabId), + ); /** How many times this run of the program said it had no MCP servers, and was asked again. */ private mcpEmptyAsks = 0; private buffered: ChatLine[] = []; @@ -364,6 +368,11 @@ export class ChatController { } private async doOpen(shown: () => void): Promise { + if (this.startup.failed) { + shown(); + await this.start(this.startArgs()); + return; + } this.flushNow(); this.update((prev) => ({ ...prev, phase: "starting", error: undefined, model: emptyModel() })); let replay: ReplayResult; @@ -540,7 +549,13 @@ export class ChatController { return false; } - private async start(resume: StartArgs): Promise { + /** Starts and initializes a program before allowing tab input. */ + private start(resume: StartArgs): Promise { + return this.startup.run(() => this.startProgram(resume)); + } + + /** Spawns Claude and applies the tab's settings after its required initialize. */ + private async startProgram(resume: StartArgs): Promise { if (this.disposed) return false; const { workspaceId, tabId, cwd } = this.target; // Before the new program's initialize tells the mode it starts in. @@ -549,13 +564,14 @@ export class ChatController { this.update((prev) => ({ ...prev, phase: "starting", error: undefined })); let result: Awaited>; try { - const prepared = await this.fromAnotherProfile(resume); + await this.startup.prepare(); + const args = await this.fromAnotherProfile(resume); if (this.disposed) return false; result = await startChat({ workspaceId, tabId, cwd, - ...prepared, + ...args, ...profileArg(this.target.profileId), }); } catch (err) { @@ -572,21 +588,16 @@ export class ChatController { return false; } if (!isSupportedClaude(result.version)) { - this.update((prev) => ({ - ...prev, - phase: "failed", - version: result.version, - error: "old-version", - })); - return false; + this.update((prev) => ({ ...prev, version: result.version })); + return this.rejectStartup("old-version"); } - this.update((prev) => ({ ...prev, phase: "ready", version: result.version })); + this.update((prev) => ({ ...prev, version: result.version })); if (!result.attached) { // Subagents' text comes as messages under their Agent call, for the agent strip. let remote = false; let started: unknown; this.initPending = true; - this.initializing = this.request("initialize", { hooks: null, forwardSubagentText: true }) + const initialized = this.request("initialize", { hooks: null, forwardSubagentText: true }) .then((init) => { remote = remoteAtStartup(init); started = init.current_permission_mode; @@ -631,18 +642,38 @@ export class ChatController { } }) .then( - () => {}, - (err: Error) => { - log.warn(`initialize failed: ${err.message}`); - }, + () => true, + (err: Error) => this.rejectStartup(err.message), ) .finally(() => { this.initPending = false; }); + this.initializing = initialized.then(() => undefined); + if (!(await initialized)) return false; } + if (this.disposed) return false; + this.flushNow(); + if (this.state.model.process === "exited") + return this.rejectStartup("Claude exited during startup"); + this.startup.failed = false; + this.update((prev) => ({ ...prev, phase: "ready" })); return true; } + /** Records the failure and keeps the tab available for a fresh startup. */ + private async rejectStartup(message: string): Promise { + if (this.disposed) return false; + log.warn(`Claude startup failed: ${message}`); + try { + await this.startup.reject(); + } catch (error) { + log.warn(`Claude startup cleanup failed: ${(error as Error).message}`); + } + this.flushNow(); + this.update((prev) => ({ ...prev, phase: "failed", error: message })); + return false; + } + /** * A fork of a session another profile keeps starts from its file there: * `claude --resume --fork-session` copies it into the tab's @@ -1843,7 +1874,12 @@ export class ChatController { /** Starts the program again when it is not running, for a message to go to. */ private async ensureRunning(): Promise { - if (this.opening) await this.opening; + if (this.disposed) return false; + if (this.opening) { + await this.opening; + if (this.state.phase === "failed") return false; + } + if (this.startup.pending) return this.startup.pending; const { phase, model } = this.state; if (phase === "ready" && model.process === "running") return true; if (phase === "held" || phase === "not-found") return false; diff --git a/src/renderer/services/chat/program-startup.ts b/src/renderer/services/chat/program-startup.ts new file mode 100644 index 000000000..151cff212 --- /dev/null +++ b/src/renderer/services/chat/program-startup.ts @@ -0,0 +1,39 @@ +import { ipcCallResult, unwrapIpcResult } from "../../ipc/client"; + +/** Stops the current program and waits for the agent to confirm the stop. */ +export async function stopChatProgram(workspaceId: string, tabId: string): Promise { + unwrapIpcResult(await ipcCallResult("chat", "stop", { workspaceId, tabId })); +} + +/** Owns a tab's active startup and cleanup of a program that failed initialization. */ +export class ProgramStartup { + pending: Promise | null = null; + failed = false; + private needsStop = false; + + constructor(private readonly stop: () => Promise) {} + + /** Shares a startup between concurrent callers of the same program. */ + run(start: () => Promise): Promise { + this.pending ??= Promise.resolve() + .then(start) + .finally(() => { + this.pending = null; + }); + return this.pending; + } + + /** Refuses to start again until the failed program has stopped. */ + async prepare(): Promise { + if (!this.needsStop) return; + await this.stop(); + this.needsStop = false; + } + + /** Records a failed startup and tries to stop the program now. */ + async reject(): Promise { + this.failed = true; + this.needsStop = true; + await this.prepare(); + } +} diff --git a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts index 164d9f084..c070b06f2 100644 --- a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts +++ b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts @@ -37,6 +37,7 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ } } if (method === "send") codex?.(args.message as Message); + if (method === "stop") onStop?.(); if (method === "replay") { return Promise.resolve(replayResponse?.()).then((value) => ({ ok: true, value })); } @@ -73,6 +74,7 @@ const starts: Message[] = []; let hostFolder: { canonicalCwd?: string } = {}; let replayResponse: (() => unknown) | undefined; let onStart: (() => void) | undefined; +let onStop: (() => void) | undefined; afterEach(() => { for (const c of live.splice(0)) c.dispose(); @@ -85,6 +87,7 @@ afterEach(() => { hostFolder = {}; replayResponse = undefined; onStart = undefined; + onStop = undefined; }); /** A tab whose program is not running and answers initialize a while after it is asked. */ @@ -139,6 +142,66 @@ test("closing a Codex tab during replay cannot open a new program once replay en expect(starts).toEqual([]); }); +test("a rejected Codex initialize leaves a failed tab and lets retry spawn another program", async () => { + const c = tab(); + onStart = () => c.receive({ seq: ++lineSeq, dir: "sys", message: { event: "start" } } as never); + let stops = 0; + onStop = () => { + stops += 1; + c.receive({ seq: ++lineSeq, dir: "sys", message: { event: "exit", code: 0 } } as never); + }; + let rejectInitialize = true; + codex = (message) => { + sent.push(message); + if (message.id === undefined) return; + c.receive({ seq: ++lineSeq, dir: "in", message } as never); + const reply = + rejectInitialize && message.method === "initialize" + ? { error: { code: -32600, message: "initialize refused" } } + : { result: message.method === "thread/resume" ? { thread: { id: "t1" } } : {} }; + c.receive({ seq: ++lineSeq, dir: "out", message: { id: message.id, ...reply } } as never); + }; + await expect(c.prepareSend()).rejects.toThrow(); + expect(c.state).toMatchObject({ phase: "failed", error: "initialize refused" }); + expect(stops).toBe(1); + expect(order()).not.toContain("thread/resume"); + + rejectInitialize = false; + await c.prepareSend(); + expect(c.state.phase).toBe("ready"); + expect(starts).toHaveLength(2); + expect(c.currentThread()).toBe("t1"); +}); + +test("Codex stays unready until resume returns the requested thread", async () => { + const c = tab(); + const resuming = Promise.withResolvers(); + const reply = Promise.withResolvers(); + codex = (message) => { + if (message.id === undefined) return; + c.receive({ seq: ++lineSeq, dir: "in", message } as never); + if (message.method === "thread/resume") resuming.resolve(); + const result = message.method === "thread/resume" ? reply.promise : {}; + void Promise.resolve(result).then((value) => { + c.receive({ + seq: ++lineSeq, + dir: "out", + message: { id: message.id, result: value }, + } as never); + }); + }; + const prepared = c.prepareSend().then( + () => undefined, + (error: unknown) => error, + ); + await resuming.promise; + const phase = c.state.phase; + reply.resolve({}); + expect(await prepared).toBeInstanceOf(Error); + expect(phase).toBe("starting"); + expect(c.state.error).toBe("Codex did not return the requested thread"); +}); + test("resumes a Codex thread after agent replacement and queues against the new log", async () => { jest.useFakeTimers(); const c = tab(); diff --git a/tests/unit/renderer/services/chat/controller-mode.test.ts b/tests/unit/renderer/services/chat/controller-mode.test.ts index e24105685..1a47f1152 100644 --- a/tests/unit/renderer/services/chat/controller-mode.test.ts +++ b/tests/unit/renderer/services/chat/controller-mode.test.ts @@ -5,7 +5,7 @@ * in. The tab's first program starts as the settings say. */ import { afterEach, describe, expect, mock, test } from "bun:test"; -import type { UserItem } from "../../../../../src/renderer/services/chat/model"; +import type { ChatLine, UserItem } from "../../../../../src/renderer/services/chat/model"; type Message = Record & { request_id?: string; @@ -18,14 +18,33 @@ let tab: { receive: (line: never) => void } | undefined; const SETTINGS_MODE = "bypassPermissions"; /** While set, the program answers nothing until it settles. */ let hold: Promise | undefined; +let rejectInitialize = false; +let stops = 0; +let onInitialize: (() => void) | undefined; +const recorded: ChatLine[] = []; let lineSeq = 0; +/** Records the same line the fake agent can send live and replay. */ +function receive(dir: ChatLine["dir"], message: Message): void { + const line = { seq: ++lineSeq, dir, message } as ChatLine; + recorded.push(line); + tab?.receive(line as never); +} + /** * The program's answer to a request, after the tab's log has the request: * the mode it starts in, the mode it switched to. */ async function answer(message: Message): Promise { - tab?.receive({ seq: ++lineSeq, dir: "in", message } as never); + receive("in", message); + if (message.request?.subtype === "initialize") onInitialize?.(); + if (rejectInitialize && message.request?.subtype === "initialize") { + receive("out", { + type: "control_response", + response: { subtype: "error", request_id: message.request_id, error: "initialize refused" }, + }); + return; + } await Bun.sleep(0); if (hold) await hold; const request = message.request ?? {}; @@ -35,14 +54,10 @@ async function answer(message: Message): Promise { : request.subtype === "set_permission_mode" ? { mode: request.mode } : {}; - tab?.receive({ - seq: ++lineSeq, - dir: "out", - message: { - type: "control_response", - response: { subtype: "success", request_id: message.request_id, response }, - }, - } as never); + receive("out", { + type: "control_response", + response: { subtype: "success", request_id: message.request_id, response }, + }); } const realIpc = await import("../../../../../src/renderer/ipc/client"); @@ -55,15 +70,22 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ if (message.type === "control_request") void answer(message); } if (method === "start") { + if (args.resetLog) recorded.length = 0; + receive("sys", { event: "start" }); return Promise.resolve({ ok: true, value: { ok: true, version: "2.1.321", attached: false }, }); } + if (method === "stop") { + stops += 1; + receive("sys", { event: "exit", code: 0 }); + } if (method === "replay") { + for (const line of recorded) tab?.receive({ ...line, replay: true } as never); return Promise.resolve({ ok: true, - value: { found: false, running: false, truncated: false, lastSeq: 0 }, + value: { found: true, running: true, truncated: false, lastSeq: lineSeq }, }); } if (method === "sessionFile") { @@ -87,6 +109,27 @@ afterEach(() => { sent.length = 0; tab = undefined; hold = undefined; + rejectInitialize = false; + stops = 0; + onInitialize = undefined; + recorded.length = 0; +}); + +test("a rejected Claude initialize cannot write the first prompt, and retry starts fresh", async () => { + const c = new ChatController({ workspaceId: "ws-mode", tabId: "init-failure", cwd: "/p" }); + live.push(c); + tab = c; + rejectInitialize = true; + await expect(c.send("keep this draft", [], undefined, "submission")).rejects.toThrow(); + expect(c.state).toMatchObject({ phase: "failed", error: "initialize refused" }); + expect(stops).toBe(1); + expect(sent.some((message) => message.type === "user")).toBe(false); + + rejectInitialize = false; + await c.send("keep this draft", [], undefined, "submission"); + expect(c.state.phase).toBe("ready"); + expect(sent.filter((message) => message.request?.subtype === "initialize")).toHaveLength(2); + expect(sent.filter((message) => message.type === "user")).toHaveLength(1); }); /** A tab going on with a session, its first program started and in the settings' mode. */ @@ -176,11 +219,15 @@ describe("the permission mode of a Claude tab's program started again", () => { hold = new Promise((resolve) => { settled = resolve; }); - await c.restart(); + const initialized = Promise.withResolvers(); + onInitialize = initialized.resolve; + const restarting = c.restart(); + await initialized.promise; const picked = c.setPermissionMode("acceptEdits"); hold = undefined; settled(); await picked; + await restarting; await settle(); expect(modesAsked()).toEqual(["acceptEdits"]); expect(c.state.model.permissionMode).toBe("acceptEdits"); diff --git a/tests/unit/renderer/services/chat/controller-open-to-read.test.ts b/tests/unit/renderer/services/chat/controller-open-to-read.test.ts index a3128052d..9a2ef8002 100644 --- a/tests/unit/renderer/services/chat/controller-open-to-read.test.ts +++ b/tests/unit/renderer/services/chat/controller-open-to-read.test.ts @@ -8,11 +8,17 @@ import { afterEach, describe, expect, mock, test } from "bun:test"; let releaseStart: () => void = () => {}; let started = false; +let replyToInitialize: ((requestId: string) => void) | undefined; +let onStartRequested: (() => void) | undefined; const realIpc = await import("../../../../../src/renderer/ipc/client"); mock.module("../../../../../src/renderer/ipc/client", () => ({ ...realIpc, - ipcCallResult: (_channel: string, method: string) => { + ipcCallResult: ( + _channel: string, + method: string, + args: { message?: { request_id?: string } }, + ) => { if (method === "replay") { return Promise.resolve({ ok: true, value: { found: false } }); } @@ -39,8 +45,12 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ started = true; resolve({ ok: true, value: { ok: true, version: "2.1.322", attached: false } }); }; + onStartRequested?.(); }); } + if (method === "send" && args.message?.request_id) { + replyToInitialize?.(args.message.request_id); + } return Promise.resolve({ ok: true, value: undefined }); }, })); @@ -55,6 +65,8 @@ afterEach(() => { releaseStart(); for (const c of live.splice(0)) c.dispose(); started = false; + replyToInitialize = undefined; + onStartRequested = undefined; }); describe("opening a Claude tab to read it", () => { @@ -66,12 +78,24 @@ describe("opening a Claude tab to read it", () => { sessionId: "s-read", }); live.push(c); + replyToInitialize = (requestId) => + c.receive({ + dir: "out", + seq: 1, + message: { + type: "control_response", + response: { subtype: "success", request_id: requestId, response: {} }, + }, + } as never); + const requested = Promise.withResolvers(); + onStartRequested = requested.resolve; const opening = c.open(); await c.openToRead(); expect(started).toBe(false); const state = useChatStore.getState().tabs[chatKey("ws-read", "t-read")]; expect(state?.history?.items.some((item) => item.kind === "user")).toBe(true); expect(state?.phase).toBe("starting"); + await requested.promise; releaseStart(); await opening; expect(started).toBe(true); From 2d58d73628846f9a0592c6482279c7591b16ca82 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:11:08 +0900 Subject: [PATCH 063/208] fix(chat): preserve Codex threads when resume fails Co-Authored-By: Claude Opus 5.5 --- .../services/chat/codex-controller.ts | 27 +++++++-- src/renderer/services/chat/codex-model.ts | 9 +-- src/shared/i18n/locales/en/common.json | 2 +- src/shared/i18n/locales/ko/common.json | 2 +- .../chat/codex-before-handshake.test.ts | 58 +++++++++++++++++++ 5 files changed, 87 insertions(+), 11 deletions(-) diff --git a/src/renderer/services/chat/codex-controller.ts b/src/renderer/services/chat/codex-controller.ts index b0ceab09d..f5a0cfd74 100644 --- a/src/renderer/services/chat/codex-controller.ts +++ b/src/renderer/services/chat/codex-controller.ts @@ -240,6 +240,8 @@ export class CodexController { private stoppingTurn?: string; private deferToolSendsForTurn?: string; private resumingSelection = false; + /** A thread started here that has yet to see any turn. */ + private emptyThread?: string; private canonicalCwd: string | undefined; private agentRefresh: ReturnType | undefined; private readonly readingAgents = new Map>(); @@ -511,20 +513,33 @@ export class CodexController { excludeTurns: this.model.items.length > 0, }); } catch (err) { - const message = (err as Error).message; - log.warn(`thread ${threadId} not resumed: ${message}`); - if (this.resumingSelection) throw err; + if (!this.canReplaceEmptyThread(threadId, err)) throw err; + log.info(`starting again after Codex discarded empty thread ${threadId}`); } if (resumed) { requireThreadId(resumed, threadId); + this.emptyThread = undefined; this.readGoal(threadId); return true; } } - requireThreadId(await this.request("thread/start", threadStartParams(this.target, this.next))); + this.emptyThread = requireThreadId( + await this.request("thread/start", threadStartParams(this.target, this.next)), + ); return true; } + /** A missing rollout is safe to replace only when this tab knows the thread was empty. */ + private canReplaceEmptyThread(threadId: string, error: unknown): boolean { + return ( + !this.resumingSelection && + this.emptyThread === threadId && + !this.model.items.some((item) => item.kind !== "notice") && + error instanceof CodexReplyError && + error.message === `no rollout found for thread id ${threadId}` + ); + } + private async forkThread( fork: CodexFork, settings?: ReturnType, @@ -1324,7 +1339,7 @@ export class CodexController { const collaboration = this.collaborationChange; if (this.rewinding || this.resumingSelection) throw new Error("Codex is changing the conversation"); - if (!(await this.ensureRunning())) throw new Error("Codex is not running"); + if (!(await this.ensureRunning())) throw new Error(this.state.error ?? "Codex is not running"); if (!(await this.ready)) throw new Error(this.state.error ?? "Codex has no thread to send to"); // A message sent while a mode change is pending must use the newly // acknowledged mode. A failed switch must leave the draft unsent. @@ -1358,6 +1373,7 @@ export class CodexController { } const threadId = this.model.threadId; if (!threadId) throw new Error("Codex has no thread to send to"); + this.emptyThread = undefined; const said = from && text ? relayedText(from, text) : text; const input = [ ...(said ? [{ type: "text", text: said, text_elements: [] }] : []), @@ -2009,6 +2025,7 @@ export class CodexController { const before = this.model; const model = applyCodexLines(before, lines); if (model === before) return; + if (model.running || model.lastResult) this.emptyThread = undefined; this.update((prev) => ({ ...prev, model, phase: phaseAfter(prev.phase, model) })); if (model.threadId && model.threadId !== this.target.threadId) { this.target = { ...this.target, threadId: model.threadId, fork: undefined }; diff --git a/src/renderer/services/chat/codex-model.ts b/src/renderer/services/chat/codex-model.ts index 972de6206..af14c9bd5 100644 --- a/src/renderer/services/chat/codex-model.ts +++ b/src/renderer/services/chat/codex-model.ts @@ -383,9 +383,7 @@ function applyResponse( return; } if (sent.subtype === "thread/resume") { - // The app starts a new thread instead, and says so where the tab had a - // conversation to go on with. One that never had a turn was never - // saved by Codex, so it cannot be resumed and nothing is lost. + // The tab keeps its conversation when resuming it fails. if (!m.items.some((i) => i.kind !== "notice")) return; // The server's reason is for the log and the notice's tooltip. draft.push({ @@ -415,10 +413,13 @@ function applyResponse( m.appServerVersion = str(result.userAgent)?.match(/^[^/]+\/([\d.]+)\b/)?.[1]; return; case "thread/start": - case "thread/resume": + case "thread/resume": { if (sent.request.ephemeral === true) return; + const intended = sent.subtype === "thread/resume" ? str(sent.request.threadId) : undefined; + if (intended && str(rec(result.thread)?.id) !== intended) return; applyThread(draft, result, seq); return; + } case "thread/list": if ( typeof sent.request.parentThreadId === "string" && diff --git a/src/shared/i18n/locales/en/common.json b/src/shared/i18n/locales/en/common.json index f7652abc5..32abc72a0 100644 --- a/src/shared/i18n/locales/en/common.json +++ b/src/shared/i18n/locales/en/common.json @@ -883,7 +883,7 @@ "exited_codex": "Codex exited", "restarted_codex": "Codex started again", "not_resumed": "Couldn't go on with the earlier conversation; started a new one", - "not_resumed_codex": "Couldn't go on with the earlier Codex conversation; started a new one", + "not_resumed_codex": "Couldn't resume the earlier Codex conversation", "review": "Code review", "goal_set": "Goal set", "goal_cleared": "Goal cleared", diff --git a/src/shared/i18n/locales/ko/common.json b/src/shared/i18n/locales/ko/common.json index 82c3e3448..ef84d81c4 100644 --- a/src/shared/i18n/locales/ko/common.json +++ b/src/shared/i18n/locales/ko/common.json @@ -883,7 +883,7 @@ "exited_codex": "Codex가 종료됨", "restarted_codex": "Codex가 다시 시작됨", "not_resumed": "이전 대화를 이어갈 수 없어 새 대화로 시작함", - "not_resumed_codex": "이전 Codex 대화를 이어갈 수 없어 새 대화로 시작함", + "not_resumed_codex": "이전 Codex 대화를 다시 열지 못함", "review": "코드 리뷰", "goal_set": "목표 설정", "goal_cleared": "목표 지움", diff --git a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts index c070b06f2..3bd3f951d 100644 --- a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts +++ b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts @@ -131,6 +131,19 @@ function tab(respond?: (message: Message) => unknown | Promise): Contro const order = () => sent.map((m) => m.method); +/** Streams a scripted app-server's lines with no real startup delay. */ +function scriptProgram(c: Controller, reply: (message: Message) => Message): void { + const line = (dir: "sys" | "in" | "out", message: Message) => + c.receive({ seq: ++lineSeq, dir, message } as never); + onStart = () => line("sys", { event: "start" }); + onStop = () => line("sys", { event: "exit", code: 0 }); + codex = (message) => { + sent.push(message); + line("in", message); + if (message.id !== undefined) line("out", { id: message.id, ...reply(message) }); + }; +} + test("closing a Codex tab during replay cannot open a new program once replay ends", async () => { const c = tab(); const replay = Promise.withResolvers(); @@ -202,6 +215,51 @@ test("Codex stays unready until resume returns the requested thread", async () = expect(c.state.error).toBe("Codex did not return the requested thread"); }); +test("a failed restored Codex resume keeps the thread and waits for an explicit retry", async () => { + const c = tab(); + let canResume = false; + scriptProgram(c, (message) => { + if (message.method === "thread/resume") { + return canResume + ? { result: { thread: { id: "t1" } } } + : { error: { code: -32600, message: "no rollout found for thread id t1" } }; + } + if (message.method === "thread/start") return { result: { thread: { id: "wrong" } } }; + if (message.method === "turn/start") return { result: { turn: { id: "sent" } } }; + return { result: {} }; + }); + await expect(c.send("preserve this prompt")).rejects.toThrow(); + expect(c.currentThread()).toBe("t1"); + expect(c.state.phase).toBe("failed"); + expect(order()).not.toContain("thread/start"); + expect(order()).not.toContain("turn/start"); + + canResume = true; + await c.send("preserve this prompt"); + expect(sent.find((message) => message.method === "turn/start")?.params).toMatchObject({ + threadId: "t1", + input: [{ type: "text", text: "preserve this prompt" }], + }); +}); + +test("a known empty Codex thread can be replaced when it has no rollout", async () => { + const c = new CodexController({ workspaceId: "ws-codex-handshake", tabId: "empty", cwd: "/p" }); + live.push(c); + let count = 0; + scriptProgram(c, (message) => { + if (message.method === "thread/start") + return { result: { thread: { id: `empty-${++count}` } } }; + if (message.method === "thread/resume") + return { error: { code: -32600, message: "no rollout found for thread id empty-1" } }; + return { result: {} }; + }); + await c.prepareSend(); + expect(c.currentThread()).toBe("empty-1"); + await c.restart(); + expect(c.state.phase).toBe("ready"); + expect(c.currentThread()).toBe("empty-2"); +}); + test("resumes a Codex thread after agent replacement and queues against the new log", async () => { jest.useFakeTimers(); const c = tab(); From c3f8c6d6af694293f2bd338bf8294b3485b83302 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:03:26 +0900 Subject: [PATCH 064/208] fix(workspace): restore connection status in newly opened windows Co-Authored-By: Claude Opus 5.5 --- src/main/features/workspace/ipc.ts | 1 + src/main/features/workspace/manager.ts | 9 ++++ src/renderer/bootstrap.ts | 13 ++++- src/renderer/state/stores/workspaces.ts | 26 +++++++--- src/shared/ipc/contract.ts | 1 + src/shared/types/workspace.ts | 1 + .../operations/workspace-selection.test.ts | 6 ++- .../workspace-status-reopen.test.ts | 51 +++++++++++++++++++ 8 files changed, 96 insertions(+), 12 deletions(-) create mode 100644 tests/unit/renderer/state/operations/workspace-status-reopen.test.ts diff --git a/src/main/features/workspace/ipc.ts b/src/main/features/workspace/ipc.ts index aeac0d607..0dfeabcb5 100644 --- a/src/main/features/workspace/ipc.ts +++ b/src/main/features/workspace/ipc.ts @@ -49,6 +49,7 @@ export function registerWorkspaceChannel( list: (_args: unknown) => { return manager.list(); }, + connectionSnapshot: () => ipcOk(manager.connectionSnapshot()), active: (_args: unknown) => { return manager.getActiveId(); }, diff --git a/src/main/features/workspace/manager.ts b/src/main/features/workspace/manager.ts index 7d9766184..992654fc4 100644 --- a/src/main/features/workspace/manager.ts +++ b/src/main/features/workspace/manager.ts @@ -6,6 +6,7 @@ import { AgentManifestSchema } from "../../../shared/agent/manifest"; import { createLogger } from "../../../shared/log/main"; import { rootPathFromLocation, + type WorkspaceConnectionChangedEvent, type WorkspaceConnectionEventStatus, type WorkspaceLocation, WorkspaceLocationSchema, @@ -534,6 +535,14 @@ export class WorkspaceManager { return null; } + /** Current remote connection statuses for a newly opened renderer. */ + connectionSnapshot(): WorkspaceConnectionChangedEvent[] { + return Array.from(this.connectionStatuses, ([workspaceId, status]) => ({ + workspaceId, + status, + })); + } + getActiveId(): string | null { return this.activeId; } diff --git a/src/renderer/bootstrap.ts b/src/renderer/bootstrap.ts index 76e2c21c1..95a14b951 100644 --- a/src/renderer/bootstrap.ts +++ b/src/renderer/bootstrap.ts @@ -300,8 +300,17 @@ async function bootstrapAppState(): Promise { * that wait for a user to connect. */ export async function bootstrapWorkspaces(): Promise { - const list = mustSucceed(await ipcCallResult("workspace", "list", undefined)); - useWorkspacesStore.getState().setAll(list); + // Bootstrap is an initialization path — no recovery possible if workspace list is unavailable. + const [workspaces, connections] = await Promise.all([ + ipcCallResult("workspace", "list", undefined), + ipcCallResult("workspace", "connectionSnapshot", undefined).catch((error: unknown) => { + log.warn(`Workspace connection snapshot failed: ${String(error)}`); + }), + ]); + if (connections && !connections.ok) + log.warn(`Workspace connection snapshot failed: ${connections.message}`); + const list = mustSucceed(workspaces); + useWorkspacesStore.getState().setAll(list, connections?.ok ? connections.value : undefined); const active = await ipcCallResult("workspace", "active", undefined); // The sidebar can already be used while the active-ID reply is pending. diff --git a/src/renderer/state/stores/workspaces.ts b/src/renderer/state/stores/workspaces.ts index 9d131e088..3b367dabf 100644 --- a/src/renderer/state/stores/workspaces.ts +++ b/src/renderer/state/stores/workspaces.ts @@ -1,6 +1,7 @@ import { create } from "zustand"; import { isDrivePath, toSlashPath } from "../../../shared/fs/drive-path"; import type { + WorkspaceConnectionChangedEvent, WorkspaceConnectionEventStatus, WorkspaceConnectionProgressEvent, WorkspaceMeta, @@ -36,7 +37,7 @@ export interface WorkspacesState { connectionStatusByWorkspaceId: Record; /** Last bootstrap progress event per workspace ID. Cleared to undefined on connection complete/error. */ connectionProgressByWorkspaceId: Record; - setAll: (workspaces: WorkspaceMeta[]) => void; + setAll: (workspaces: WorkspaceMeta[], snapshot?: WorkspaceConnectionChangedEvent[]) => void; upsert: (meta: WorkspaceMeta) => void; remove: (id: string) => void; setConnectionStatus: (id: string, status: WorkspaceConnectionStatus) => void; @@ -360,15 +361,24 @@ export function createWorkspacesStore(deps: WorkspacesStoreDeps = defaultWorkspa connectionStatusByWorkspaceId: {}, connectionProgressByWorkspaceId: {}, - setAll(incoming) { + setAll(incoming, snapshot = []) { const workspaces = incoming.map(withSlashRoot); - set((state) => ({ - workspaces, - connectionStatusByWorkspaceId: pruneConnectionStatuses( - state.connectionStatusByWorkspaceId, + set((state) => { + const statuses = Object.fromEntries( + snapshot.map(({ workspaceId, status }) => [ + workspaceId, + statusFromConnectionEvent(status), + ]), + ); + return { workspaces, - ), - })); + // Live events can arrive while bootstrap waits for its snapshot. + connectionStatusByWorkspaceId: pruneConnectionStatuses( + { ...statuses, ...state.connectionStatusByWorkspaceId }, + workspaces, + ), + }; + }); }, upsert(incoming) { diff --git a/src/shared/ipc/contract.ts b/src/shared/ipc/contract.ts index 138c58dbd..ed4dfe9b3 100644 --- a/src/shared/ipc/contract.ts +++ b/src/shared/ipc/contract.ts @@ -594,6 +594,7 @@ export const ipcContract = { workspace: { call: { list: call(z.void(), z.array(WorkspaceMetaSchema)), + connectionSnapshot: call(z.void(), z.array(WorkspaceConnectionChangedEventSchema)), create: call(WorkspaceCreateArgsSchema, WorkspaceMetaSchema), /** * Atomic workspace creation: for SSH locations, authenticates and diff --git a/src/shared/types/workspace.ts b/src/shared/types/workspace.ts index fae7daa6b..194338c0e 100644 --- a/src/shared/types/workspace.ts +++ b/src/shared/types/workspace.ts @@ -97,6 +97,7 @@ export const WorkspaceConnectionChangedEventSchema = z.object({ workspaceId: WorkspaceIdSchema, status: WorkspaceConnectionEventStatusSchema, }); +export type WorkspaceConnectionChangedEvent = z.infer; export type WorkspaceConnectionEventStatus = z.infer; diff --git a/tests/unit/renderer/state/operations/workspace-selection.test.ts b/tests/unit/renderer/state/operations/workspace-selection.test.ts index a6f2bdb72..91c450764 100644 --- a/tests/unit/renderer/state/operations/workspace-selection.test.ts +++ b/tests/unit/renderer/state/operations/workspace-selection.test.ts @@ -75,13 +75,15 @@ test("startup restores the remembered workspace away from the first row without const calls: string[] = []; setWorkspaceIpc(async (method) => { calls.push(method); - return method === "list" ? [local, ssh] : ssh.id; + if (method === "list") return [local, ssh]; + if (method === "connectionSnapshot") return []; + return ssh.id; }); await bootstrapWorkspaces(); expect(useActiveStore.getState().activeWorkspaceId).toBe(ssh.id); - expect(calls).toEqual(["list", "active"]); + expect(calls).toEqual(["list", "connectionSnapshot", "active"]); }); test("a workspace selected while startup waits for the last active ID stays selected", async () => { diff --git a/tests/unit/renderer/state/operations/workspace-status-reopen.test.ts b/tests/unit/renderer/state/operations/workspace-status-reopen.test.ts new file mode 100644 index 000000000..52ebb6e08 --- /dev/null +++ b/tests/unit/renderer/state/operations/workspace-status-reopen.test.ts @@ -0,0 +1,51 @@ +import { expect, test } from "bun:test"; +import { bootstrapWorkspaces } from "../../../../../src/renderer/bootstrap"; +import { + selectIsWorkspaceOnline, + useWorkspacesStore, +} from "../../../../../src/renderer/state/stores/workspaces"; +import type { WorkspaceMeta } from "../../../../../src/shared/types/workspace"; + +test("a reopened window restores connected SSH workspaces and keeps status events received during startup", async () => { + const stableId = crypto.randomUUID(); + const changedId = crypto.randomUUID(); + const workspaces: WorkspaceMeta[] = [stableId, changedId].map((id) => ({ + id, + name: id, + location: { kind: "ssh", host: "example.invalid", remotePath: "/repo" }, + rootPath: "/repo", + colorTone: "default", + pinned: false, + sortOrder: 0, + pinnedSortOrder: 0, + tabs: [], + })); + const originalWindow = globalThis.window; + const originalStore = useWorkspacesStore.getState(); + useWorkspacesStore.setState({ workspaces: [], connectionStatusByWorkspaceId: {} }); + Object.assign(globalThis, { + window: { + ipc: { + call: async (_channel: string, method: string) => { + if (method === "list") return workspaces; + if (method === "active") return stableId; + if (method === "connectionSnapshot") { + useWorkspacesStore.getState().setConnectionStatus(changedId, "held-then-expired"); + return workspaces.map(({ id }) => ({ workspaceId: id, status: "connected" })); + } + throw new Error(`Unexpected request: ${method}`); + }, + }, + }, + }); + try { + await bootstrapWorkspaces(); + const state = useWorkspacesStore.getState(); + expect(selectIsWorkspaceOnline(state, stableId)).toBe(true); + expect(selectIsWorkspaceOnline(state, changedId)).toBe(false); + expect(state.connectionStatusByWorkspaceId[changedId]).toBe("held-then-expired"); + } finally { + useWorkspacesStore.setState(originalStore); + Object.assign(globalThis, { window: originalWindow }); + } +}); From 0e180c98345966f00daa1f221a93840903d6d658 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:16:56 +0900 Subject: [PATCH 065/208] fix(chat): commit profile changes after the destination starts Co-Authored-By: Claude Opus 5.5 --- .../services/chat/codex-controller.ts | 246 +++++++++------- src/renderer/services/chat/controller.ts | 268 +++++++++++------- .../chat/codex-before-handshake.test.ts | 19 ++ .../services/chat/controller-card.test.ts | 32 ++- .../chat/controller-switch-profile.test.ts | 99 +++++-- 5 files changed, 444 insertions(+), 220 deletions(-) diff --git a/src/renderer/services/chat/codex-controller.ts b/src/renderer/services/chat/codex-controller.ts index f5a0cfd74..c0b2878a8 100644 --- a/src/renderer/services/chat/codex-controller.ts +++ b/src/renderer/services/chat/codex-controller.ts @@ -400,6 +400,7 @@ export class CodexController { this.canonicalCwd = result.canonicalCwd; this.update((prev) => ({ ...prev, version: result.version })); if (result.attached) { + if (options.resetLog) return this.rejectStartup("Codex attached to the previous program"); // A program this controller started a moment ago, whose start line has // not come yet: its handshake still decides. this.ready = this.handshaking ?? Promise.resolve(this.model.threadId !== undefined); @@ -418,11 +419,15 @@ export class CodexController { ); const handshake = (catalogOnly ? introduced : this.handshake(introduced, forkSettings)) .then( - async () => { + async (threadId) => { if (this.disposed) return false; this.flushNow(); if (this.model.process === "exited") return this.rejectStartup("Codex exited during startup"); + if (typeof threadId === "string" && this.model.threadId !== threadId) { + this.patchModel({ threadId }); + this.rememberThread(threadId); + } this.startup.failed = false; this.update((prev) => ({ ...prev, phase: "ready" })); if (!catalogOnly) this.showPicks(); @@ -466,7 +471,7 @@ export class CodexController { private async handshake( introduced: Promise, forkSettings?: ReturnType, - ): Promise { + ): Promise { await introduced; void this.request("account/read", {}).catch(() => {}); void this.request("model/list", {}).catch(() => {}); @@ -489,14 +494,14 @@ export class CodexController { // profile keeps the name it had there, which Codex does not copy. this.titled = true; if (fork.title) { - this.hooks.onTitle?.(fork.title); + if (!this.resumingSelection) this.hooks.onTitle?.(fork.title); if (staged && copy) { void this.request("thread/name/set", { threadId: copy, name: fork.title }).catch( () => {}, ); } } - return true; + return copy; } catch (err) { const message = (err as Error).message; log.warn(`thread ${fork.threadId} not forked: ${message}`); @@ -520,13 +525,13 @@ export class CodexController { requireThreadId(resumed, threadId); this.emptyThread = undefined; this.readGoal(threadId); - return true; + return threadId; } } this.emptyThread = requireThreadId( await this.request("thread/start", threadStartParams(this.target, this.next)), ); - return true; + return this.emptyThread; } /** A missing rollout is safe to replace only when this tab knows the thread was empty. */ @@ -838,19 +843,11 @@ export class CodexController { */ async resumeThread(threadId: string, title: string, profileId = this.profileId): Promise { this.requireHistoryIdle(); - this.resumingSelection = true; - try { - const { workspaceId, tabId } = this.target; - if (this.model.process === "running") { - unwrapIpcResult(await ipcCallResult("chat", "stop", { workspaceId, tabId })); - } - this.flushNow(); + await this.changeThread(async () => { const switching = !sameProfile(profileId, this.target.profileId); if (switching) { this.next = {}; this.pickedPermissionMode = undefined; - this.hooks.onProfile?.(profileId); - this.hooks.onChosen?.({}); } this.target = { ...this.target, @@ -859,11 +856,7 @@ export class CodexController { moves: undefined, profileId: isDefaultProfileId(profileId) ? undefined : profileId, }; - this.hooks.onThread?.(threadId); - this.hooks.onMoves?.([]); - this.hooks.onTitle?.(title); this.titled = true; - // A command's card told of the thread the tab had. this.update((prev) => ({ ...prev, history: null, @@ -873,13 +866,17 @@ export class CodexController { ? { ...emptyCodexModel(), lastSeq: this.model.lastSeq } : nextThreadModel(this.model), })); - if (!(await this.start({ resetLog: true })) || !(await this.ready)) { + if (!(await this.start({ resetLog: true }))) { throw new Error(this.state.error ?? "Codex could not resume this thread"); } - this.flushNow(); - } finally { - this.resumingSelection = false; - } + if (switching) { + this.hooks.onProfile?.(profileId); + this.hooks.onChosen?.({}); + } + this.hooks.onThread?.(threadId); + this.hooks.onMoves?.([]); + this.hooks.onTitle?.(this.model.threadName ?? title); + }); } /** @@ -929,32 +926,89 @@ export class CodexController { if (this.rewinding || this.resumingSelection) throw new Error("Codex is changing the conversation"); if (sameProfile(profileId, this.target.profileId)) return; - const { workspaceId, tabId } = this.target; - if (this.model.process === "running") { - await ipcCallResult("chat", "stop", { workspaceId, tabId }); + await this.changeThread(async () => { + this.next = {}; + this.pickedPermissionMode = undefined; + this.target = { + ...this.target, + threadId: undefined, + fork: undefined, + profileId: isDefaultProfileId(profileId) ? undefined : profileId, + moves: undefined, + }; + this.titled = false; + this.update((prev) => ({ + ...prev, + history: null, + queue: [], + card: undefined, + model: { ...emptyCodexModel(), lastSeq: this.model.lastSeq }, + })); + if (!(await this.start({ resetLog: true }))) { + throw new Error(this.state.error ?? "Codex could not switch profiles"); + } + this.hooks.onProfile?.(profileId); + const threadId = this.currentThread(); + if (threadId) this.hooks.onThread?.(threadId); + this.hooks.onTitle?.(this.model.threadName ?? ""); + }); + } + + /** Holds sends while the source stops and restores it if the destination fails. */ + private async changeThread(change: () => Promise): Promise { + if ( + this.disposed || + this.rewinding || + this.resumingSelection || + this.startup.pending || + this.startingTurn || + this.state.queue.some((item) => item.status === "sending") + ) { + throw new Error("Codex is changing the conversation"); + } + this.resumingSelection = true; + try { + this.flushNow(); + if (this.model.process === "running") { + await stopChatProgram(this.target.workspaceId, this.target.tabId); + } + this.flushNow(); + if (this.disposed) throw new Error("the tab closed"); + const source = this.state; + const sourceModel = this.model; + const target = this.target; + const next = this.next; + const permissionMode = this.pickedPermissionMode; + const titled = this.titled; + const emptyThread = this.emptyThread; + try { + await change(); + } catch (error) { + this.target = target; + this.next = next; + this.pickedPermissionMode = permissionMode; + this.titled = titled; + this.emptyThread = emptyThread; + this.startup.failed = true; + this.update((prev) => ({ + ...source, + phase: "failed", + error: (error as Error).message, + model: { + ...sourceModel, + lastSeq: Math.max(sourceModel.lastSeq, prev.model.lastSeq), + process: "exited", + running: false, + turn: null, + turnId: undefined, + permissions: [], + } satisfies CodexModel, + })); + throw error; + } + } finally { + this.resumingSelection = false; } - this.flushNow(); - this.next = {}; - this.pickedPermissionMode = undefined; - this.target = { - ...this.target, - threadId: undefined, - fork: undefined, - profileId: isDefaultProfileId(profileId) ? undefined : profileId, - moves: undefined, - }; - this.hooks.onProfile?.(profileId); - this.hooks.onTitle?.(""); - this.titled = false; - // The account and its limits are the old profile's too. - this.update((prev) => ({ - ...prev, - history: null, - queue: [], - card: undefined, - model: { ...emptyCodexModel(), lastSeq: this.model.lastSeq }, - })); - await this.start({ resetLog: true }); } /** @@ -979,7 +1033,7 @@ export class CodexController { await this.switchProfile(profileId); return; } - const { workspaceId, tabId, cwd } = this.target; + const { workspaceId, cwd } = this.target; const sourceProfile = this.profileId; const forkSettings = await CodexController.destinationForkSettings( { workspaceId, cwd, profileId }, @@ -992,45 +1046,42 @@ export class CodexController { if (sourceProfile !== this.profileId || threadId !== this.currentThread()) { throw new Error("The Codex source thread changed while resolving the destination profile"); } - // Messages held for the turn's end would go to the program that stops. - this.update((prev) => (prev.queue.length > 0 ? { ...prev, queue: [] } : prev)); - if (this.model.process === "running") { - await ipcCallResult("chat", "stop", { workspaceId, tabId }); - } - this.flushNow(); - // Codex numbers a thread's items anew as it reads it; its turns keep their ids. - const after = lastMessageId(this.model.items.filter((item) => item.kind === "assistant")); - const moves = after - ? withMove(this.target.moves, { profileId, after, at: Date.now() }) - : [...(this.target.moves ?? [])]; - this.next = {}; - this.pickedPermissionMode = undefined; - const title = this.model.threadName; - this.target = { - ...this.target, - threadId: undefined, - fork: { - threadId, - ...(title ? { title } : {}), - profileId: this.target.profileId ?? defaultProfileId("codex"), - }, - profileId: isDefaultProfileId(profileId) ? undefined : profileId, - moves, - }; - this.hooks.onProfile?.(profileId); - this.hooks.onMoves?.(moves); - // The fork's answer brings the turns back; the account and its limits - // are the old profile's. - this.update((prev) => ({ - ...prev, - history: null, - card: undefined, - model: { ...emptyCodexModel(), lastSeq: this.model.lastSeq }, - })); - if (!(await this.start({ resetLog: true }, false, forkSettings)) || !(await this.ready)) { - throw new Error(this.state.error ?? "Codex could not continue in the destination profile"); - } - this.flushNow(); + await this.changeThread(async () => { + // Codex numbers a thread's items anew as it reads it; its turns keep their ids. + const after = lastMessageId(this.model.items.filter((item) => item.kind === "assistant")); + const moves = after + ? withMove(this.target.moves, { profileId, after, at: Date.now() }) + : [...(this.target.moves ?? [])]; + this.next = {}; + this.pickedPermissionMode = undefined; + const title = this.model.threadName; + this.target = { + ...this.target, + threadId: undefined, + fork: { + threadId, + ...(title ? { title } : {}), + profileId: this.target.profileId ?? defaultProfileId("codex"), + }, + profileId: isDefaultProfileId(profileId) ? undefined : profileId, + moves, + }; + this.update((prev) => ({ + ...prev, + history: null, + queue: [], + card: undefined, + model: { ...emptyCodexModel(), lastSeq: this.model.lastSeq }, + })); + if (!(await this.start({ resetLog: true }, false, forkSettings))) { + throw new Error(this.state.error ?? "Codex could not continue in the destination profile"); + } + this.hooks.onProfile?.(profileId); + const copy = this.currentThread(); + if (copy) this.hooks.onThread?.(copy); + if (title) this.hooks.onTitle?.(title); + this.hooks.onMoves?.(moves); + }); } /** Asks the program for a command (/mcp, /goal, /compact…), once it is running. */ @@ -1190,6 +1241,13 @@ export class CodexController { return this.model.threadId ?? this.target.threadId; } + /** Persists the program's thread after the current selection commits. */ + private rememberThread(threadId: string): void { + if (threadId === this.target.threadId) return; + this.target = { ...this.target, threadId, fork: undefined }; + if (!this.resumingSelection) this.hooks.onThread?.(threadId); + } + /** Reads again what the program is signed in with: after a sign-in in a terminal. */ async refreshAccount(): Promise { if (!(await this.ensureRunning())) return; @@ -1529,6 +1587,7 @@ export class CodexController { } private sendNextQueued(): void { + if (this.resumingSelection) return; dispatchQueuedMessage( this.state.queue, (update) => this.update(update), @@ -1802,7 +1861,7 @@ export class CodexController { * opens (its list of threads, its defaults) would come before that. */ private async ensureRunning(): Promise { - if (this.disposed) return false; + if (this.disposed || this.resumingSelection) return false; if (this.opening) { await this.opening; if (this.state.phase === "failed") return false; @@ -2027,10 +2086,7 @@ export class CodexController { if (model === before) return; if (model.running || model.lastResult) this.emptyThread = undefined; this.update((prev) => ({ ...prev, model, phase: phaseAfter(prev.phase, model) })); - if (model.threadId && model.threadId !== this.target.threadId) { - this.target = { ...this.target, threadId: model.threadId, fork: undefined }; - this.hooks.onThread?.(model.threadId); - } + if (model.threadId) this.rememberThread(model.threadId); if (model.threadId && model.threadId !== before.threadId) { this.dirtyAgents.clear(); this.readAgentAt.clear(); @@ -2041,7 +2097,7 @@ export class CodexController { // The thread's name, when it gets one or another (/rename), is the tab's. if (model.threadName && model.threadName !== before.threadName) { this.titled = true; - this.hooks.onTitle?.(model.threadName); + if (!this.resumingSelection) this.hooks.onTitle?.(model.threadName); } if ( model.items !== before.items && diff --git a/src/renderer/services/chat/controller.ts b/src/renderer/services/chat/controller.ts index b79ca286a..6b7aa3276 100644 --- a/src/renderer/services/chat/controller.ts +++ b/src/renderer/services/chat/controller.ts @@ -245,6 +245,7 @@ export class ChatController { /** How many times the user picked a mode, which a program starting then takes over its last one's. */ private modePicks = 0; /** A started program's initialize, and the flags given again after it. */ + private changingSession = false; private initializing: Promise = Promise.resolve(); private readonly startup = new ProgramStartup(() => stopChatProgram(this.target.workspaceId, this.target.tabId), @@ -592,6 +593,9 @@ export class ChatController { return this.rejectStartup("old-version"); } this.update((prev) => ({ ...prev, version: result.version })); + if (resume.resetLog && result.attached) { + return this.rejectStartup("Claude attached to the previous program"); + } if (!result.attached) { // Subagents' text comes as messages under their Agent call, for the agent strip. let remote = false; @@ -711,6 +715,7 @@ export class ChatController { /** Starts the program again, going on with the session. */ async restart(): Promise { + if (this.changingSession) throw new Error("Claude is changing the conversation"); const { workspaceId, tabId } = this.target; if (this.state.model.process === "running") { await ipcCallResult("chat", "stop", { workspaceId, tabId }); @@ -786,33 +791,29 @@ export class ChatController { */ async resumeSession(sessionId: string, profileId?: string): Promise { if (this.state.model.running) throw new Error("a turn is running"); - const { workspaceId, tabId } = this.target; - if (this.state.model.process === "running") { - await ipcCallResult("chat", "stop", { workspaceId, tabId }); - } - this.flushNow(); - const from = - profileId !== undefined && !sameProfile(profileId, this.target.profileId) - ? profileId - : undefined; - const fork: ForkPoint | undefined = from ? { sessionId, profileId: from } : undefined; - this.sessionId = fork ? undefined : sessionId; - this.target = { ...this.target, sessionId: this.sessionId, fork, moves: undefined }; - this.hooks.onTarget?.(fork ? { fork } : { sessionId }); - this.hooks.onMoves?.([]); - this.titled = false; - // The session gone on with has its own name. - this.pendingName = undefined; - this.named = false; - // A command's card told of the session the tab had. - this.update((prev) => ({ - ...prev, - history: null, - card: undefined, - model: { ...emptyModel(), lastSeq: prev.model.lastSeq }, - })); - await this.loadTranscript(sessionId, undefined, from); - if (await this.start({ ...this.startArgs(), resetLog: true })) await this.rebuild(); + await this.changeSession(async () => { + const from = + profileId !== undefined && !sameProfile(profileId, this.target.profileId) + ? profileId + : undefined; + const fork: ForkPoint | undefined = from ? { sessionId, profileId: from } : undefined; + this.sessionId = fork ? undefined : sessionId; + this.sessionName = undefined; + this.target = { ...this.target, sessionId: this.sessionId, fork, moves: undefined }; + this.titled = false; + this.pendingName = undefined; + this.named = false; + this.update((prev) => ({ + ...prev, + history: null, + card: undefined, + model: { ...emptyModel(), lastSeq: prev.model.lastSeq }, + })); + await this.loadTranscript(sessionId, undefined, from); + await this.startChangedSession(this.startArgs()); + this.publishSessionTarget(); + this.hooks.onMoves?.([]); + }); } /** @@ -822,31 +823,101 @@ export class ChatController { */ async switchProfile(profileId: string): Promise { if (sameProfile(profileId, this.target.profileId)) return; - const { workspaceId, tabId } = this.target; - if (this.state.model.process === "running") { - await ipcCallResult("chat", "stop", { workspaceId, tabId }); + await this.changeSession(async () => { + this.sessionId = undefined; + this.sessionName = undefined; + this.target = { + ...this.target, + sessionId: undefined, + fork: undefined, + profileId: isDefaultProfileId(profileId) ? undefined : profileId, + moves: undefined, + }; + this.titled = false; + this.update((prev) => ({ + ...prev, + history: null, + queue: [], + card: undefined, + model: { ...emptyModel(), lastSeq: prev.model.lastSeq }, + })); + await this.startChangedSession({}); + this.hooks.onProfile?.(profileId); + this.hooks.onTitle?.(this.sessionName ?? ""); + this.publishSessionTarget(); + }); + } + + /** Waits for a confirmed stop before changing the session and its profile. */ + private async changeSession(change: (shown: number) => Promise): Promise { + if ( + this.disposed || + this.changingSession || + this.startup.pending || + this.state.queue.some((item) => item.status === "sending") + ) { + throw new Error("Claude is changing the conversation"); } - this.flushNow(); - this.sessionId = undefined; - this.sessionName = undefined; - this.target = { - ...this.target, - sessionId: undefined, - fork: undefined, - profileId: isDefaultProfileId(profileId) ? undefined : profileId, - moves: undefined, - }; - this.hooks.onProfile?.(profileId); - this.hooks.onTitle?.(""); - this.titled = false; - this.update((prev) => ({ - ...prev, - history: null, - queue: [], - card: undefined, - model: { ...emptyModel(), lastSeq: prev.model.lastSeq }, - })); - if (await this.start({ resetLog: true })) await this.rebuild(); + this.changingSession = true; + try { + this.flushNow(); + const shown = this.state.model.items.length; + if (this.state.model.process === "running") { + await stopChatProgram(this.target.workspaceId, this.target.tabId); + } + this.flushNow(); + if (this.disposed) throw new Error("the tab closed"); + const source = this.state; + const target = this.target; + const sessionId = this.sessionId; + const sessionName = this.sessionName; + const titled = this.titled; + const pendingName = this.pendingName; + const named = this.named; + const lastMode = this.lastMode; + try { + await change(shown); + } catch (error) { + this.target = target; + this.sessionId = sessionId; + this.sessionName = sessionName; + this.titled = titled; + this.pendingName = pendingName; + this.named = named; + this.lastMode = lastMode; + this.startup.failed = true; + this.update((prev) => ({ + ...source, + phase: "failed", + error: (error as Error).message, + model: { + ...source.model, + lastSeq: Math.max(source.model.lastSeq, prev.model.lastSeq), + process: "exited", + running: false, + turn: null, + permissions: [], + }, + })); + throw error; + } + } finally { + this.changingSession = false; + } + } + + /** Starts the proposed session and reports failure before tab metadata is saved. */ + private async startChangedSession(args: StartArgs): Promise { + if (!(await this.start({ ...args, resetLog: true }))) { + throw new Error(this.state.error ?? "Claude could not start the requested session"); + } + } + + /** Persists the session the replacement actually established or is forking. */ + private publishSessionTarget(): void { + const fork = this.target.fork; + if (fork) this.hooks.onTarget?.({ fork }); + else if (this.sessionId) this.hooks.onTarget?.({ sessionId: this.sessionId }); } /** @@ -864,51 +935,44 @@ export class ChatController { await this.switchProfile(profileId); return; } - const { workspaceId, tabId } = this.target; - // Messages held for the turn's end would go to the program that stops. - this.update((prev) => (prev.queue.length > 0 ? { ...prev, queue: [] } : prev)); - this.flushNow(); - const shown = this.state.model.items.length; - if (this.state.model.process === "running") { - await ipcCallResult("chat", "stop", { workspaceId, tabId }); - } - this.flushNow(); - // The program stopped here told of its exit; the conversation goes on. - const model = this.state.model; - const items = model.items.filter( - (item, i) => i < shown || !(item.kind === "notice" && item.code === "exited"), - ); - const joined = joinHistory(this.state.history, { ...model, items }); - const all = { ...emptyModel(), items: joined.items, tools: joined.tools }; - // A copy that has no id of its own yet is copied from where it copies. - const fork: ForkPoint = - this.sessionId === undefined && pending - ? { ...pending, profileId: pending.profileId ?? this.profileId } - : { sessionId, profileId: this.profileId }; - const after = lastMessageId(all.items); - const moves = after - ? withMove(this.target.moves, { profileId, after, at: Date.now() }) - : [...(this.target.moves ?? [])]; - this.sessionId = undefined; - this.sessionName = undefined; - this.target = { - ...this.target, - sessionId: undefined, - fork, - profileId: isDefaultProfileId(profileId) ? undefined : profileId, - moves, - }; - this.hooks.onProfile?.(profileId); - this.hooks.onTarget?.({ fork }); - this.hooks.onMoves?.(moves); - // The conversation stays in sight; the new program's log starts empty. - this.update((prev) => ({ - ...prev, - history: all.items.length > 0 ? all : null, - card: undefined, - model: { ...emptyModel(), lastSeq: prev.model.lastSeq }, - })); - if (await this.start({ ...this.startArgs(), resetLog: true })) await this.rebuild(); + await this.changeSession(async (shown) => { + // The program stopped here told of its exit; the conversation goes on. + const model = this.state.model; + const items = model.items.filter( + (item, i) => i < shown || !(item.kind === "notice" && item.code === "exited"), + ); + const joined = joinHistory(this.state.history, { ...model, items }); + const all = { ...emptyModel(), items: joined.items, tools: joined.tools }; + // A copy that has no id of its own yet is copied from where it copies. + const fork: ForkPoint = + this.sessionId === undefined && pending + ? { ...pending, profileId: pending.profileId ?? this.profileId } + : { sessionId, profileId: this.profileId }; + const after = lastMessageId(all.items); + const moves = after + ? withMove(this.target.moves, { profileId, after, at: Date.now() }) + : [...(this.target.moves ?? [])]; + this.sessionId = undefined; + this.sessionName = undefined; + this.target = { + ...this.target, + sessionId: undefined, + fork, + profileId: isDefaultProfileId(profileId) ? undefined : profileId, + moves, + }; + this.update((prev) => ({ + ...prev, + history: all.items.length > 0 ? all : null, + queue: [], + card: undefined, + model: { ...emptyModel(), lastSeq: prev.model.lastSeq }, + })); + await this.startChangedSession(this.startArgs()); + this.hooks.onProfile?.(profileId); + this.publishSessionTarget(); + this.hooks.onMoves?.(moves); + }); } /** @@ -1098,6 +1162,7 @@ export class ChatController { // A program just started takes the tab's flags and pick first, so its // first turn runs with them. The chain settles on its own failures. await this.initializing; + if (this.changingSession) throw new Error("Claude is changing the conversation"); if (queued && !this.state.queue.some((entry) => entry.id === id && entry.status === "sending")) throw new Error("The conversation changed while delivering a queued message"); const first = !this.titled && text.trim() ? text.trim() : undefined; @@ -1183,6 +1248,7 @@ export class ChatController { } private sendNextQueued(): void { + if (this.changingSession) return; dispatchQueuedMessage( this.state.queue, (update) => this.update(update), @@ -1874,7 +1940,7 @@ export class ChatController { /** Starts the program again when it is not running, for a message to go to. */ private async ensureRunning(): Promise { - if (this.disposed) return false; + if (this.disposed || this.changingSession) return false; if (this.opening) { await this.opening; if (this.state.phase === "failed") return false; @@ -1927,7 +1993,7 @@ export class ChatController { if (title && title !== this.sessionName) { this.sessionName = title; this.titled = true; - this.hooks.onRename?.(title); + if (!this.changingSession) this.hooks.onRename?.(title); } } else if (message.type === "control_request") { const request = message.request as Record | undefined; @@ -1975,8 +2041,10 @@ export class ChatController { const name = this.pendingName ?? this.target.fork?.title ?? this.ownName; this.sessionId = model.sessionId; this.target = { ...this.target, fork: undefined }; - this.hooks.onSession?.(model.sessionId); - if (name) void this.renameSession(name).catch(() => {}); + if (!this.changingSession) { + this.hooks.onSession?.(model.sessionId); + if (name) void this.renameSession(name).catch(() => {}); + } } // What the tab showed before a /clear, a command's card too, is another session's. if ((model.clears ?? 0) !== (before.clears ?? 0)) { diff --git a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts index 3bd3f951d..1b1272e62 100644 --- a/tests/unit/renderer/services/chat/codex-before-handshake.test.ts +++ b/tests/unit/renderer/services/chat/codex-before-handshake.test.ts @@ -260,6 +260,25 @@ test("a known empty Codex thread can be replaced when it has no rollout", async expect(c.currentThread()).toBe("empty-2"); }); +test("a refused profile resume does not persist the destination thread or title", async () => { + const c = tab(); + const persisted: string[] = []; + c.setHooks({ + onProfile: (id) => persisted.push(id), + onThread: (id) => persisted.push(id), + onTitle: (title) => persisted.push(title), + }); + scriptProgram(c, (message) => + message.method === "thread/resume" + ? { error: { code: -32600, message: "resume refused" } } + : { result: {} }, + ); + await expect(c.resumeThread("dest", "Destination", "work")).rejects.toThrow("resume refused"); + expect(c.currentThread()).toBe("t1"); + expect(c.profileId).toBe("codex-default"); + expect(persisted).toEqual([]); +}); + test("resumes a Codex thread after agent replacement and queues against the new log", async () => { jest.useFakeTimers(); const c = tab(); diff --git a/tests/unit/renderer/services/chat/controller-card.test.ts b/tests/unit/renderer/services/chat/controller-card.test.ts index 777cb07db..a18ed3c5e 100644 --- a/tests/unit/renderer/services/chat/controller-card.test.ts +++ b/tests/unit/renderer/services/chat/controller-card.test.ts @@ -6,19 +6,40 @@ */ import { afterEach, describe, expect, mock, test } from "bun:test"; +(globalThis as { __APP_VERSION__?: string }).__APP_VERSION__ ??= "0.0.0"; + const realIpc = await import("../../../../../src/renderer/ipc/client"); mock.module("../../../../../src/renderer/ipc/client", () => ({ ...realIpc, // A Codex tab listens for its lines as it is made; none come here. ipcListen: () => () => {}, - ipcCallResult: (_channel: string, method: string) => { - // A start that does not come up: nothing past it runs here. + ipcCallResult: (_channel: string, method: string, args: Record) => { if (method === "start" || method === "codexStart") { return Promise.resolve({ ok: true, - value: { ok: false, reason: "failed", message: "not here" }, + value: { ok: true, pid: 1, attached: false, version: null }, }); } + if (method === "send") { + const message = args.message as Record; + const c = live.find((entry) => entry.key === `${args.workspaceId}:${args.tabId}`); + if (message.type === "control_request") { + c?.receive({ + seq: ++lineSeq, + dir: "out", + message: { + type: "control_response", + response: { subtype: "success", request_id: message.request_id, response: {} }, + }, + } as never); + } else if (message.id !== undefined) { + c?.receive({ + seq: ++lineSeq, + dir: "out", + message: { id: message.id, result: { thread: { id: "other" } } }, + } as never); + } + } if (method === "transcript") return Promise.resolve({ ok: true, value: { found: false } }); return Promise.resolve({ ok: true, value: undefined }); }, @@ -30,7 +51,8 @@ const { CodexController } = await import( ); let seq = 0; -const live: { dispose: () => void }[] = []; +let lineSeq = 0; +const live: (InstanceType | InstanceType)[] = []; afterEach(() => { for (const c of live.splice(0)) c.dispose(); @@ -56,7 +78,7 @@ describe("a Codex tab's card", () => { test("closes as another thread goes on in the tab", async () => { const c = codex(); - await expect(c.resumeThread("other", "Other")).rejects.toThrow("not here"); + await c.resumeThread("other", "Other"); expect(c.state.card).toBeUndefined(); }); }); diff --git a/tests/unit/renderer/services/chat/controller-switch-profile.test.ts b/tests/unit/renderer/services/chat/controller-switch-profile.test.ts index 7e8f50f50..b763abc28 100644 --- a/tests/unit/renderer/services/chat/controller-switch-profile.test.ts +++ b/tests/unit/renderer/services/chat/controller-switch-profile.test.ts @@ -7,11 +7,11 @@ * keep its other exports. */ import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"; - import { type ContinuedCodexChoices, profileForkSettings, } from "../../../../../src/renderer/services/chat/codex-profile-fork"; +import { ipcErr } from "../../../../../src/shared/ipc/result"; // The version the app tells Codex it is. (globalThis as { __APP_VERSION__?: string }).__APP_VERSION__ ??= "0.0.0"; @@ -19,8 +19,10 @@ import { const calls: { method: string; args: Record }[] = []; /** What a stopped program does to the tab's lines: none come here unless a test says. */ let onStop: (() => void) | undefined; +let stopFails = false; /** A Codex program that comes up, answering what is sent to it as the test says. */ let codex: ((message: Record) => void) | undefined; +let claudeSeq = 500; const realIpc = await import("../../../../../src/renderer/ipc/client"); mock.module("../../../../../src/renderer/ipc/client", () => ({ @@ -28,8 +30,24 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ // A Codex tab listens for its lines as it is made; none come here. ipcListen: () => () => {}, ipcCallResult: (_channel: string, method: string, args: Record) => { + const input = args.message as { type?: string; request_id?: string } | undefined; + if (method === "send" && input?.type === "control_request") { + const controller = live.find((c) => c.key === `${args.workspaceId}:${args.tabId}`); + controller?.receive({ + seq: ++claudeSeq, + dir: "out", + message: { + type: "control_response", + response: { subtype: "success", request_id: input.request_id, response: {} }, + }, + } as never); + return Promise.resolve({ ok: true, value: undefined }); + } calls.push({ method, args }); - if (method === "stop") onStop?.(); + if (method === "stop") { + if (stopFails) return Promise.resolve(ipcErr("chat.stop-failed", "stop refused")); + onStop?.(); + } if (method === "send") codex?.(args.message as Record); if (method === "stageThread") { return Promise.resolve({ ok: true, value: { found: args.threadId !== "gone" } }); @@ -52,8 +70,14 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ if (method === "transcript") { return Promise.resolve({ ok: true, value: { found: false, lines: [], truncated: false } }); } - // A start that does not come up: nothing past it runs here. - if (method === "start" || method === "codexStart") { + if (method === "start") { + return Promise.resolve({ + ok: true, + value: { ok: true, pid: 1, attached: false, version: null }, + }); + } + // Codex starts only when the test scripts a destination program. + if (method === "codexStart") { return Promise.resolve({ ok: true, value: { ok: false, reason: "failed", message: "not here" }, @@ -71,7 +95,7 @@ const { useChatStore } = await import("../../../../../src/renderer/services/chat const { useTabsStore } = await import("../../../../../src/renderer/state/stores/tabs"); let seq = 0; -const live: { dispose: () => void }[] = []; +const live: (InstanceType | InstanceType)[] = []; let restoreDestination: (() => void) | undefined; afterEach(() => { @@ -80,6 +104,7 @@ afterEach(() => { for (const c of live.splice(0)) c.dispose(); calls.length = 0; onStop = undefined; + stopFails = false; codex = undefined; }); @@ -129,7 +154,7 @@ describe("a Claude tab switched to another profile", () => { const state = c.state; expect(state.history).toBeNull(); expect(state.model.items).toEqual([]); - expect(state.model.lastSeq).toBe(7); + expect(state.model.lastSeq).toBeGreaterThan(7); expect(state.queue).toEqual([]); }); @@ -139,10 +164,20 @@ describe("a Claude tab switched to another profile", () => { expect(calls).toEqual([]); expect(seen).toEqual({}); }); + + test("a failed Claude stop leaves the source profile and held message", async () => { + const { c, seen } = claude(); + stopFails = true; + await expect(c.switchProfile("work")).rejects.toThrow("stop refused"); + expect(calls.map((call) => call.method)).toEqual(["stop"]); + expect(c.currentSession()).toBe("old"); + expect(c.state.queue.map((item) => item.id)).toEqual(["q"]); + expect(seen).toEqual({}); + }); }); describe("a Codex tab switched to another profile", () => { - function codex() { + function codexTab() { const seen: { profile?: string; title?: string } = {}; const c = new CodexController( { workspaceId: "ws-switch", tabId: `x${++seq}`, cwd: "/p", threadId: "old" }, @@ -174,23 +209,44 @@ describe("a Codex tab switched to another profile", () => { } test("starts a new thread with the destination profile defaults", async () => { - const { c, seen } = codex(); + const { c, seen } = codexTab(); + let seq = 100; + codex = (message) => { + if (message.id === undefined) return; + const result = message.method === "thread/start" ? { thread: { id: "new" } } : {}; + c.receive({ seq: ++seq, dir: "out", message: { id: message.id, result } } as never); + }; await c.setPermissionMode("fullAccess"); await c.setModel("gpt-old"); await c.setEffort("high"); await c.switchProfile("work"); - expect(calls.map((call) => call.method)).toEqual(["stop", "codexStart"]); + expect(calls.map((call) => call.method).filter((method) => method !== "send")).toEqual([ + "stop", + "codexStart", + ]); expect(calls[1]?.args.profileId).toBe("work"); expect(calls[1]?.args.resetLog).toBe(true); - expect(c.currentThread()).toBeUndefined(); + expect(c.currentThread()).toBe("new"); expect(seen).toEqual({ profile: "work", title: "" }); const model = c.state.model as Record; expect(model.items).toEqual([]); - expect(model.lastSeq).toBe(3); + expect(model.lastSeq as number).toBeGreaterThan(3); expect(model.model).toBeUndefined(); expect(model.account).toBeUndefined(); expect(model.permissionMode).toBeUndefined(); }); + + test("a rejected Codex destination startup leaves the source thread and queue available", async () => { + const { c, seen } = codexTab(); + const held = { id: "draft", text: "keep this", images: [] }; + useChatStore.getState().update(c.key, (prev) => ({ ...prev, queue: [held] })); + await expect(c.switchProfile("work")).rejects.toThrow("not here"); + expect(c.profileId).toBe("codex-default"); + expect(c.currentThread()).toBe("old"); + expect(c.state.queue).toEqual([held]); + expect(c.state.model.items.map((item) => item.key)).toEqual(["u1"]); + expect(seen).toEqual({}); + }); }); describe("a Claude tab's conversation gone on with in another profile", () => { @@ -271,7 +327,7 @@ describe("a Claude tab's conversation gone on with in another profile", () => { const state = c.state; expect(state.history?.items.map((item) => item.key)).toEqual(["u0", "u1", "a1"]); expect(state.model.items).toEqual([]); - expect(state.model.lastSeq).toBe(7); + expect(state.model.lastSeq).toBeGreaterThan(7); expect(state.queue).toEqual([]); }); @@ -323,9 +379,11 @@ describe("a Claude tab's conversation gone on with in another profile", () => { test("a session gone from the old profile fails the start", async () => { const { c } = claude({ sessionId: "gone" }); - await c.continueInProfile("work"); + await expect(c.continueInProfile("work")).rejects.toThrow(); expect(calls.map((call) => call.method)).toEqual(["stop", "sessionFile"]); expect(c.state.phase).toBe("failed"); + expect(c.currentSession()).toBe("gone"); + expect(c.profileId).toBe("claude-default"); }); test("a tab with no session yet just switches", async () => { @@ -413,7 +471,7 @@ describe("a Codex tab's thread gone on with in another profile", () => { expect(calls.map((call) => call.method)).not.toContain("codexStart"); }); - test("stops its program and starts one that forks the thread", async () => { + test("preserves the source after a failed fork startup", async () => { const resolve = resolveDestination(); const seen: { profile?: string; moves?: readonly unknown[] } = {}; const c = new CodexController( @@ -446,12 +504,12 @@ describe("a Codex tab's thread gone on with in another profile", () => { await expect(c.continueInProfile("work")).rejects.toThrow("not here"); expect(calls.map((call) => call.method)).toEqual(["stop", "codexStart"]); expect(calls[1]?.args.profileId).toBe("work"); - expect(seen.profile).toBe("work"); - // A turn's id holds in the copy; its items are numbered anew. - expect(seen.moves).toEqual([{ profileId: "work", after: "turn-1", at: expect.any(Number) }]); + expect(seen).toEqual({}); + expect(c.profileId).toBe("codex-default"); + expect(c.currentThread()).toBe("old"); const model = c.state.model as Record; - expect(model.items).toEqual([]); - expect(model.permissionMode).toBeUndefined(); + expect(c.state.model.items.map((item) => item.key)).toEqual(["u1", "a1"]); + expect(model.permissionMode).toBe("fullAccess"); expect(resolve.mock.calls[0]?.[1]).toEqual({ model: undefined, effort: undefined, @@ -597,8 +655,9 @@ describe("a Codex tab's thread gone on with in another profile", () => { codex = (message) => { sent.push(message); if (message.id === undefined) return; + const result = message.method === "thread/start" ? { thread: { id: "new" } } : {}; queueMicrotask(() => - c.receive({ seq: ++lineSeq, dir: "out", message: { id: message.id, result: {} } } as never), + c.receive({ seq: ++lineSeq, dir: "out", message: { id: message.id, result } } as never), ); }; await c.continueInProfile("work"); From a86989e0f9b853c5c0c832c6b041ef38135454a8 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:18:50 +0900 Subject: [PATCH 066/208] fix(pty): attach callers that join an in-flight spawn Co-Authored-By: Claude Opus 5.5 --- internal/pty/hangup_test.go | 29 ++++++++++++++++++++++------- internal/pty/service.go | 37 +++++++++++++++++++++++-------------- 2 files changed, 45 insertions(+), 21 deletions(-) diff --git a/internal/pty/hangup_test.go b/internal/pty/hangup_test.go index 3d7b2825d..09ff4930e 100644 --- a/internal/pty/hangup_test.go +++ b/internal/pty/hangup_test.go @@ -249,35 +249,37 @@ func TestRacingSpawnsOfATabForkOnlyOnce(t *testing.T) { <-release return startTerminal(spec) } - params := mustJSON(t, SpawnParams{ + params := SpawnParams{ WorkspaceID: testWorkspaceID, TabID: "racing-spawns", Cwd: t.TempDir(), Shell: "/bin/sh", Args: []string{"-c", "exec /bin/sleep 60"}, Cols: 80, Rows: 24, - }) + } type response struct { value any err error } var calls sync.WaitGroup - spawn := func(ctx context.Context) <-chan response { + spawn := func(ctx context.Context, params SpawnParams) <-chan response { + raw := mustJSON(t, params) done := make(chan response, 1) calls.Add(1) go func() { defer calls.Done() - value, err := service.Spawn(ctx, params) + value, err := service.Spawn(ctx, raw) done <- response{value, err} }() return done } defer func() { unblock(); calls.Wait() }() - owner := spawn(context.Background()) + owner := spawn(context.Background(), params) select { case <-first: case <-time.After(2 * time.Second): t.Fatal("first request never attempted to start a shell") } waiting := make(chan struct{}) - joined := spawn(spawnWaitContext{context.Background(), sync.OnceFunc(func() { close(waiting) })}) + params.Cols, params.Rows = 120, 40 + joined := spawn(spawnWaitContext{context.Background(), sync.OnceFunc(func() { close(waiting) })}, params) select { case <-waiting: case <-duplicate: @@ -288,9 +290,22 @@ func TestRacingSpawnsOfATabForkOnlyOnce(t *testing.T) { unblock() a, b := <-owner, <-joined - if a.err != nil || b.err != nil || a.value != b.value || starts.Load() != 1 { + firstSpawn, firstOK := a.value.(SpawnResult) + attached, attachedOK := b.value.(SpawnResult) + if a.err != nil || b.err != nil || !firstOK || !attachedOK || starts.Load() != 1 || + firstSpawn.Attached || !attached.Attached || firstSpawn.PID != attached.PID { t.Fatalf("spawns returned %+v and %+v with %d starts", a, b, starts.Load()) } + session := service.lookup(tabKey{workspaceID: testWorkspaceID, tabID: params.TabID}) + if session == nil { + t.Fatal("the shared shell exited before the attach finished") + } + session.sizeMu.Lock() + cols, rows := session.lastCols, session.lastRows + session.sizeMu.Unlock() + if cols != params.Cols || rows != params.Rows { + t.Fatalf("joined terminal is %dx%d, want %dx%d", cols, rows, params.Cols, params.Rows) + } } // A kill that reaches the agent before the spawn it followed — each request diff --git a/internal/pty/service.go b/internal/pty/service.go index 51d595b0a..cb7c7bbec 100644 --- a/internal/pty/service.go +++ b/internal/pty/service.go @@ -34,9 +34,9 @@ type Service struct { // pendingSpawn publishes one shell startup result to concurrent callers. type pendingSpawn struct { - done chan struct{} - result SpawnResult - err error + done chan struct{} + session *session + err error } // outputSink identifies a connection and captures its event destination. @@ -246,18 +246,17 @@ func (s *Service) Spawn(ctx context.Context, raw json.RawMessage) (any, error) { s.mu.Unlock() select { case <-starting.done: - return starting.result, starting.err + if starting.err != nil { + return nil, starting.err + } + return starting.session.attach(p.Cols, p.Rows), nil case <-ctx.Done(): return nil, ctx.Err() } } if existing := s.sessions[key]; existing != nil { s.mu.Unlock() - // The session outlived its previous client (an app restart or a window - // reload). Fit it to the new client, which replays it to redraw the - // screen. Best-effort: a session that is exiting reports exit anyway. - _ = existing.resize(p.Cols, p.Rows) - return SpawnResult{PID: existing.child.Pid, Attached: true}, nil + return existing.attach(p.Cols, p.Rows), nil } attempt := &pendingSpawn{done: make(chan struct{})} s.spawning[key] = attempt @@ -265,16 +264,19 @@ func (s *Service) Spawn(ctx context.Context, raw json.RawMessage) (any, error) { s.mu.Unlock() defer s.starts.Done() - attempt.result, attempt.err = s.spawnSession(key, p) + attempt.session, attempt.err = s.spawnSession(key, p) s.mu.Lock() delete(s.spawning, key) close(attempt.done) s.mu.Unlock() - return attempt.result, attempt.err + if attempt.err != nil { + return nil, attempt.err + } + return SpawnResult{PID: attempt.session.child.Pid}, nil } // spawnSession starts and registers a shell for a reserved tab. -func (s *Service) spawnSession(key tabKey, p SpawnParams) (SpawnResult, error) { +func (s *Service) spawnSession(key tabKey, p SpawnParams) (*session, error) { shell := strings.TrimSpace(p.Shell) if shell == "" { shell = defaultShell() @@ -288,7 +290,7 @@ func (s *Service) spawnSession(key tabKey, p SpawnParams) (SpawnResult, error) { rows: p.Rows, }) if err != nil { - return SpawnResult{}, requestFailed("failed to spawn PTY: %s", err) + return nil, requestFailed("failed to spawn PTY: %s", err) } session := newSession(s, key, child, master) @@ -305,7 +307,14 @@ func (s *Service) spawnSession(key tabKey, p SpawnParams) (SpawnResult, error) { // The tab's kill overtook this spawn: end the shell as it would have. session.stop() } - return SpawnResult{PID: child.Pid}, nil + return session, nil +} + +// attach fits a running shell to its caller, which replays the session to +// redraw the screen. A shell exiting during the resize reports its exit. +func (s *session) attach(cols, rows int) SpawnResult { + _ = s.resize(cols, rows) + return SpawnResult{PID: s.child.Pid, Attached: true} } // Write sends user input bytes to the child PTY. From 2497491116d2dbd30fcd3218554ebaed54afccc3 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:02:40 +0900 Subject: [PATCH 067/208] fix(remote): stop the pairing relay during main shutdown Co-Authored-By: Claude Opus 5.5 --- src/main/features/remote/index.ts | 2 + tests/integration/ipc-roundtrip.test.ts | 65 ++++++++++++++++++++++++- tests/setup.ts | 6 +++ 3 files changed, 71 insertions(+), 2 deletions(-) diff --git a/src/main/features/remote/index.ts b/src/main/features/remote/index.ts index d33eb1e68..4bc03c774 100644 --- a/src/main/features/remote/index.ts +++ b/src/main/features/remote/index.ts @@ -974,8 +974,10 @@ export async function registerRemoteChannel(options: { inRoom().request(deviceId, method, params, timeoutMs, signal), }, dispose: () => { + if (disposed) return; disposed = true; proxyProbe.stop(); + pairing.stop(); account.cancelSignIn(); voice.cancel(); noteVoice.cancel(); diff --git a/tests/integration/ipc-roundtrip.test.ts b/tests/integration/ipc-roundtrip.test.ts index 386335c2f..3fd33f65a 100644 --- a/tests/integration/ipc-roundtrip.test.ts +++ b/tests/integration/ipc-roundtrip.test.ts @@ -8,7 +8,10 @@ * Monaco + xterm renderer integration requires a browser-level manual scenario. */ -import { beforeAll, describe, expect, it, mock } from "bun:test"; +import { beforeAll, describe, expect, it, mock, spyOn } from "bun:test"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; import { z } from "zod"; // --------------------------------------------------------------------------- @@ -57,15 +60,26 @@ mock.module("electron-log/main", () => ({ }, })); +let userData = "/tmp"; mock.module("electron", () => ({ ipcMain: { handle: fakeIpcMainHandle, on: fakeIpcMainOn }, webContents: { getAllWebContents: fakeGetAllWebContents }, - app: { getPath: () => "/tmp" }, + app: { getPath: () => userData, isPackaged: false, getVersion: () => "0.1.0" }, + nativeImage: {}, + shell: {}, + systemPreferences: {}, + safeStorage: { + isAsyncEncryptionAvailable: async () => true, + getSelectedStorageBackend: () => "test", + decryptStringAsync: async (bytes: Buffer) => ({ result: bytes.toString("utf8") }), + }, })); const { broadcast, excludeFromBroadcast, register, setupRouter, validateArgs } = await import( "../../src/main/infra/ipc-router" ); +const { registerRemoteChannel } = await import("../../src/main/features/remote"); +const { remoteServer } = await import("../../src/main/features/remote/server"); const { isIpcErrResult } = await import("../../src/shared/ipc/result"); // --------------------------------------------------------------------------- @@ -196,3 +210,50 @@ describe("ipc round-trip — routing errors", () => { ); }); }); + +describe("remote shutdown", () => { + it("stops the temporary relay when the registered remote feature shuts down", async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), "nexus-remote-dispose-")); + userData = directory; + const ticket = Promise.withResolvers(); + const fetch = spyOn(globalThis, "fetch").mockImplementation(async (url, options) => { + if (new URL(String(url)).pathname === "/relay/ticket") { + ticket.resolve(options?.signal); + return new Promise(() => {}); + } + return new Response(null, { status: 404 }); + }); + try { + await writeFile( + path.join(directory, "remote-account.bin"), + JSON.stringify({ + server: remoteServer(process.env, false), + token: "fixture-token", + user: { id: "u1", name: "Test", email: "test@example.test" }, + device: { id: "d1", name: "Test", platform: "darwin" }, + }), + ); + const off = { get: () => false, set: () => {} }; + const remote = await registerRemoteChannel({ + services: () => null, + allowControl: off, + allowTerminal: off, + agents: { get: () => "deny", set: () => {} }, + }); + try { + const start = getHandler()({}, "remote", "pairStart", undefined); + const signal = await ticket.promise; + await start; + remote.dispose(); + expect(signal?.aborted).toBe(true); + } finally { + await getHandler()({}, "remote", "pairStop", undefined); + remote.dispose(); + } + } finally { + fetch.mockRestore(); + userData = "/tmp"; + await rm(directory, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/setup.ts b/tests/setup.ts index 1e32c9d5f..dce98a2d4 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -344,6 +344,12 @@ mock.module("electron", () => ({ quit: (): void => {}, }, + // Remote feature registration imports these Electron services. + nativeImage: {}, + shell: {}, + systemPreferences: {}, + safeStorage: {}, + // ipcMain — used by: setupRouter() in pty-channel, ipc-shim-integration, // ipc-wrapper-env, show-save-dialog ipcMain: { From 98eefc57ffa15caaef51d876afdfa782b79f64fe Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:10:43 +0900 Subject: [PATCH 068/208] fix(ipc): return typed call failures and log unexpected errors Co-Authored-By: Claude Opus 5.5 --- src/main/features/fs/ipc/fs-result.ts | 19 +- src/main/features/fs/ipc/watch-handlers.ts | 45 +---- src/main/features/fs/ipc/write-handlers.ts | 167 ++++++------------ src/main/features/pty/ipc.ts | 4 +- src/main/features/remote/account-keys.ts | 18 +- src/main/features/remote/account.ts | 5 +- src/main/features/remote/index.ts | 5 +- src/main/features/remote/room.ts | 12 +- src/main/features/remote/route.ts | 6 +- src/main/features/remote/session-watches.ts | 6 +- src/main/features/ssh/ipc.ts | 150 ++++------------ src/main/features/workspace/ipc.ts | 91 +--------- src/main/features/wsl/ipc.ts | 44 ++++- src/main/infra/agent/pipe.ts | 2 +- src/main/infra/ipc-router/agent-errors.ts | 50 ++++++ src/main/infra/ipc-router/index.ts | 118 ++++--------- .../add-workspace/main-list-view.tsx | 23 +-- .../ssh-connection-list-view.tsx | 21 ++- .../ssh-directory-picker-view.tsx | 68 +++---- .../workspace/add-workspace/ssh-helpers.ts | 49 ----- .../add-workspace/ssh-new-connection-view.tsx | 31 ++-- .../add-workspace/use-path-autocomplete.ts | 4 +- .../add-workspace/wsl-distro-list-view.tsx | 58 ++++-- src/renderer/hooks/use-ipc-action.ts | 3 + src/renderer/ipc/client.ts | 10 +- .../services/error-surface/surface-error.ts | 30 +++- src/renderer/services/fs-mutations/errors.ts | 8 + src/renderer/services/workspace/ssh-browse.ts | 17 +- src/renderer/services/workspace/wsl.ts | 8 +- src/shared/ipc/result.ts | 33 ++-- tests/integration/ipc-roundtrip.test.ts | 135 +++++++++++++- tests/unit/main/pty/ipc-shell-choice.test.ts | 12 +- tests/unit/main/wsl/ipc.test.ts | 41 ++++- 33 files changed, 645 insertions(+), 648 deletions(-) create mode 100644 src/main/infra/ipc-router/agent-errors.ts diff --git a/src/main/features/fs/ipc/fs-result.ts b/src/main/features/fs/ipc/fs-result.ts index 19a3c0298..f235af54a 100644 --- a/src/main/features/fs/ipc/fs-result.ts +++ b/src/main/features/fs/ipc/fs-result.ts @@ -16,7 +16,9 @@ */ import { FS_ERROR } from "../../../../shared/fs/errors"; -import { type IpcErrResult, ipcErr } from "../../../../shared/ipc/result"; +import { type IpcErrResult, type IpcResult, ipcErr, ipcOk } from "../../../../shared/ipc/result"; + +import { agentCallError } from "../../../infra/ipc-router/agent-errors"; export const FS_IPC_ERROR_KIND = "fs-error" as const; export type FsIpcErrorResult = IpcErrResult; @@ -41,5 +43,18 @@ export function isFsError(error: unknown): boolean { */ export function fsErrorToIpcResult(error: unknown): FsIpcErrorResult { const message = error instanceof Error ? error.message : String(error); - return ipcErr(FS_IPC_ERROR_KIND, message); + const code = Object.values(FS_ERROR).find((value) => message.startsWith(`${value}:`)); + return ipcErr(FS_IPC_ERROR_KIND, message, { category: "failed", domain: "fs", code }); +} + +/** Envelopes a file operation, including failures while resolving its provider. */ +export async function runFsCall(run: () => Promise): Promise> { + try { + return ipcOk(await run()); + } catch (error) { + if (isFsError(error)) return fsErrorToIpcResult(error); + const expected = agentCallError(error); + if (expected) return expected; + throw error; + } } diff --git a/src/main/features/fs/ipc/watch-handlers.ts b/src/main/features/fs/ipc/watch-handlers.ts index 8ead5081e..25281d4a7 100644 --- a/src/main/features/fs/ipc/watch-handlers.ts +++ b/src/main/features/fs/ipc/watch-handlers.ts @@ -1,49 +1,22 @@ -/** - * fs watch handlers — watch / unwatch lifecycle. - * - * Both handlers catch agent-thrown fs errors and return them as a typed - * `ipcErr` envelope (matches the read-handlers pattern). The motivating - * case is `ensureRoot`'s hydration loop: every persisted expanded path - * triggers a `fs.watch` call, and if the user has deleted the folder on - * disk between sessions the agent throws NOT_FOUND. Without this - * envelope the rejection reaches Electron's `ipcMain.handle` invocation - * logger, which prints - * "Error occurred in handler for 'ipc:call': Error: NOT_FOUND: …" - * on every stale row. The renderer side is unchanged — `unwrapIpcResult` - * still throws the same `"CODE: …"` message that `hasFsErrorCode` can - * classify — so call sites that previously surfaced toasts keep working. - */ import { ipcContract } from "../../../../shared/ipc/contract"; import { validateArgs } from "../../../infra/ipc-router"; import type { AgentFsWatcher } from "../bridge/agent-watch"; -import { type FsIpcErrorResult, fsErrorToIpcResult, isFsError } from "./fs-result"; +import { runFsCall } from "./fs-result"; const c = ipcContract.fs.call; -export function watchHandler( - watcher: AgentFsWatcher, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Registers a directory watch and returns any expected failure in the call envelope. */ +export function watchHandler(watcher: AgentFsWatcher) { + return (args: unknown) => { const { workspaceId, relPath } = validateArgs(c.watch.args, args); - try { - await watcher.watch(workspaceId, relPath); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(() => watcher.watch(workspaceId, relPath)); }; } -export function unwatchHandler( - watcher: AgentFsWatcher, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Removes a directory watch through the same call contract. */ +export function unwatchHandler(watcher: AgentFsWatcher) { + return (args: unknown) => { const { workspaceId, relPath } = validateArgs(c.unwatch.args, args); - try { - await watcher.unwatch(workspaceId, relPath); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(() => watcher.unwatch(workspaceId, relPath)); }; } diff --git a/src/main/features/fs/ipc/write-handlers.ts b/src/main/features/fs/ipc/write-handlers.ts index f05ccd034..86cd61fea 100644 --- a/src/main/features/fs/ipc/write-handlers.ts +++ b/src/main/features/fs/ipc/write-handlers.ts @@ -1,146 +1,95 @@ -/** - * Write fs handlers — thin IPC adapters over the workspace's agent-backed - * filesystem provider. - * - * Every handler catches agent-thrown fs errors (ALREADY_EXISTS, NOT_FOUND, - * PERMISSION_DENIED, IS_DIRECTORY, NOT_EMPTY, …) and returns them as a typed - * `ipcErr` envelope instead of letting them throw. Without this, Electron's - * `ipcMain.handle` invocation logger prints - * "Error occurred in handler for 'ipc:call': Error: ALREADY_EXISTS: …" - * on every expected user-facing failure (creating a name that already exists, - * renaming to a colliding name, deleting a path the watcher hasn't dropped - * yet, …) — duplicating the toast we already raise in the renderer. The - * renderer side is unchanged: `unwrapIpcResult` rethrows the envelope as an - * `Error("CODE: …")` so `toFsToast` keeps classifying it. - * - * Mirrors the read/watch handlers, which have used this wrap since they were - * introduced. - */ - -import type { WriteFileResult } from "../../../../shared/fs/types"; +/** Write adapters envelope both provider startup and the agent operation. */ import { ipcContract } from "../../../../shared/ipc/contract"; import { validateArgs } from "../../../infra/ipc-router"; import type { WorkspaceManager } from "../../workspace/manager"; -import { type FsIpcErrorResult, fsErrorToIpcResult, isFsError } from "./fs-result"; +import { runFsCall } from "./fs-result"; const c = ipcContract.fs.call; -export function writeFileHandler( - manager: WorkspaceManager, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Runs the agent's writeFile operation on the selected workspace. */ +export function writeFileHandler(manager: WorkspaceManager) { + return (args: unknown) => { const { workspaceId, relPath, content, expected, bytes } = validateArgs(c.writeFile.args, args); - const fs = await manager.getFs(workspaceId); - try { - return await fs.writeFile(relPath, content, expected, bytes); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(async () => { + const fs = await manager.getFs(workspaceId); + return fs.writeFile(relPath, content, expected, bytes); + }); }; } -export function createFileHandler( - manager: WorkspaceManager, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Runs the agent's createFile operation on the selected workspace. */ +export function createFileHandler(manager: WorkspaceManager) { + return (args: unknown) => { const { workspaceId, relPath } = validateArgs(c.createFile.args, args); - const fs = await manager.getFs(workspaceId); - try { - await fs.createFile(relPath); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(async () => { + const fs = await manager.getFs(workspaceId); + return fs.createFile(relPath); + }); }; } -export function mkdirHandler( - manager: WorkspaceManager, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Runs the agent's mkdir operation on the selected workspace. */ +export function mkdirHandler(manager: WorkspaceManager) { + return (args: unknown) => { const { workspaceId, relPath, recursive } = validateArgs(c.mkdir.args, args); - const fs = await manager.getFs(workspaceId); - try { - await fs.mkdir(relPath, recursive); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(async () => { + const fs = await manager.getFs(workspaceId); + return fs.mkdir(relPath, recursive); + }); }; } -export function unlinkHandler( - manager: WorkspaceManager, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Runs the agent's unlink operation on the selected workspace. */ +export function unlinkHandler(manager: WorkspaceManager) { + return (args: unknown) => { const { workspaceId, relPath } = validateArgs(c.unlink.args, args); - const fs = await manager.getFs(workspaceId); - try { - await fs.unlink(relPath); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(async () => { + const fs = await manager.getFs(workspaceId); + return fs.unlink(relPath); + }); }; } -export function rmdirHandler( - manager: WorkspaceManager, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Runs the agent's rmdir operation on the selected workspace. */ +export function rmdirHandler(manager: WorkspaceManager) { + return (args: unknown) => { const { workspaceId, relPath } = validateArgs(c.rmdir.args, args); - const fs = await manager.getFs(workspaceId); - try { - await fs.rmdir(relPath); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(async () => { + const fs = await manager.getFs(workspaceId); + return fs.rmdir(relPath); + }); }; } -export function renameHandler( - manager: WorkspaceManager, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Runs the agent's rename operation on the selected workspace. */ +export function renameHandler(manager: WorkspaceManager) { + return (args: unknown) => { const { workspaceId, fromRelPath, toRelPath, overwrite } = validateArgs(c.rename.args, args); - const fs = await manager.getFs(workspaceId); - try { - await fs.rename(fromRelPath, toRelPath, overwrite); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(async () => { + const fs = await manager.getFs(workspaceId); + return fs.rename(fromRelPath, toRelPath, overwrite); + }); }; } -export function copyFileHandler( - manager: WorkspaceManager, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Runs the agent's copyFile operation on the selected workspace. */ +export function copyFileHandler(manager: WorkspaceManager) { + return (args: unknown) => { const { workspaceId, fromRelPath, toRelPath, overwrite } = validateArgs(c.copyFile.args, args); - const fs = await manager.getFs(workspaceId); - try { - await fs.copyFile(fromRelPath, toRelPath, overwrite); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(async () => { + const fs = await manager.getFs(workspaceId); + return fs.copyFile(fromRelPath, toRelPath, overwrite); + }); }; } -export function removeAllHandler( - manager: WorkspaceManager, -): (args: unknown) => Promise { - return async (args: unknown): Promise => { +/** Runs the agent's removeAll operation on the selected workspace. */ +export function removeAllHandler(manager: WorkspaceManager) { + return (args: unknown) => { const { workspaceId, relPath } = validateArgs(c.removeAll.args, args); - const fs = await manager.getFs(workspaceId); - try { - await fs.removeAll(relPath); - } catch (error) { - if (isFsError(error)) return fsErrorToIpcResult(error); - throw error; - } + return runFsCall(async () => { + const fs = await manager.getFs(workspaceId); + return fs.removeAll(relPath); + }); }; } diff --git a/src/main/features/pty/ipc.ts b/src/main/features/pty/ipc.ts index c18de15ed..478c5759a 100644 --- a/src/main/features/pty/ipc.ts +++ b/src/main/features/pty/ipc.ts @@ -195,7 +195,9 @@ export function registerPtyChannel(options: PtyChannelOptions): void { let env = givenEnv; if (profile !== undefined) { const fromProfile = await options.profileEnv?.(workspaceId, profile); - if (!fromProfile) throw new Error(`no profile ${profile}`); + if (!fromProfile) { + return ipcErr("not-found", `no profile ${profile}`, { category: "failed" }); + } env = { ...givenEnv, ...fromProfile }; } recorder.start(workspaceId, tabId, cols, rows); diff --git a/src/main/features/remote/account-keys.ts b/src/main/features/remote/account-keys.ts index 1a7b562c9..ef3ea8ee6 100644 --- a/src/main/features/remote/account-keys.ts +++ b/src/main/features/remote/account-keys.ts @@ -8,6 +8,7 @@ * from an envelope after another device rotated it, rotates it when it * removes a device, and gives the server the password's proof where it asks. */ + import { z } from "zod"; import { ACCOUNT_AUTH_ERROR, @@ -22,6 +23,7 @@ import { KeyEnvelopesResponseSchema, type KeyRotation, } from "../../../../packages/remote-protocol/src"; +import { createLogger } from "../../../shared/log/main"; import type { AccountKeyState, KeyFailure, @@ -49,6 +51,8 @@ import { import { ServerError, SignedOutError, UnreachableError } from "./errors"; import type { Kept } from "./sealed-file"; +const log = createLogger("remote-account-keys"); + const BUNDLE_PATH = "/account/key-bundle"; /** The account key as this device keeps it, sealed: whose, and which version. */ @@ -366,7 +370,7 @@ export class AccountKeys { // A device with an older key, or none, asks for the password, as before v2. if (!device.key || device.key.kid !== k) continue; if (!certChecks(opened.key, userId, device.id, device.key)) { - console.warn(`[remote] device ${device.id}'s key does not check; the key was not rotated`); + log.warn(`device ${device.id}'s key does not check; the key was not rotated`); throw new KeyError("device-key"); } envelopes.push({ @@ -427,19 +431,19 @@ export class AccountKeys { if (found && this.held && found.bundle.kid > this.held.kid) { // Another device rotated the key: an envelope may carry it here. await this.takeEnvelopes().catch((error: unknown) => - console.warn("[remote] taking the new account key from an envelope failed:", error), + log.warn(`Could not open the new account key envelope: ${String(error)}`), ); } if (!found) this.set({ status: "missing" }); else if (this.held?.kid === found.bundle.kid) { this.set({ status: "unlocked", kid: found.bundle.kid, ...this.extras() }); await this.syncDeviceKey().catch((error: unknown) => - console.warn("[remote] registering this device's key failed:", error), + log.warn(`Could not register this device key: ${String(error)}`), ); } else if (this.held && this.older(found)) { // A key older than the one held: the server went back, or is made to. The newer key stays. - console.warn( - `[remote] the server's account key (version ${found.bundle.kid}) is older than this device's (${this.held.kid}); kept this one`, + log.warn( + `the server's account key (version ${found.bundle.kid}) is older than this device's (${this.held.kid}); kept this one`, ); this.set({ status: "unlocked", kid: this.held.kid, ...this.extras() }); } else this.set({ status: "locked", kid: found.bundle.kid, ...this.extras() }); @@ -494,7 +498,7 @@ export class AccountKeys { held: current, }); if (!key) { - console.warn(`[remote] an envelope of key version ${envelope.kid} did not open`); + log.warn(`an envelope of key version ${envelope.kid} did not open`); break; } current = { kid: envelope.kid, key }; @@ -627,7 +631,7 @@ export class AccountKeys { } catch (error) { if (error instanceof WrongPasswordError) throw new KeyError("wrong-password"); if (error instanceof KdfTooHeavyError) { - console.warn(`[remote] ${error.message}`); + log.warn(`${error.message}`); throw new KeyError("too-heavy"); } throw error; diff --git a/src/main/features/remote/account.ts b/src/main/features/remote/account.ts index f538a1570..a91635184 100644 --- a/src/main/features/remote/account.ts +++ b/src/main/features/remote/account.ts @@ -10,6 +10,7 @@ import os from "node:os"; import { z } from "zod"; import { type ServerInfo, ServerInfoSchema } from "../../../../packages/remote-protocol/src"; +import { createLogger } from "../../../shared/log/main"; import { type RemoteAccountState, type RemoteDeviceInfo, @@ -24,6 +25,8 @@ import { makePkce, makeState } from "./pkce"; import { ServerRoute } from "./route"; import type { Kept } from "./sealed-file"; +const log = createLogger("remote-account"); + export { SignedOutError } from "./errors"; /** How long a call to the server may take. */ @@ -182,7 +185,7 @@ export class RemoteAccount { await this.deps.store.save(this.saved); } catch (error) { this.failure = failureOf(error); - console.warn("[remote] sign-in failed:", error instanceof Error ? error.message : error); + log.warn(`Sign-in failed: ${error instanceof Error ? error.message : String(error)}`); } finally { listener.close(); this.signingIn = null; diff --git a/src/main/features/remote/index.ts b/src/main/features/remote/index.ts index 4bc03c774..dfe4bd332 100644 --- a/src/main/features/remote/index.ts +++ b/src/main/features/remote/index.ts @@ -12,6 +12,7 @@ import { MAX_TRANSCRIBE_BYTES } from "../../../../packages/remote-protocol/src/v import type { GitStatus } from "../../../shared/git/types"; import { ipcContract } from "../../../shared/ipc/contract"; import { type IpcResult, ipcErr, ipcOk } from "../../../shared/ipc/result"; +import { createLogger } from "../../../shared/log/main"; import { type AccountKeyState, deviceLabel } from "../../../shared/remote/account"; import type { RoomState } from "../../../shared/remote/room"; import type { RemoteAgentsPolicy } from "../../../shared/types/app-state"; @@ -46,6 +47,8 @@ import { askTicket } from "./ticket"; import { VoiceSessions } from "./voice"; import { listedComputers, VoiceNames } from "./voice-names"; +const log = createLogger("remote-index"); + const c = ipcContract.remote.call; /** @@ -267,7 +270,7 @@ export async function registerRemoteChannel(options: { broadcast("remote", "roomChanged", state); }; let keys: AccountKeys | null = null; - const server = remoteServer(process.env, app.isPackaged, (m) => console.warn(`[remote] ${m}`)); + const server = remoteServer(process.env, app.isPackaged, (message) => log.warn(message)); const account = new RemoteAccount({ server, proxy: remoteProxy(process.env, app.isPackaged, server), diff --git a/src/main/features/remote/room.ts b/src/main/features/remote/room.ts index 7b1f04b36..5054a2176 100644 --- a/src/main/features/remote/room.ts +++ b/src/main/features/remote/room.ts @@ -5,6 +5,7 @@ * It takes only what was sealed for it, now, and each message once: the * epochs and seqs of packages/remote-protocol's ./sealed.ts. */ + import { randomBytes } from "node:crypto"; import { posix, win32 } from "node:path"; import { @@ -32,11 +33,14 @@ import { type SealedMessage, type ServerFrame, } from "../../../../packages/remote-protocol/src"; +import { createLogger } from "../../../shared/log/main"; import type { RoomPeer, RoomState, RoomStatus } from "../../../shared/remote/room"; import { isFileTransferMethod } from "./file-io"; import type { RelayConnectionDeps, RelayStatus } from "./relay-connection"; import { openMessage, type RoomKey, sealMessage } from "./seal"; +const log = createLogger("remote-room"); + /** How long an answer may take. */ export const REQUEST_TIMEOUT_MS = 15_000; @@ -454,7 +458,7 @@ export class RemoteRoom { if (frame.t === "message") { this.inbox = this.inbox .then(() => this.take(frame)) - .catch((error) => console.warn("[remote] taking a message failed:", error)); + .catch((error) => log.warn(`Could not process a relay message: ${String(error)}`)); return; } if (frame.t === "account") { @@ -469,7 +473,7 @@ export class RemoteRoom { p.reject(new RpcFailure(RpcErrorCode.Unavailable, "that device is not in the room")); } } else if (frame.code !== "unauthorized") { - console.warn(`[remote] relay: ${frame.code} ${frame.message}`); + log.warn(`relay: ${frame.code} ${frame.message}`); } } @@ -762,7 +766,9 @@ export class RemoteRoom { }, }; } - console.warn(`[remote] serving ${method} failed:`, error); + log.warn( + `Serving ${method} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`, + ); return { error: { code: RpcErrorCode.InternalError, message: "the device could not answer" }, }; diff --git a/src/main/features/remote/route.ts b/src/main/features/remote/route.ts index 190d21388..29cc141c9 100644 --- a/src/main/features/remote/route.ts +++ b/src/main/features/remote/route.ts @@ -6,6 +6,10 @@ * PROXY_DOWN_MS, then try it again. */ +import { createLogger } from "../../../shared/log/main"; + +const log = createLogger("remote-route"); + /** How long requests go straight to the server once the proxy could not be reached. */ export const PROXY_DOWN_MS = 5 * 60_000; @@ -46,7 +50,7 @@ export class ServerRoute { unreachable(address: string): boolean { if (this.proxy === null || !sameHost(address, this.proxy)) return false; if (this.now() >= this.downUntil) { - console.warn("[remote] the proxy could not be reached; going to the server straight"); + log.warn("The proxy could not be reached, using the direct server route."); } this.downUntil = this.now() + PROXY_DOWN_MS; return true; diff --git a/src/main/features/remote/session-watches.ts b/src/main/features/remote/session-watches.ts index e9695dfe9..2e7e36281 100644 --- a/src/main/features/remote/session-watches.ts +++ b/src/main/features/remote/session-watches.ts @@ -7,6 +7,7 @@ * change within a second. The consent prompts waiting on the user go with * it, as that watcher may answer them. */ + import { randomUUID } from "node:crypto"; import { type RemoteConsent, @@ -15,8 +16,11 @@ import { type RpcResult, type SessionsUpdate, } from "../../../../packages/remote-protocol/src"; +import { createLogger } from "../../../shared/log/main"; import { RpcFailure } from "./room"; +const log = createLogger("remote-session-watches"); + /** How often the list is made again while watched. */ export const SESSIONS_POLL_MS = 1000; @@ -114,7 +118,7 @@ export class SessionWatches { await this.deps.notify(watch.from, { ...list, watchId }); } } catch (error) { - console.warn("[remote] the sessions' list could not be made:", error); + log.warn(`Could not list sessions: ${String(error)}`); } finally { this.polling = false; } diff --git a/src/main/features/ssh/ipc.ts b/src/main/features/ssh/ipc.ts index 79d0bb545..38b44cee8 100644 --- a/src/main/features/ssh/ipc.ts +++ b/src/main/features/ssh/ipc.ts @@ -1,14 +1,12 @@ import { readFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { FS_ERROR } from "../../../shared/fs/errors"; import type { DirEntry } from "../../../shared/fs/types"; import { DirEntrySchema } from "../../../shared/fs/types"; import { ipcContract } from "../../../shared/ipc/contract"; -import { ipcErr, ipcOk } from "../../../shared/ipc/result"; -import { createLogger } from "../../../shared/log/main"; -import type { SshErrorCode } from "../../../shared/ssh/errors"; -import { SshErrorCodeSchema } from "../../../shared/ssh/errors"; -import { AuthCancelledError } from "../../infra/agent/ssh/auth-prompt"; +import { type IpcResult, ipcErr, ipcOk } from "../../../shared/ipc/result"; +import { messageForSshErrorCode } from "../../infra/agent/pipe"; import type { SshAuthPromptHandler } from "../../infra/agent/ssh/auth-pty"; import { createSshChannel } from "../../infra/agent/ssh/channel"; import type { SshControlMaster } from "../../infra/agent/ssh/master"; @@ -23,11 +21,11 @@ import { type SshTarget, } from "../../infra/agent/ssh/ssh2/config"; import { register, validateArgs } from "../../infra/ipc-router"; +import { agentCallError } from "../../infra/ipc-router/agent-errors"; import { BROWSE_MAX_ENTRIES, type SshBrowseSessionRegistry } from "./browse-session-registry"; import { parseSshConfig, type SshConfigHost } from "./config"; const c = ipcContract.ssh.call; -const log = createLogger("ssh"); /** The host fields a browse session connects with. */ type SshUserTarget = Pick; @@ -279,7 +277,7 @@ export function openBrowseSessionHandler( channel?.dispose(); // If bootstrap succeeded but channel setup failed, dispose bootstrap. bootstrapResult?.dispose?.(); - throw mapToBrowseError(error); + throw error; } }; } @@ -302,21 +300,15 @@ export function openBrowseSessionResultHandler( options: EnsureRemoteAgentOptions, onProgress?: (event: LspBootstrapProgressEvent) => void, ) => ReturnType, -): (args: unknown) => Promise | ReturnType> { +): (args: unknown) => Promise> { const inner = openBrowseSessionHandler(registry, promptHandler, broadcast, bootstrap); return async (args: unknown) => { try { const result = await inner(args); return ipcOk(result); } catch (error) { - if (isAuthCancellation(error)) { - return ipcErr("cancelled", "SSH authentication cancelled"); - } - const code = sshErrorCodeFromError(error); - if (code) { - return ipcErr("auth-failed", messageForSshErrorCode(code), { code }); - } - // Unexpected bug — rethrow so the router logs it. + const expected = agentCallError(error, "auth-failed"); + if (expected) return expected; throw error; } }; @@ -353,30 +345,44 @@ function buildMasterHandle( */ export function browseSessionHandler( registry: SshBrowseSessionRegistry, -): (args: unknown) => Promise<{ entries: DirEntry[]; truncated: boolean }> { - return async (args: unknown): Promise<{ entries: DirEntry[]; truncated: boolean }> => { +): (args: unknown) => Promise> { + return async (args: unknown) => { const { sessionId, path: dirPath } = validateArgs(c.browseSession.args, args); const session = registry.get(sessionId); if (!session) { - throw createSshErrorObject("ssh.session-expired"); + const code = "ssh.session-expired"; + return ipcErr("session-expired", messageForSshErrorCode(code), { + category: "failed", + domain: "ssh", + code, + }); } let rawEntries: unknown; try { rawEntries = await session.channel.call("fs.readdir", { relPath: dirPath }); } catch (error) { - throw mapToBrowseError(error); + if (error instanceof Error && "code" in error && error.code === FS_ERROR.NOT_FOUND) { + const code = "ssh.path-not-found"; + return ipcErr("not-found", messageForSshErrorCode(code), { + category: "failed", + domain: "ssh", + code, + }); + } + const expected = agentCallError(error); + if (expected) return expected; + throw error; } // Parse the raw response — the agent returns an array of DirEntry objects. - const parseResult = DirEntrySchema.array().safeParse(rawEntries); - const allEntries: DirEntry[] = parseResult.success ? parseResult.data : []; + const allEntries = DirEntrySchema.array().parse(rawEntries); const truncated = allEntries.length > BROWSE_MAX_ENTRIES; const entries = truncated ? allEntries.slice(0, BROWSE_MAX_ENTRIES) : allEntries; - return { entries, truncated }; + return ipcOk({ entries, truncated }); }; } @@ -388,12 +394,11 @@ export function browseSessionHandler( * Builds the closeBrowseSession IPC handler. Idempotent — safe to call on * an already-closed or unknown session. */ -export function closeBrowseSessionHandler( - registry: SshBrowseSessionRegistry, -): (args: unknown) => void { - return (args: unknown): void => { +export function closeBrowseSessionHandler(registry: SshBrowseSessionRegistry) { + return (args: unknown) => { const { sessionId } = validateArgs(c.closeBrowseSession.args, args); registry.close(sessionId); + return ipcOk(undefined); }; } @@ -418,94 +423,3 @@ function closeBrowseSessionStub(): (args: unknown) => void { throw new Error("SSH browse session handler not registered"); }; } - -// --------------------------------------------------------------------------- -// Error helpers -// --------------------------------------------------------------------------- - -/** - * Walks the error cause chain to detect AuthCancelledError at any depth. - * User cancellation is a normal control-flow outcome, not a failure, so the - * caller must treat it differently from genuine authentication failures. - */ -function isAuthCancellation(error: unknown): boolean { - if (error instanceof AuthCancelledError) return true; - if (error instanceof Error && error.cause !== undefined) { - return isAuthCancellation(error.cause); - } - return false; -} - -/** - * Maps arbitrary errors from the agent channel or bootstrap to a typed SSH - * error with a sanitized message. Raw stderr is never forwarded. - * - * User-initiated cancellation (AuthCancelledError anywhere in the cause chain) - * is returned as ssh.auth-cancelled — no console.error, since it is expected. - * Truly unmapped errors are still logged for diagnosability. - */ -function mapToBrowseError(error: unknown): Error { - if (isAuthCancellation(error)) { - // Cancellation is a normal outcome — no noise in the console. - return createSshErrorObject("ssh.auth-cancelled"); - } - const code = sshErrorCodeFromError(error) ?? "ssh.unknown"; - if (code === "ssh.unknown") { - // The renderer only ever sees the sanitized code. Log the raw cause to - // the main-process console so an unmapped failure is still diagnosable. - log.error(`unmapped browse-session error: ${(error as Error).message}`); - } - return createSshErrorObject(code); -} - -function createSshErrorObject(code: SshErrorCode): Error & { code: SshErrorCode } { - // The `.code` property does not survive Electron's IPC error serialization - // (only name/message/stack cross the boundary), so we also embed the code in - // the message text. The renderer classifies the failure by matching the code - // substring in error.message (see humanizeSshError / extractSshErrorKind). - const err = new Error(`${messageForSshErrorCode(code)} [${code}]`) as Error & { - code: SshErrorCode; - }; - err.code = code; - return err; -} - -function sshErrorCodeFromError(error: unknown): SshErrorCode | undefined { - if (typeof error !== "object" || error === null || !("code" in error)) { - return undefined; - } - const rawCode = (error as { code?: unknown }).code; - // Agent filesystem failures surface domain codes (NOT_FOUND, …) that are not - // SSH codes. Map the ones with dedicated UX so a missing path is reported as - // "path not found" instead of the generic ssh.unknown. - if (rawCode === "NOT_FOUND") return "ssh.path-not-found"; - const parsed = SshErrorCodeSchema.safeParse(rawCode); - return parsed.success ? parsed.data : undefined; -} - -function messageForSshErrorCode(code: SshErrorCode): string { - switch (code) { - case "ssh.connect-failed": - return "SSH connection failed"; - case "ssh.auth-failed": - return "SSH authentication failed"; - case "ssh.auth-cancelled": - return "SSH authentication cancelled"; - case "ssh.session-expired": - return "SSH browse session expired"; - case "ssh.path-not-found": - return "Remote path not found"; - case "server.spawn-failed": - return "Remote agent failed to start"; - case "server.protocol-error": - return "Remote agent protocol error"; - case "server.protocol-version-mismatch": - return "Remote agent protocol version mismatch"; - case "ssh.unknown": - return "SSH workspace validation failed"; - case "transport.unknown": - return "Agent transport failed"; - case "transport.timeout": - return "Agent request timed out"; - } -} diff --git a/src/main/features/workspace/ipc.ts b/src/main/features/workspace/ipc.ts index aeac0d607..2e33659be 100644 --- a/src/main/features/workspace/ipc.ts +++ b/src/main/features/workspace/ipc.ts @@ -1,8 +1,8 @@ import { createAbortError, isAbortError, throwIfAborted } from "../../../shared/abort"; import { ipcContract } from "../../../shared/ipc/contract"; import { ipcErr, ipcOk } from "../../../shared/ipc/result"; -import { type SshErrorCode, SshErrorCodeSchema } from "../../../shared/ssh/errors"; -import { AuthCancelledError } from "../../infra/agent/ssh/auth-prompt"; +import type { SshErrorCode } from "../../../shared/ssh/errors"; +import { messageForSshErrorCode } from "../../infra/agent/pipe"; import { type CreateSshChannelOptions, createSshChannel, @@ -14,6 +14,7 @@ import { ensureRemoteAgent, } from "../../infra/agent/ssh/ssh-bootstrap/index"; import { type CallContext, register, validateArgs } from "../../infra/ipc-router"; +import { agentCallError, sshErrorCode } from "../../infra/ipc-router/agent-errors"; import type { SshBrowseSessionRegistry } from "../ssh/browse-session-registry"; import type { WorkspaceManager } from "./manager"; @@ -102,18 +103,8 @@ export function registerWorkspaceChannel( const meta = await manager.createAndConnectSsh(createArgs); return ipcOk(meta); } catch (error) { - // User-initiated cancellation (password dialog closed / signal aborted). - // Return a Result so the router passes through silently — no log. - if (isSshAuthCancellation(error) || isAbortError(error)) { - return ipcErr("cancelled", "SSH authentication cancelled"); - } - // Typed SSH failures (wrong credentials, host unreachable, …) — - // surface as auth-failed so the renderer can show a human message. - const code = sshErrorCodeFromError(error); - if (code) { - return ipcErr("auth-failed", messageForSshErrorCode(code), { code }); - } - // Unexpected bug — rethrow so the router logs it. + const expected = agentCallError(error, "auth-failed"); + if (expected) return expected; throw error; } }, @@ -157,18 +148,9 @@ function workspaceConnectionHandler(manager: WorkspaceManager, action: "activate await manager[action](id); return ipcOk(undefined); } catch (error) { - const code = sshErrorCodeFromError(error); - if (isSshAuthCancellation(error) || isAbortError(error) || code === "ssh.auth-cancelled") { - return ipcErr("cancelled", "Workspace connection cancelled", { category: "cancelled" }); - } - if (code !== undefined) { - return ipcErr("connection-failed", messageForSshErrorCode(code), { - category: "failed", - domain: "ssh", - code, - }); - } - return ipcErr("connection-failed", String(error), { category: "bug" }); + const expected = agentCallError(error, "connection-failed"); + if (expected) return expected; + throw error; } }; } @@ -251,65 +233,10 @@ export function testSshHandler( * Converts SSH transport and server failures to the public testSsh result. */ function sshFailureResult(error: unknown): TestSshResult { - const code = sshErrorCodeFromError(error) ?? "ssh.unknown"; + const code = sshErrorCode(error) ?? "ssh.unknown"; return { ok: false, code, message: messageForSshErrorCode(code), }; } - -/** - * Reads a stable SshErrorCode from errors without trusting arbitrary strings. - */ -function sshErrorCodeFromError(error: unknown): SshErrorCode | undefined { - if (typeof error !== "object" || error === null || !("code" in error)) { - return undefined; - } - - const parsed = SshErrorCodeSchema.safeParse((error as { code?: unknown }).code); - return parsed.success ? parsed.data : undefined; -} - -/** - * Maps SshErrorCode values to sanitized messages that never include stderr. - */ -function messageForSshErrorCode(code: SshErrorCode): string { - switch (code) { - case "ssh.connect-failed": - return "SSH connection failed"; - case "ssh.auth-failed": - return "SSH authentication failed"; - case "ssh.auth-cancelled": - return "SSH authentication cancelled"; - case "ssh.session-expired": - return "SSH browse session expired"; - case "ssh.path-not-found": - return "Remote path not found"; - case "server.spawn-failed": - return "Remote agent failed to start"; - case "server.protocol-error": - return "Remote agent protocol error"; - case "server.protocol-version-mismatch": - return "Remote agent protocol version mismatch"; - case "ssh.unknown": - return "SSH workspace validation failed"; - case "transport.unknown": - return "Agent transport failed"; - case "transport.timeout": - return "Agent request timed out"; - } -} - -/** - * Walks the error cause chain to detect user-initiated SSH authentication - * cancellations. AuthCancelledError can be wrapped inside a createSshError - * envelope by auth-pty, so the chain must be traversed recursively. - */ -function isSshAuthCancellation(error: unknown): boolean { - if (error instanceof AuthCancelledError) return true; - if (error instanceof Error && error.cause !== undefined) { - return isSshAuthCancellation(error.cause); - } - return false; -} diff --git a/src/main/features/wsl/ipc.ts b/src/main/features/wsl/ipc.ts index 0029990c4..d516f6ae4 100644 --- a/src/main/features/wsl/ipc.ts +++ b/src/main/features/wsl/ipc.ts @@ -3,11 +3,14 @@ // folder. The session joins the SSH browse sessions' registry, so // `ssh.browseSession` and `ssh.closeBrowseSession` serve it unchanged. +import { throwIfAborted } from "../../../shared/abort"; import { ipcContract } from "../../../shared/ipc/contract"; +import { type IpcResult, ipcErr, ipcOk } from "../../../shared/ipc/result"; import type { AgentChannel } from "../../infra/agent/channel"; import type { LspBootstrapProgressEvent } from "../../infra/agent/ssh/ssh-bootstrap/index"; import { createWslChannel, ensureWslAgent, listWslDistros } from "../../infra/agent/wsl"; -import { register, validateArgs } from "../../infra/ipc-router"; +import { type CallContext, register, validateArgs } from "../../infra/ipc-router"; +import { agentCallError } from "../../infra/ipc-router/agent-errors"; import type { SshBrowseSessionRegistry } from "../ssh/browse-session-registry"; import type { BrowseProgressBroadcast } from "../ssh/ipc"; @@ -27,7 +30,7 @@ export function registerWslChannel( const listDistros = dependencies.listDistros ?? listWslDistros; register("wsl", { call: { - listDistros: () => listDistros(), + listDistros: async () => ipcOk(await listDistros()), openBrowseSession: openWslBrowseSessionHandler(registry, broadcast, dependencies), }, listen: {}, @@ -43,10 +46,13 @@ export function openWslBrowseSessionHandler( registry: SshBrowseSessionRegistry, broadcast?: BrowseProgressBroadcast, dependencies: WslChannelDependencies = {}, -): (args: unknown) => Promise<{ sessionId: string; initialPath: string }> { +): ( + args: unknown, + ctx?: CallContext, +) => Promise> { const bootstrap = dependencies.bootstrap ?? ensureWslAgent; const createChannel = dependencies.createChannel ?? createWslChannel; - return async (args) => { + return async (args, ctx) => { const { distro, progressId } = validateArgs(c.openBrowseSession.args, args); const onProgress = progressId && broadcast @@ -62,21 +68,41 @@ export function openWslBrowseSessionHandler( : undefined; let channel: AgentChannel | null = null; + const signal = ctx?.signal; + const disposeChannel = () => { + channel?.dispose(); + channel = null; + }; try { - const result = await bootstrap({ distro, remotePath: "/" }, { onProgress }); + throwIfAborted(signal); + const result = await bootstrap( + { distro, remotePath: "/", ...(signal ? { signal } : {}) }, + { onProgress }, + ); + throwIfAborted(signal); channel = createChannel({ distro, remoteCommand: result.remoteCommand }); + signal?.addEventListener("abort", disposeChannel, { once: true }); await channel.ready; + throwIfAborted(signal); const sessionId = registry.register(channel, null); - return { sessionId, initialPath: result.remoteHome }; + return ipcOk({ sessionId, initialPath: result.remoteHome }); } catch (error) { - channel?.dispose(); - throw new Error(wslFailureMessage(error), { cause: error }); + disposeChannel(); + if (signal?.aborted) return ipcErr("cancelled", "Operation cancelled"); + const expected = agentCallError(error); + if (expected) { + if (expected.kind === "cancelled") return expected; + return { ...expected, domain: undefined, message: wslFailureMessage(error) }; + } + throw error; + } finally { + signal?.removeEventListener("abort", disposeChannel); } }; } /** - * What went wrong, for the dialog: a transport error's generic message hides + * Keeps diagnostic detail in the envelope for logging: the generic message hides * what wsl.exe said (an unknown distribution, WSL not installed), which it * carries as its cause. */ diff --git a/src/main/infra/agent/pipe.ts b/src/main/infra/agent/pipe.ts index a8b10fb85..83fd51b3d 100644 --- a/src/main/infra/agent/pipe.ts +++ b/src/main/infra/agent/pipe.ts @@ -824,7 +824,7 @@ export function createDisposedError(): Error { /** * Maps stable SSH error codes to non-sensitive caller-facing messages. */ -function messageForSshErrorCode(code: SshErrorCode): string { +export function messageForSshErrorCode(code: SshErrorCode): string { switch (code) { case "ssh.connect-failed": return "SSH connection failed"; diff --git a/src/main/infra/ipc-router/agent-errors.ts b/src/main/infra/ipc-router/agent-errors.ts new file mode 100644 index 000000000..13323298c --- /dev/null +++ b/src/main/infra/ipc-router/agent-errors.ts @@ -0,0 +1,50 @@ +import { type IpcErrResult, ipcErr } from "../../../shared/ipc/result"; +import { type SshErrorCode, SshErrorCodeSchema } from "../../../shared/ssh/errors"; +import { messageForSshErrorCode } from "../agent/pipe"; + +/** Reads a known SSH or agent transport code without exposing raw stderr. */ +export function sshErrorCode(error: unknown): SshErrorCode | undefined { + if (typeof error !== "object" || error === null || !("code" in error)) return; + const parsed = SshErrorCodeSchema.safeParse(error.code); + return parsed.success ? parsed.data : undefined; +} + +/** Recognizes cancellation even when the SSH transport wrapped the prompt error. */ +function isAuthCancellation(error: unknown): boolean { + const seen = new Set(); + while (error instanceof Error && !seen.has(error)) { + if (error.name === "AbortError" || error.name === "AuthCancelledError") return true; + seen.add(error); + error = error.cause; + } + return false; +} + +/** Envelopes expected agent failures while leaving unexpected exceptions to the router. */ +export function agentCallError( + error: unknown, + kind: "unavailable" | "auth-failed" | "connection-failed" = "unavailable", +): IpcErrResult | undefined { + const code = sshErrorCode(error); + if (code === "ssh.auth-cancelled" || isAuthCancellation(error)) { + return ipcErr("cancelled", "Operation cancelled", { + category: "cancelled", + ...(code ? { domain: "ssh", code } : {}), + }); + } + if (code) { + return ipcErr( + code === "ssh.session-expired" ? "session-expired" : kind, + messageForSshErrorCode(code), + { category: "failed", domain: "ssh", code }, + ); + } + if ( + error instanceof Error && + error.name === "AgentReconnectError" && + "code" in error && + typeof error.code === "string" + ) { + return ipcErr("unavailable", error.message, { category: "failed", code: error.code }); + } +} diff --git a/src/main/infra/ipc-router/index.ts b/src/main/infra/ipc-router/index.ts index 724904808..a5865fe42 100644 --- a/src/main/infra/ipc-router/index.ts +++ b/src/main/infra/ipc-router/index.ts @@ -1,7 +1,7 @@ import * as crypto from "node:crypto"; import type { WebContents } from "electron"; import type { z } from "zod"; -import { createAbortError, isAbortError } from "../../../shared/abort"; +import { createAbortError } from "../../../shared/abort"; import type { AppError } from "../../../shared/error/app-error"; import { IPC_GIT_ERROR_MARK, type IpcGitErrorPayload } from "../../../shared/git/error-ipc"; import { @@ -13,7 +13,12 @@ import { } from "../../../shared/ipc/contract"; import { PendingRequestMap } from "../../../shared/ipc/pending-request-map"; import { type IpcErrResult, ipcErr, isIpcErrResult } from "../../../shared/ipc/result"; +import { createLogger } from "../../../shared/log/main"; +import { fsErrorToIpcResult, isFsError } from "../../features/fs/ipc/fs-result"; import { GitError } from "../../features/git/domain/error"; +import { agentCallError } from "./agent-errors"; + +const log = createLogger("main"); export interface CallContext { requestId?: string; @@ -96,18 +101,7 @@ type RegisterChannelDef = C extends ContractChannelName ? RegisteredChannelDef : ChannelDef; -/** - * Thrown by `validateArgs` when the caller-supplied arguments fail Zod - * schema validation. The `ipc:call` router catches this error at the IPC - * boundary and converts it into an `IpcErrResult<"invalid-args">` with - * `category:"invalid-input"` so the renderer can branch on the result - * without catching exceptions. - * - * Handlers do not need to catch this error themselves — throwing it is the - * correct signal that propagates to the router-level conversion. Handlers - * that opt into the result-based API should use `isIpcErrResult` on the - * return value of `validateArgs` after T7 migration. - */ +/** Signals argument validation failure to the IPC boundary. */ export class IpcValidationError extends Error { readonly kind = "invalid-args" as const; readonly category = "invalid-input" as const; @@ -155,60 +149,35 @@ export function setupRouter(): void { args: unknown, requestId?: unknown, ) => { - const channel = channels.get(channelName); - if (!channel) throw new Error(`ipc:call — unknown channel: ${channelName}`); - const handler = channel.call[method]; - if (typeof handler !== "function") - throw new Error(`ipc:call — unknown method: ${channelName}.${method}`); + const methods = channels.get(channelName)?.call; + const handler = methods && Object.hasOwn(methods, method) ? methods[method] : undefined; + if (typeof handler !== "function") { + return ipcErr("invalid-args", `Unknown IPC call: ${channelName}.${method}`, { + category: "invalid-input", + }); + } const correlationId = crypto.randomUUID(); const callContext = createCallContext(event, requestId, correlationId); + const procedure = `${channelName}.${method}`; try { - const handlerResult = await handler(args, callContext.ctx); - if ( - isIpcErrResult(handlerResult) && - // `category` is an extension field set by `ipcErr(..., { category })` and - // is not declared on the base IpcErrResult interface; cast to access it. - (handlerResult as unknown as { category?: string }).category === "bug" - ) { - // Lazy-require avoids pulling electron into module scope at load time - // (shared/log/main imports electron.app which is unavailable in test env). - // The try-catch guards against module-cache mismatches in test workers - // where another file already loaded the real electron without app mocked. - try { - // eslint-disable-next-line @typescript-eslint/no-require-imports - const { createLogger } = - require("../../../shared/log/main") as typeof import("../../../shared/log/main"); - createLogger("main").error( - `ipc:call — bug result from ${channelName}.${method}: ${handlerResult.message}`, - { correlationId }, - ); - } catch { - /* logger unavailable — suppress to allow the IpcErrResult to be returned */ - } + const result = await handler(args, callContext.ctx); + if (isIpcErrResult(result) && result.category === "bug") { + return { + ...result, + ...reportCallBug(procedure, correlationId, result.message), + kind: result.kind, + }; } - return handlerResult; + return result; } catch (error) { if (error instanceof IpcValidationError) { - // Handler called validateArgs with invalid args — convert to IpcErrResult. - // This is the router-boundary enforcement: the renderer always receives - // a typed result rather than a raw rejection. - return ipcErr("invalid-args", error.message, { category: "invalid-input" as const }); + return ipcErr("invalid-args", error.message, { category: "invalid-input" }); } - if (isAbortError(error)) { - try { - // eslint-disable-next-line @typescript-eslint/no-require-imports - const { createLogger } = - require("../../../shared/log/main") as typeof import("../../../shared/log/main"); - createLogger("main").debug( - `ipc:call — cancelled ${channelName}.${method} req=${requestId ?? "(none)"}`, - { correlationId }, - ); - } catch { - /* logger unavailable — suppress */ - } - return ipcErr("cancelled", "operation cancelled"); - } - throw error; + if (isFsError(error)) return fsErrorToIpcResult(error); + const expected = agentCallError(error); + if (expected) return expected; + const detail = error instanceof Error ? (error.stack ?? error.message) : String(error); + return reportCallBug(procedure, correlationId, detail); } finally { if (callContext.key) pendingCallControllers.delete(callContext.key); } @@ -248,6 +217,12 @@ export function setupRouter(): void { ); } +/** Records the original detail while exposing only a correlation ID and safe message. */ +function reportCallBug(procedure: string, correlationId: string, detail: string): IpcErrResult { + log.error(`ipc:call — ${procedure}: ${detail}`, { correlationId }); + return ipcErr("bug", "An unexpected error occurred", { category: "bug", correlationId }); +} + function senderId(event: { sender?: { id?: number } }): string { return typeof event.sender?.id === "number" ? String(event.sender.id) : "unknown"; } @@ -488,28 +463,7 @@ export function broadcast(channelName: string, event: string, args: unknown): vo } } -/** - * Validate handler arguments against a Zod schema. - * - * On success returns the parsed (typed) value. On failure throws - * `IpcValidationError` — the `ipc:call` router catches this at the IPC - * boundary and converts it into an `IpcErrResult<"invalid-args">` with - * `category:"invalid-input"` so the renderer always receives a typed result. - * - * Handlers do not need to catch `IpcValidationError` themselves. Handlers - * that adopt the result-based API (T7 migration) should instead call this - * function and check `isIpcErrResult` on the return — until then the throw - * path is fully supported and backward-compatible with all existing handlers. - * - * @example - * // Legacy throw style (pre-T7): - * const { workspaceId, relPath } = validateArgs(c.readdir.args, args); - * - * // Result style (post-T7): - * const parsed = validateArgs(c.readdir.args, args); - * if (isIpcErrResult(parsed)) return parsed; - * const { workspaceId, relPath } = parsed; - */ +/** Parses handler arguments and lets the router envelope validation failures. */ export function validateArgs(schema: T, args: unknown): z.infer { const parsed = schema.safeParse(args); if (!parsed.success) { diff --git a/src/renderer/components/workspace/add-workspace/main-list-view.tsx b/src/renderer/components/workspace/add-workspace/main-list-view.tsx index fa2251a89..d2cafb994 100644 --- a/src/renderer/components/workspace/add-workspace/main-list-view.tsx +++ b/src/renderer/components/workspace/add-workspace/main-list-view.tsx @@ -11,6 +11,8 @@ import { import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import type { ConnectionProfile, FolderBookmark } from "../../../../shared/types/entry-points"; +import { normaliseError } from "../../../hooks/use-ipc-action"; +import { surfaceError } from "../../../services/error-surface/surface-error"; import { createLocalWorkspace, createSshWorkspace, @@ -28,12 +30,7 @@ import { Button } from "../../ui/button"; import { EmptyState } from "../../ui/empty-state"; import { Skeleton, SkeletonLine } from "../../ui/skeleton"; import { ErrorNotice } from "./error-notice"; -import { - folderName, - formatSshSecondaryLine, - formatSshTooltip, - humanizeSshError, -} from "./ssh-helpers"; +import { folderName, formatSshSecondaryLine, formatSshTooltip } from "./ssh-helpers"; import type { MainListViewProps } from "./types"; // --------------------------------------------------------------------------- @@ -158,10 +155,6 @@ export function MainListView({ }); if (!result.ok) { - // User cancelled the auth prompt — silently stop, no error banner. - if (result.kind === "cancelled") return; - // Typed SSH failure (wrong credentials, host unreachable, …); the - // result carries the SshErrorCode the humanizer maps. setError(bookmark.id, result, profile.id); return; } @@ -233,14 +226,8 @@ export function MainListView({ // ── Error helpers ───────────────────────────────────────────────────────── function setError(bookmarkId: string | null, error: unknown, profileId: string | null): void { - // SSH reconnect failures (profileId set) are humanised so raw SshErrorCode - // strings never reach the UI. Opening a local folder only fails inside - // the IPC layer, whose message is internal, so it gets a generic one. - showError( - bookmarkId, - profileId !== null ? humanizeSshError(error) : t("workspace.could_not_open"), - profileId, - ); + const surface = surfaceError(normaliseError(error), { surface: "inline" }); + if (surface.surface === "inline") showError(bookmarkId, surface.userMessage, profileId); } function showError(bookmarkId: string | null, message: string, profileId: string | null): void { diff --git a/src/renderer/components/workspace/add-workspace/ssh-connection-list-view.tsx b/src/renderer/components/workspace/add-workspace/ssh-connection-list-view.tsx index f66043f7b..47dea2661 100644 --- a/src/renderer/components/workspace/add-workspace/ssh-connection-list-view.tsx +++ b/src/renderer/components/workspace/add-workspace/ssh-connection-list-view.tsx @@ -3,6 +3,8 @@ import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import type { ConnectionProfile } from "../../../../shared/types/entry-points"; import type { SshBrowseProgressEvent } from "../../../../shared/types/workspace"; +import { normaliseError } from "../../../hooks/use-ipc-action"; +import { surfaceError } from "../../../services/error-surface/surface-error"; import { listConnectionProfiles, openSshBrowseSession, @@ -14,7 +16,7 @@ import { EmptyState } from "../../ui/empty-state"; import { Skeleton, SkeletonLine } from "../../ui/skeleton"; import { BootstrapProgressBar } from "../bootstrap-progress-bar"; import { ErrorNotice } from "./error-notice"; -import { formatProfileSubtitle, humanizeSshError } from "./ssh-helpers"; +import { formatProfileSubtitle } from "./ssh-helpers"; import type { SshBrowseSession, SshConnectionListViewProps } from "./types"; import { useBrowseProgress } from "./use-browse-progress"; @@ -76,10 +78,14 @@ export function SshConnectionListView({ setConnectingId(profile.id); setErrorId(null); setErrorHuman(null); + const presentError = (error: unknown) => { + const surface = surfaceError(normaliseError(error), { surface: "inline" }); + if (surface.surface === "inline") { + setErrorId(profile.id); + setErrorHuman(surface.userMessage); + } + }; try { - // openBrowseSession is migrated to the IpcResult contract — auth - // cancellation arrives as ipcErr("cancelled") so the router stays silent - // and the renderer branches without showing an error banner. const result = await openSshBrowseSession({ host: profile.host, user: profile.user, @@ -89,10 +95,7 @@ export function SshConnectionListView({ progressId: beginProgress(), }); if (!result.ok) { - // User cancelled the SSH auth prompt — silent stop, no error banner. - if (result.kind === "cancelled") return; - setErrorId(profile.id); - setErrorHuman(humanizeSshError(result)); + presentError(result); return; } // Update usage record @@ -116,6 +119,8 @@ export function SshConnectionListView({ connectionProfileId: profile.id, }; onConnected(session); + } catch (error) { + presentError(error); } finally { setConnectingId(null); clearProgress(); diff --git a/src/renderer/components/workspace/add-workspace/ssh-directory-picker-view.tsx b/src/renderer/components/workspace/add-workspace/ssh-directory-picker-view.tsx index 543d5c3d0..37bca9977 100644 --- a/src/renderer/components/workspace/add-workspace/ssh-directory-picker-view.tsx +++ b/src/renderer/components/workspace/add-workspace/ssh-directory-picker-view.tsx @@ -2,7 +2,10 @@ import { ChevronRight, CornerLeftUp, Folder } from "lucide-react"; import type { FormEvent } from "react"; import { useCallback, useEffect, useImperativeHandle, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; +import type { AppError } from "../../../../shared/error/app-error"; import type { DirEntry } from "../../../../shared/fs/types"; +import { normaliseError } from "../../../hooks/use-ipc-action"; +import { surfaceError } from "../../../services/error-surface/surface-error"; import { browseSshSession, closeSshBrowseSession, @@ -14,7 +17,6 @@ import { import { EmptyState } from "../../ui/empty-state"; import { Skeleton, SkeletonLine } from "../../ui/skeleton"; import { ErrorNotice } from "./error-notice"; -import { humanizeSshError } from "./ssh-helpers"; import type { SshDirectoryPickerViewProps } from "./types"; import { type BrowseCacheEntry, usePathAutocomplete } from "./use-path-autocomplete"; @@ -58,14 +60,10 @@ function parentPath(path: string): string { return clean.slice(0, idx); } -/** Extract SSH error kind from an IPC error. */ -function extractSshErrorKind(error: unknown): BrowseErrorKind { - if (!(error instanceof Error)) return "retryable"; - const msg = error.message; - if (msg.includes("ssh.path-not-found")) return "path-not-found"; - for (const code of SESSION_FATAL_CODES) { - if (msg.includes(code)) return "session-expired"; - } +/** Selects a recovery action from the browse error's typed code. */ +function browseErrorKindFor(error: AppError): BrowseErrorKind { + if (error.code === "ssh.path-not-found") return "path-not-found"; + if (error.code && SESSION_FATAL_CODES.has(error.code)) return "session-expired"; return "retryable"; } @@ -143,29 +141,36 @@ export function SshDirectoryPickerView({ setBrowseErrorHuman(null); setBrowseErrorKind(null); + const presentError = (error: unknown) => { + const appError = normaliseError(error); + const surface = surfaceError(appError, { surface: "inline" }); + if (surface.surface !== "inline") return; + const kind = browseErrorKindFor(appError); + if (kind === "path-not-found") { + setPathErrorHuman(surface.userMessage); + } else { + setBrowseErrorHuman(surface.userMessage); + setBrowseErrorKind(kind); + } + }; + try { const result = await browseSshSession(sessionId, path); if (abortSignal?.aborted) return; + if (!result.ok) { + presentError(result); + return; + } - browseCache.current.set(path, { entries: result.entries, truncated: result.truncated }); + browseCache.current.set(path, result.value); setCurrentPath(path); - setEntries(result.entries); - setTruncated(result.truncated); + setEntries(result.value.entries); + setTruncated(result.value.truncated); setBrowseErrorHuman(null); setBrowseErrorKind(null); setPathErrorHuman(null); } catch (error) { - if (abortSignal?.aborted) return; - const kind = extractSshErrorKind(error); - if (kind === "path-not-found") { - // Non-destructive: the typed path is missing, but the previous listing - // (currentPath/entries) is untouched. Surface the error inline by the - // path bar and leave the tree on screen. - setPathErrorHuman(humanizeSshError(error)); - } else { - setBrowseErrorHuman(humanizeSshError(error)); - setBrowseErrorKind(kind); - } + if (!abortSignal?.aborted) presentError(error); } finally { if (!abortSignal?.aborted) setListLoading(false); } @@ -299,10 +304,7 @@ export function SshDirectoryPickerView({ if (!result.ok) { setAddPhase("idle"); - // User cancelled the auth prompt — silent stop, no error banner. - if (result.kind === "cancelled") return; - // Auth failure after the browse session — surface error. - setAddErrorHuman(humanizeSshError(result)); + presentAddError(result); return; } @@ -319,11 +321,17 @@ export function SshDirectoryPickerView({ await onWorkspaceCreated(result.value); onClose(); } catch (error) { - setAddErrorHuman(humanizeSshError(error)); + presentAddError(error); setAddPhase("idle"); } } + /** Presents an add failure once, beside the picker when it can be retried there. */ + function presentAddError(error: unknown): void { + const surface = surfaceError(normaliseError(error), { surface: "inline" }); + setAddErrorHuman(surface.surface === "inline" ? surface.userMessage : null); + } + // A WSL workspace needs no connection handoff: the distribution is reached // through wsl.exe again. It records no bookmark (bookmarks are local or SSH). async function addWslWorkspace(distro: string): Promise { @@ -331,13 +339,13 @@ export function SshDirectoryPickerView({ const result = await createWslWorkspace({ distro, remotePath: currentPath }); if (!result.ok) { setAddPhase("idle"); - setAddErrorHuman(result.message); + presentAddError(result); return; } await onWorkspaceCreated(result.value); onClose(); } catch (error) { - setAddErrorHuman(error instanceof Error ? error.message : String(error)); + presentAddError(error); setAddPhase("idle"); } } diff --git a/src/renderer/components/workspace/add-workspace/ssh-helpers.ts b/src/renderer/components/workspace/add-workspace/ssh-helpers.ts index 9c3182089..39c87384f 100644 --- a/src/renderer/components/workspace/add-workspace/ssh-helpers.ts +++ b/src/renderer/components/workspace/add-workspace/ssh-helpers.ts @@ -2,7 +2,6 @@ // Pure SSH utility functions — exported for unit tests. // --------------------------------------------------------------------------- -import i18next from "i18next"; import type { SshConfigHost } from "./types"; export function parseSshDestination(input: string): { host: string; user?: string } | null { @@ -90,54 +89,6 @@ export function formatProfileSubtitle(profile: { return `${userPrefix}${profile.host}${portSuffix}`; } -// --------------------------------------------------------------------------- -// SSH error humanisation -// --------------------------------------------------------------------------- - -/** - * Maps an SSH failure to human-readable cause + recovery sentences: an Error - * whose message embeds the SshErrorCode string, or an `ipcErr` result that - * carries the code in its `code` field. - * raw error.message is never surfaced directly in UI. - */ -export function humanizeSshError(error: unknown): string { - const t = i18next.t.bind(i18next); - if (typeof error !== "object" || error === null) { - return t("common:ssh.error.unknown_error"); - } - const { code, message } = error as { code?: unknown; message?: unknown }; - if (typeof code !== "string" && !(error instanceof Error)) { - return t("common:ssh.error.unknown_error"); - } - const msg = `${typeof code === "string" ? code : ""} ${typeof message === "string" ? message : ""}`; - if (msg.includes("ssh.connect-failed")) { - return t("common:ssh.error.connect_failed"); - } - if (msg.includes("ssh.auth-failed")) { - return t("common:ssh.error.auth_failed"); - } - if (msg.includes("ssh.session-expired")) { - return t("common:ssh.error.session_expired"); - } - if (msg.includes("ssh.path-not-found")) { - return t("common:ssh.error.path_not_found"); - } - if (msg.includes("server.spawn-failed")) { - return t("common:ssh.error.spawn_failed"); - } - if (msg.includes("server.protocol-version-mismatch")) { - return t("common:ssh.error.protocol_version_mismatch"); - } - if (msg.includes("server.protocol-error")) { - return t("common:ssh.error.protocol_error"); - } - if (msg.includes("transport.unknown") || msg.includes("ssh.unknown")) { - return t("common:ssh.error.ssh_unknown"); - } - // Fallback — intentionally generic, no raw message leak - return t("common:ssh.error.connection_failed"); -} - // --------------------------------------------------------------------------- // Path helpers // --------------------------------------------------------------------------- diff --git a/src/renderer/components/workspace/add-workspace/ssh-new-connection-view.tsx b/src/renderer/components/workspace/add-workspace/ssh-new-connection-view.tsx index 159068536..fea78ced5 100644 --- a/src/renderer/components/workspace/add-workspace/ssh-new-connection-view.tsx +++ b/src/renderer/components/workspace/add-workspace/ssh-new-connection-view.tsx @@ -4,8 +4,10 @@ import type { FormEvent, KeyboardEvent } from "react"; import { useEffect, useMemo, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { isImeComposing } from "@/utils/ime"; -import { appErrorCancelled, appErrorFailed } from "../../../../shared/error/app-error"; +import { appErrorFailed } from "../../../../shared/error/app-error"; +import { ipcErrorToAppError } from "../../../../shared/ipc/result"; import { useIpcAction } from "../../../hooks/use-ipc-action"; +import { surfaceError } from "../../../services/error-surface/surface-error"; import { closeSshBrowseSession, openSshBrowseSession, @@ -20,7 +22,6 @@ import { filterSshConfigHosts, findSshConfigHost, formatSshHostSummary, - humanizeSshError, parseSshDestination, parseSshPort, sshHostOptionId, @@ -306,9 +307,6 @@ export function SshNewConnectionView({ runConnect(async (signal) => { // --- Stage 1: primary effect — establish SSH browse session --- - // openBrowseSession is migrated to the IpcResult contract. - // auth cancellation arrives as ipcErr("cancelled") so we throw an - // AppError category:"cancelled" and the hook silently returns to idle. // Keep receiving the result after cancellation so a session created // by main can be closed even when the view has already gone away. const result = await openSshBrowseSession({ @@ -320,16 +318,7 @@ export function SshNewConnectionView({ progressId: beginProgress(), }); - if (!result.ok) { - if (result.kind === "cancelled") { - // Auth prompt dismissed by the user — throw category:'cancelled' so the - // hook routes this to idle without surfacing any error UI. - throw appErrorCancelled("SSH authentication was cancelled.", { domain: "ssh" }); - } - // Connection failure → throw so the hook transitions to state:'error'. - // The inline banner below renders state.error.message. - throw appErrorFailed(humanizeSshError(result), { domain: "ssh", code: result.kind }); - } + if (!result.ok) throw ipcErrorToAppError(result); // `result.value.user` is the user actually connected as — when the form // had only a host, the main process resolved it to the local account name, @@ -428,9 +417,15 @@ export function SshNewConnectionView({ const connecting = connectState.status === "loading"; - // Inline error message for connection failures. - // Cancelled (state:'idle') and save failures (surfaced as toast) do not reach here. - const inlineError = connectState.status === "error" ? connectState.error.message : null; + const [inlineError, setInlineError] = useState(null); + useEffect(() => { + if (connectState.status !== "error") { + setInlineError(null); + return; + } + const surface = surfaceError(connectState.error, { surface: "inline" }); + setInlineError(surface.surface === "inline" ? surface.userMessage : null); + }, [connectState]); return (
(null); - const [connecting, setConnecting] = useState(null); - const [error, setError] = useState<{ distro: string; message: string } | null>(null); + const [selected, setSelected] = useState(null); + const [errorMessage, setErrorMessage] = useState(null); + const { state, run, isPending } = useIpcAction(); + const connecting = isPending ? selected : null; const { progress, begin: beginProgress, clear: clearProgress } = useBrowseProgress(); useEffect(() => { @@ -36,19 +45,30 @@ export function WslDistroListView({ onConnected }: WslDistroListViewProps): Reac }; }, []); - async function connect(distro: string): Promise { - if (connecting) return; - setConnecting(distro); - setError(null); - try { - const session = await openWslBrowseSession(distro, beginProgress()); - onConnected({ ...session, distro }); - } catch (err) { - setError({ distro, message: err instanceof Error ? err.message : String(err) }); - } finally { - clearProgress(); - setConnecting(null); - } + useEffect(() => { + if (state.status !== "error") return; + const surface = surfaceError(state.error, { surface: "inline" }); + if (surface.surface === "inline") setErrorMessage(surface.userMessage); + }, [state]); + + /** Starts one distribution and surfaces any failed attempt beside its row. */ + function connect(distro: string): void { + if (isPending) return; + setSelected(distro); + setErrorMessage(null); + run(async (signal) => { + try { + const result = await openWslBrowseSession(distro, beginProgress(), signal); + if (!result.ok) throw ipcErrorToAppError(result); + if (signal.aborted) { + void closeSshBrowseSession(result.value.sessionId); + return; + } + onConnected({ ...result.value, distro }); + } finally { + clearProgress(); + } + }); } if (distros === null) { @@ -77,7 +97,7 @@ export function WslDistroListView({ onConnected }: WslDistroListViewProps): Reac
    {distros.map((distro) => { const isConnecting = connecting === distro; - const errorMessage = error?.distro === distro ? error.message : null; + const rowError = selected === distro ? errorMessage : null; return (
  • - {errorMessage ? ( + {rowError ? ( diff --git a/src/renderer/hooks/use-ipc-action.ts b/src/renderer/hooks/use-ipc-action.ts index 6e9ea7df6..2148b59b6 100644 --- a/src/renderer/hooks/use-ipc-action.ts +++ b/src/renderer/hooks/use-ipc-action.ts @@ -52,6 +52,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { isAbortError } from "../../shared/abort"; import { type AppError, appErrorBug, appErrorCancelled } from "../../shared/error/app-error"; +import { ipcErrorToAppError, isIpcErrResult } from "../../shared/ipc/result"; // --------------------------------------------------------------------------- // State type — discriminated union covering all four lifecycle phases @@ -296,6 +297,8 @@ export function isAppError(value: unknown): value is AppError { * Exported so tests can verify normalisation rules without mounting a hook. */ export function normaliseError(err: unknown): AppError { + if (isIpcErrResult(err)) return ipcErrorToAppError(err); + if (isAbortError(err)) return appErrorCancelled(err.message); if (isAppError(err)) return err; if (err instanceof Error) { diff --git a/src/renderer/ipc/client.ts b/src/renderer/ipc/client.ts index 0c962e0b7..ba3858144 100644 --- a/src/renderer/ipc/client.ts +++ b/src/renderer/ipc/client.ts @@ -6,6 +6,7 @@ import { type IpcOkResult, type IpcResult, type IpcResultKind, + ipcErrorToAppError, isIpcErrResult, isIpcOkResult, isIpcResult, @@ -140,8 +141,7 @@ export function unwrapIpcResult(result: IpcResult): T { if (result.ok) return result.value; const err = new Error(result.message); err.name = `IpcError[${result.kind}]`; - (err as unknown as Record)["kind"] = result.kind; - throw err; + throw Object.assign(err, ipcErrorToAppError(result), { kind: result.kind }); } /** @@ -194,11 +194,7 @@ export function unwrapGitResult(result: IpcResult): T { }); throw error; } - // Other expected failures: throw a generic IpcError. - const err = new Error(result.message); - err.name = `IpcError[${result.kind}]`; - (err as unknown as Record)["kind"] = result.kind; - throw err; + return unwrapIpcResult(result); } // Re-export result type utilities so renderer code only needs to import from diff --git a/src/renderer/services/error-surface/surface-error.ts b/src/renderer/services/error-surface/surface-error.ts index f50872207..437fc094f 100644 --- a/src/renderer/services/error-surface/surface-error.ts +++ b/src/renderer/services/error-surface/surface-error.ts @@ -160,7 +160,7 @@ function buildInvalidInputMessage(error: AppError): string { return i18next.t("errors:generic.invalid-input"); } -/** Friendly message for failed errors with fs / git code awareness. */ +/** Friendly message for failed errors with domain-specific recovery copy. */ function buildFailedMessage(error: AppError): string { if (error.code === "terminal-input-failed") return i18next.t("errors:terminal.inputFailed"); if (error.domain === "fs" && error.code) { @@ -169,9 +169,37 @@ function buildFailedMessage(error: AppError): string { if (error.domain === "git" && error.code) { return gitCodeToUserMessage(error.code) ?? i18next.t("errors:generic.failed"); } + if (error.domain === "ssh") { + return sshCodeToUserMessage(error.code); + } return i18next.t("errors:generic.failed"); } +/** Maps SSH codes to the existing localized connection and picker copy. */ +function sshCodeToUserMessage(code: string | undefined): string { + switch (code) { + case "ssh.connect-failed": + return i18next.t("common:ssh.error.connect_failed"); + case "ssh.auth-failed": + return i18next.t("common:ssh.error.auth_failed"); + case "ssh.session-expired": + return i18next.t("common:ssh.error.session_expired"); + case "ssh.path-not-found": + return i18next.t("common:ssh.error.path_not_found"); + case "server.spawn-failed": + return i18next.t("common:ssh.error.spawn_failed"); + case "server.protocol-version-mismatch": + return i18next.t("common:ssh.error.protocol_version_mismatch"); + case "server.protocol-error": + return i18next.t("common:ssh.error.protocol_error"); + case "transport.unknown": + case "ssh.unknown": + return i18next.t("common:ssh.error.ssh_unknown"); + default: + return i18next.t("common:ssh.error.connection_failed"); + } +} + /** * Maps FsErrorCode strings to localised user-facing phrases via the errors * namespace (errors:fs.). i18next.t is evaluated at call time so that diff --git a/src/renderer/services/fs-mutations/errors.ts b/src/renderer/services/fs-mutations/errors.ts index dbfc9e81b..9c8db36da 100644 --- a/src/renderer/services/fs-mutations/errors.ts +++ b/src/renderer/services/fs-mutations/errors.ts @@ -11,6 +11,8 @@ import i18next from "i18next"; import { showToast } from "@/components/ui/toast"; import { FS_ERROR, hasFsErrorCode } from "../../../shared/fs/errors"; +import { isAppError } from "../../hooks/use-ipc-action"; +import { surfaceError } from "../error-surface/surface-error"; export interface FsToastMessages { /** Generic fallback when no code matches. */ @@ -32,6 +34,12 @@ export interface FsToastMessages { } export function toFsToast(error: unknown, msgs: FsToastMessages): void { + // Structured transport and bug outcomes use the common policy; keep the + // existing file-operation copy and warning severity for domain FsErrorCode. + if (isAppError(error) && (error.category !== "failed" || error.domain !== "fs")) { + surfaceError(error, { surface: "auto" }); + return; + } if (hasFsErrorCode(error, FS_ERROR.ALREADY_EXISTS)) { showToast({ kind: "error", diff --git a/src/renderer/services/workspace/ssh-browse.ts b/src/renderer/services/workspace/ssh-browse.ts index e60147b6b..656d22a69 100644 --- a/src/renderer/services/workspace/ssh-browse.ts +++ b/src/renderer/services/workspace/ssh-browse.ts @@ -6,9 +6,10 @@ */ import type { DirEntry } from "../../../shared/fs/types"; +import { ipcOk } from "../../../shared/ipc/result"; import type { SshBrowseProgressEvent } from "../../../shared/types/workspace"; import type { IpcResult } from "../../ipc/client"; -import { ipcCallResult, ipcListen, unwrapIpcResult } from "../../ipc/client"; +import { ipcCallResult, ipcListen } from "../../ipc/client"; // --------------------------------------------------------------------------- // Open browse session @@ -80,17 +81,18 @@ export interface BrowseSessionResult { /** * List the directory at `path` within an existing browse session. * Returns only directory and symlink entries, sorted alphabetically. - * Throws on IPC error (caller handles retries / error state). + * Returns the error envelope for callers that offer reconnect or retry. */ export async function browseSshSession( sessionId: string, path: string, -): Promise { - const result = unwrapIpcResult(await ipcCallResult("ssh", "browseSession", { sessionId, path })); - const dirs = result.entries +): Promise> { + const result = await ipcCallResult("ssh", "browseSession", { sessionId, path }); + if (!result.ok) return result; + const dirs = result.value.entries .filter((e) => e.type === "dir" || e.type === "symlink") .sort((a, b) => a.name.localeCompare(b.name)); - return { entries: dirs, truncated: result.truncated }; + return ipcOk({ entries: dirs, truncated: result.value.truncated }); } /** @@ -102,7 +104,8 @@ export async function prefetchSshDirectory( path: string, ): Promise { try { - return await browseSshSession(sessionId, path); + const result = await browseSshSession(sessionId, path); + return result.ok ? result.value : null; } catch { return null; } diff --git a/src/renderer/services/workspace/wsl.ts b/src/renderer/services/workspace/wsl.ts index f0cef61ed..26635b821 100644 --- a/src/renderer/services/workspace/wsl.ts +++ b/src/renderer/services/workspace/wsl.ts @@ -18,14 +18,14 @@ export async function listWslDistros(): Promise { /** * Start the agent in `distro` for the folder picker. `progressId` keys its - * install progress on `ssh.browseProgress`. Throws with what wsl.exe said - * when the distribution cannot start. + * install progress on `ssh.browseProgress`. Returns failures in the IPC envelope. */ export async function openWslBrowseSession( distro: string, progressId?: string, -): Promise<{ sessionId: string; initialPath: string }> { - return unwrapIpcResult(await ipcCallResult("wsl", "openBrowseSession", { distro, progressId })); + signal?: AbortSignal, +): Promise> { + return ipcCallResult("wsl", "openBrowseSession", { distro, progressId }, { signal }); } /** Create a workspace on `remotePath` inside `distro` and connect it. */ diff --git a/src/shared/ipc/result.ts b/src/shared/ipc/result.ts index 82e971b0b..55bd99b21 100644 --- a/src/shared/ipc/result.ts +++ b/src/shared/ipc/result.ts @@ -7,11 +7,10 @@ * A handler that encounters an *expected* failure (one that a caller can react * to, e.g. "not found", "auth failed") returns an IpcResult object instead of * throwing. The ipc:call router detects the envelope via `isIpcResult` and - * passes it through to the renderer without logging anything — the invariant - * "a log line means a real bug" is therefore preserved. + * passes expected failures through to the renderer without logging them. * - * Handlers that encounter *unexpected* failures (bugs) still throw; the router - * logs those and rejects the renderer-side promise. + * The router logs unexpected failures and returns a sanitized bug envelope + * with the same correlation ID. * * BRAND KEY * --------- @@ -21,14 +20,10 @@ * properties. The UUID suffix prevents accidental collision with normal * domain objects that happen to carry an `ok` field. * - * MIGRATION - * --------- - * This file is the T1 foundation. T2–T4 will migrate individual channel - * handlers onto this contract. Until a handler is migrated its existing - * throw/sentinel/GitError path is preserved by the router; the two paths - * co-exist without conflict. */ +import type { AppError } from "../error/app-error"; + // --------------------------------------------------------------------------- // Brand // --------------------------------------------------------------------------- @@ -45,8 +40,6 @@ export const IPC_RESULT_BRAND = "__nexusIpcResult_a3f8b1d2" as const; * renderer. Handlers MAY extend this union in domain-specific types; the * router passes any IpcResult through regardless of the kind value, so new * kinds can be introduced in handler code without touching the router. - * - * Add new kinds here as additional channels are migrated in T2–T4. */ export type IpcResultKind = | "not-found" @@ -83,6 +76,10 @@ export interface IpcErrResult { readonly ok: false; readonly kind: K; readonly message: string; + readonly category?: AppError["category"]; + readonly domain?: AppError["domain"]; + readonly code?: string; + readonly correlationId?: string; } /** @@ -181,3 +178,15 @@ export function ipcResultKindToCategory( if (kind === "invalid-args") return "invalid-input"; return "failed"; } + +/** Restores structured call errors for the renderer's shared presentation policy. */ +export function ipcErrorToAppError(error: IpcErrResult): AppError { + const { category, domain, code, correlationId, message } = error; + return { + category: category ?? ipcResultKindToCategory(error.kind), + domain, + code, + correlationId, + message, + }; +} diff --git a/tests/integration/ipc-roundtrip.test.ts b/tests/integration/ipc-roundtrip.test.ts index 3fd33f65a..817b8abec 100644 --- a/tests/integration/ipc-roundtrip.test.ts +++ b/tests/integration/ipc-roundtrip.test.ts @@ -13,6 +13,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { z } from "zod"; +import { mainErrorMock } from "../log-test-spies"; // --------------------------------------------------------------------------- // Fake Electron harness @@ -196,18 +197,136 @@ describe("ipc round-trip — broadcast reaches listener", () => { // --------------------------------------------------------------------------- describe("ipc round-trip — routing errors", () => { - it("rejects calls to an unknown channel", async () => { + it("returns invalid input for an unknown channel or method", async () => { const handler = getHandler(); - await expect(handler({}, "no-such-channel", "someMethod", {})).rejects.toThrow( - "unknown channel: no-such-channel", - ); + for (const [channel, method] of [ + ["no-such-channel", "someMethod"], + ["integration-echo", "noSuchMethod"], + ["integration-echo", "constructor"], + ]) { + expect(await handler({}, channel, method, {})).toMatchObject({ + ok: false, + kind: "invalid-args", + category: "invalid-input", + }); + } }); - it("rejects calls to an unknown method on a registered channel", async () => { - const handler = getHandler(); - await expect(handler({}, "integration-echo", "noSuchMethod", {})).rejects.toThrow( - "unknown method: integration-echo.noSuchMethod", + it("returns a sanitized bug envelope and logs the original exception with its correlation ID", async () => { + const detail = "unexpected internal failure /private/source"; + register("integration-bug", { + call: { work: () => Promise.reject(new Error(detail)) }, + listen: {}, + }); + const start = mainErrorMock.mock.calls.length; + const result = await getHandler()({}, "integration-bug", "work", {}); + expect(result).toMatchObject({ + ok: false, + kind: "bug", + category: "bug", + correlationId: expect.any(String), + }); + expect(JSON.stringify(result)).not.toContain(detail); + expect(mainErrorMock.mock.calls.slice(start)).toEqual([ + [ + expect.stringContaining(detail), + { correlationId: (result as { correlationId: string }).correlationId }, + ], + ]); + }); + + it("maps workspace activation and connection failures through the call envelope", async () => { + const { registerWorkspaceChannel } = await import("../../src/main/features/workspace/ipc"); + const id = "123e4567-e89b-12d3-a456-426614174000"; + let name: string | null = "Workspace"; + let failure: unknown; + const run = async () => { + throw failure; + }; + registerWorkspaceChannel({ getName: () => name, activate: run, connect: run } as never); + const invoke = (method: string) => getHandler()({}, "workspace", method, { id }); + + name = null; + expect(await invoke("activate")).toMatchObject({ + ok: false, + kind: "not-found", + category: "failed", + }); + name = "Workspace"; + failure = Object.assign(new Error("raw SSH detail"), { code: "ssh.auth-failed" }); + expect(await invoke("connect")).toMatchObject({ + ok: false, + kind: "connection-failed", + category: "failed", + domain: "ssh", + code: "ssh.auth-failed", + message: "SSH authentication failed", + }); + failure = Object.assign(new Error("interrupted"), { name: "AbortError" }); + expect(await invoke("activate")).toMatchObject({ + ok: false, + kind: "cancelled", + category: "cancelled", + }); + failure = new Error("unexpected connection internals"); + expect(await invoke("connect")).toMatchObject({ + ok: false, + kind: "bug", + correlationId: expect.any(String), + message: "An unexpected error occurred", + }); + }); + + it("returns a recoverable SSH browse error after the session closes", async () => { + const { browseSessionHandler } = await import("../../src/main/features/ssh/ipc"); + const { SshBrowseSessionRegistry } = await import( + "../../src/main/features/ssh/browse-session-registry" ); + const registry = new SshBrowseSessionRegistry(); + const sessionId = registry.register({ dispose: () => {} } as never, null); + registry.close(sessionId); + register("integration-browse", { call: { list: browseSessionHandler(registry) }, listen: {} }); + try { + expect( + await getHandler()({}, "integration-browse", "list", { sessionId, path: "/" }), + ).toMatchObject({ + ok: false, + kind: "session-expired", + category: "failed", + domain: "ssh", + code: "ssh.session-expired", + }); + } finally { + registry.dispose(); + } + }); + + it("returns typed transport failures from FS watch and write provider startup", async () => { + const { watchHandler } = await import("../../src/main/features/fs/ipc/watch-handlers"); + const { writeFileHandler } = await import("../../src/main/features/fs/ipc/write-handlers"); + const offline = async () => { + throw Object.assign(new Error("timed out"), { code: "transport.timeout" }); + }; + register("integration-fs-transport", { + call: { + watch: watchHandler({ watch: offline } as never), + write: writeFileHandler({ getFs: offline } as never), + }, + listen: {}, + }); + const args = { + workspaceId: "123e4567-e89b-12d3-a456-426614174000", + relPath: "a", + content: "new", + expected: { exists: false }, + }; + for (const method of ["watch", "write"]) { + expect(await getHandler()({}, "integration-fs-transport", method, args)).toMatchObject({ + ok: false, + category: "failed", + code: "transport.timeout", + }); + } }); }); diff --git a/tests/unit/main/pty/ipc-shell-choice.test.ts b/tests/unit/main/pty/ipc-shell-choice.test.ts index 6a2fc4b19..c6103636f 100644 --- a/tests/unit/main/pty/ipc-shell-choice.test.ts +++ b/tests/unit/main/pty/ipc-shell-choice.test.ts @@ -129,10 +129,9 @@ function setup(opts: { const handler = calls.filter(([channel]) => channel === "ipc:call").at(-1)?.[1]; if (!handler) throw new Error("ipc:call was not registered"); return { - // Handlers return either a plain value (spawn) or an IpcResult. + // Unwrap success values while keeping error envelopes available to assertions. call: async (method, args) => { const result = (await handler({}, "pty", method, args)) as { ok?: boolean; value?: unknown }; - if (result.ok === false) throw new Error(JSON.stringify(result)); return result.ok === true ? result.value : result; }, agent, @@ -330,9 +329,12 @@ describe("pty.spawn — a terminal opened for an agent profile", () => { test("one that is not there fails: never the default folder in its place", async () => { const { call, agent } = setup({ profileEnv }); - await expect(call("spawn", spawnArgs({ profile: "codex-gone" }))).rejects.toThrow( - /no profile codex-gone/, - ); + expect(await call("spawn", spawnArgs({ profile: "codex-gone" }))).toMatchObject({ + ok: false, + kind: "not-found", + category: "failed", + message: "no profile codex-gone", + }); expect(agent.spawnCalls).toEqual([]); }); }); diff --git a/tests/unit/main/wsl/ipc.test.ts b/tests/unit/main/wsl/ipc.test.ts index 0d2e84379..937c9d03c 100644 --- a/tests/unit/main/wsl/ipc.test.ts +++ b/tests/unit/main/wsl/ipc.test.ts @@ -43,7 +43,9 @@ describe("wsl.openBrowseSession", () => { createChannel: createChannel as never, }); - const { sessionId, initialPath } = await open({ distro: "Ubuntu", progressId: "p1" }); + const result = await open({ distro: "Ubuntu", progressId: "p1" }); + if (!result.ok) throw new Error("browse failed"); + const { sessionId, initialPath } = result.value; expect(bootstrap.mock.calls[0][0]).toEqual({ distro: "Ubuntu", remotePath: "/" }); expect(createChannel).toHaveBeenCalledWith({ @@ -72,21 +74,48 @@ describe("wsl.openBrowseSession", () => { }) as never, }); - await expect(open({ distro: "Nope" })).rejects.toThrow( - "There is no distribution with the supplied name.", - ); + expect(await open({ distro: "Nope" })).toMatchObject({ + ok: false, + category: "failed", + code: "transport.unknown", + message: expect.stringContaining("There is no distribution with the supplied name."), + }); + }); + + test("does not open a channel when the browse action is cancelled during bootstrap", async () => { + const registry = makeRegistry(); + const bootstrap = Promise.withResolvers(); + const createChannel = mock(() => makeChannel()); + const open = openWslBrowseSessionHandler(registry, undefined, { + bootstrap: () => bootstrap.promise, + createChannel: createChannel as never, + }); + const controller = new AbortController(); + const opened = open({ distro: "Ubuntu" }, { signal: controller.signal }); + controller.abort(); + bootstrap.resolve(bootstrapResult); + + expect(await opened).toMatchObject({ ok: false, kind: "cancelled" }); + expect(createChannel).not.toHaveBeenCalled(); + expect(registry.size()).toBe(0); }); test("closes the channel when the agent never answers", async () => { const registry = makeRegistry(); - const channel = makeChannel(Promise.reject(new Error("agent exited"))); + const channel = makeChannel( + Promise.reject(createSshError("transport.timeout", new Error("agent exited"))), + ); channel.ready.catch(() => {}); const open = openWslBrowseSessionHandler(registry, undefined, { bootstrap: (async () => bootstrapResult) as never, createChannel: (() => channel) as never, }); - await expect(open({ distro: "Ubuntu" })).rejects.toThrow("agent exited"); + expect(await open({ distro: "Ubuntu" })).toMatchObject({ + ok: false, + category: "failed", + code: "transport.timeout", + }); expect(channel.dispose).toHaveBeenCalledTimes(1); }); }); From 0242bbee83961e2e74edad5cbd04a6dc888db564 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:20:18 +0900 Subject: [PATCH 069/208] fix(editor): promote previews only for the same workspace model Co-Authored-By: Claude Opus 5.5 --- src/renderer/services/editor/save/service.ts | 2 +- .../services/editor/tabs/promote-policy.ts | 48 +++++++------------ .../services/editor/promote-policy.test.ts | 41 ++++++++++++---- 3 files changed, 49 insertions(+), 42 deletions(-) diff --git a/src/renderer/services/editor/save/service.ts b/src/renderer/services/editor/save/service.ts index 2ac6266d2..40b58456f 100644 --- a/src/renderer/services/editor/save/service.ts +++ b/src/renderer/services/editor/save/service.ts @@ -197,7 +197,7 @@ export async function saveModel( // SaveReason.EXPLICIT before invoking the model's save. saveModel is // only called from explicit user gestures (Cmd+S, close-confirm), so // every entry counts as EXPLICIT. - promoteAllPreviewTabsForFile(resolved.filePath); + promoteAllPreviewTabsForFile(resolved.workspaceId, resolved.filePath); const dirtyEntry = getDirtyEntry(resolved.cacheUri); if (!dirtyEntry) return { kind: "no-model" }; diff --git a/src/renderer/services/editor/tabs/promote-policy.ts b/src/renderer/services/editor/tabs/promote-policy.ts index ff15a7020..100c03228 100644 --- a/src/renderer/services/editor/tabs/promote-policy.ts +++ b/src/renderer/services/editor/tabs/promote-policy.ts @@ -6,41 +6,29 @@ // Subsequent edits are no-ops because the dirty-tracker only fires // transition events on flips, not on every keystroke. // -// One file (cacheUri) may be visible in multiple tabs across multiple -// workspaces — they all get promoted, since each one's preview state -// would survive otherwise and surprise the user when their typed changes -// look like they vanished on a single-click of another file. +// Several tabs in one workspace can show the same model. Their preview +// states are independent, so promote them together when that model changes. import { useTabsStore } from "@/state/stores/tabs"; -import { cacheUriToFilePath } from "../model/cache"; +import { parseCacheUri } from "../model/cache"; import { subscribeAllDirtyTransitions } from "../model/dirty-tracker"; import { workingFileOfDiff } from "./diff-working-file"; /** - * Promote every preview editor tab pointing at `filePath`, and every preview - * diff tab editing it, to permanent across every workspace. Idempotent — already-permanent tabs are no-ops - * via tabsStore.promoteFromPreview. - * - * Centralized here because two separate triggers want this exact - * behaviour: a clean→dirty transition (the user typed) and an explicit - * save (Cmd+S, even when the buffer is clean). VSCode's - * editorService.save() takes the same shortcut on - * `SaveReason.EXPLICIT`. + * Promote preview tabs sharing the model identified by workspace and path. + * Both editing and an explicit save make the preview permanent. */ -export function promoteAllPreviewTabsForFile(filePath: string): void { +export function promoteAllPreviewTabsForFile(workspaceId: string, filePath: string): void { const tabsStore = useTabsStore.getState(); - for (const [workspaceId, wsRecord] of Object.entries(tabsStore.byWorkspace)) { - for (const tab of Object.values(wsRecord)) { - if (!tab.isPreview) continue; - const tabFilePath = - tab.type === "editor" - ? tab.props.filePath - : tab.type === "editor.diff" - ? workingFileOfDiff(tab.props) - : null; - if (tabFilePath !== filePath) continue; - tabsStore.promoteFromPreview(workspaceId, tab.id); - } + for (const tab of Object.values(tabsStore.byWorkspace[workspaceId] ?? {})) { + if (!tab.isPreview) continue; + const tabFilePath = + tab.type === "editor" && tab.props.workspaceId === workspaceId + ? tab.props.filePath + : tab.type === "editor.diff" && tab.props.workspaceId === workspaceId + ? workingFileOfDiff(tab.props) + : null; + if (tabFilePath === filePath) tabsStore.promoteFromPreview(workspaceId, tab.id); } } @@ -52,10 +40,8 @@ export function startPromoteOnDirtyPolicy(): void { unsubscribe = subscribeAllDirtyTransitions((event) => { if (!event.isDirty) return; // we only care about clean → dirty - const filePath = cacheUriToFilePath(event.cacheUri); - if (!filePath) return; - - promoteAllPreviewTabsForFile(filePath); + const file = parseCacheUri(event.cacheUri); + if (file) promoteAllPreviewTabsForFile(file.workspaceId, file.filePath); }); } diff --git a/tests/unit/renderer/services/editor/promote-policy.test.ts b/tests/unit/renderer/services/editor/promote-policy.test.ts index 6c0b0c3d3..8a549d51d 100644 --- a/tests/unit/renderer/services/editor/promote-policy.test.ts +++ b/tests/unit/renderer/services/editor/promote-policy.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import { workspaceUriFor } from "../../../../../src/shared/fs/workspace-uri"; (globalThis as Record).window = { ipc: { @@ -16,6 +17,7 @@ const tabsStoreMod = await import("../../../../../src/renderer/state/stores/tabs const workspacesStoreMod = await import("../../../../../src/renderer/state/stores/workspaces"); const WS = "11111111-1111-4111-1111-111111111111"; +const OTHER_WS = "22222222-2222-4222-8222-222222222222"; function makeModel(altId = 1) { let id = altId; @@ -45,15 +47,24 @@ describe("promote-on-dirty policy", () => { promotePolicyMod.stopPromoteOnDirtyPolicyForTests(); }); - it("promotes the preview editor tab pointing at a file when it first becomes dirty", () => { + it("promotes dirty model splits while a matching path in another workspace stays a preview", () => { const tab = tabsStoreMod.useTabsStore .getState() .createTab(WS, { type: "editor", props: { workspaceId: WS, filePath: "/repo/a.ts" } }, true); - expect(tabsStoreMod.useTabsStore.getState().byWorkspace[WS][tab.id].isPreview).toBe(true); + const split = tabsStoreMod.useTabsStore + .getState() + .createTab(WS, { type: "editor", props: { workspaceId: WS, filePath: "/repo/a.ts" } }, true); + const other = tabsStoreMod.useTabsStore + .getState() + .createTab( + OTHER_WS, + { type: "editor", props: { workspaceId: OTHER_WS, filePath: "/repo/a.ts" } }, + true, + ); const model = makeModel(1); dirtyMod.attachDirtyTracker({ - cacheUri: "file:///repo/a.ts", + cacheUri: workspaceUriFor(WS, "/repo/a.ts"), model: model as never, loadedMtime: "T0", loadedSize: 0, @@ -61,7 +72,10 @@ describe("promote-on-dirty policy", () => { model.edit(2); // clean → dirty - expect(tabsStoreMod.useTabsStore.getState().byWorkspace[WS][tab.id].isPreview).toBe(false); + const tabs = tabsStoreMod.useTabsStore.getState().byWorkspace; + expect(tabs[WS][tab.id].isPreview).toBe(false); + expect(tabs[WS][split.id].isPreview).toBe(false); + expect(tabs[OTHER_WS][other.id].isPreview).toBe(true); }); }); @@ -71,28 +85,35 @@ describe("promoteAllPreviewTabsForFile (explicit-save helper)", () => { dirtyMod.__resetDirtyTrackerForTests(); }); - it("promotes a preview diff tab that edits the working-tree file", () => { + it("explicit save promotes only the working-tree diff for its own workspace model", () => { workspacesStoreMod.useWorkspacesStore.setState({ - workspaces: [{ id: WS, rootPath: "/repo" } as never], + workspaces: [ + { id: WS, rootPath: "/repo" }, + { id: OTHER_WS, rootPath: "/repo" }, + ] as never, }); - const diff = (rightRef: string) => + const diff = (rightRef: string, workspaceId = WS) => tabsStoreMod.useTabsStore.getState().createTab( - WS, + workspaceId, { type: "editor.diff", - props: { workspaceId: WS, relPath: "a.ts", leftRef: "INDEX", rightRef }, + props: { workspaceId, relPath: "a.ts", leftRef: "INDEX", rightRef }, }, true, ); const working = diff("WORKING"); const staged = diff("INDEX"); + const other = diff("WORKING", OTHER_WS); - promotePolicyMod.promoteAllPreviewTabsForFile("/repo/a.ts"); + promotePolicyMod.promoteAllPreviewTabsForFile(WS, "/repo/a.ts"); const tabs = tabsStoreMod.useTabsStore.getState().byWorkspace[WS]; expect(tabs[working.id].isPreview).toBe(false); // A staged diff shows the index, not the file being edited. expect(tabs[staged.id].isPreview).toBe(true); + expect(tabsStoreMod.useTabsStore.getState().byWorkspace[OTHER_WS][other.id].isPreview).toBe( + true, + ); workspacesStoreMod.useWorkspacesStore.setState({ workspaces: [] }); }); }); From 23bd3fb606ee125b9e439a1feab994b80ab9f04a Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:22:03 +0900 Subject: [PATCH 070/208] fix(notifications): reveal the target tab before marking it seen Co-Authored-By: Claude Opus 5.5 --- src/renderer/state/notification-click.ts | 29 +++--- .../operations/notification-seen.test.ts | 93 +++++++++++++++++++ 2 files changed, 105 insertions(+), 17 deletions(-) create mode 100644 tests/unit/renderer/state/operations/notification-seen.test.ts diff --git a/src/renderer/state/notification-click.ts b/src/renderer/state/notification-click.ts index c49c9945f..eaa569bd2 100644 --- a/src/renderer/state/notification-click.ts +++ b/src/renderer/state/notification-click.ts @@ -26,24 +26,19 @@ export function startNotificationClickListener(): () => void { } } - focusWorkspace(workspaceId, "workspace"); - - // Reveal the tab in whichever leaf group contains it. + // Set the destination tab first. Active-context subscribers run + // synchronously and would mark any intermediate tab as seen. const layout = useLayoutStore.getState().byWorkspace[workspaceId]; - if (!layout) return; - - for (const leaf of allLeaves(layout.root)) { - if (leaf.tabIds.includes(tabId)) { - useLayoutStore.getState().setActiveTabInGroup({ - workspaceId, - groupId: leaf.id, - tabId, - activateGroup: true, - }); - return; - } + const group = layout && allLeaves(layout.root).find((leaf) => leaf.tabIds.includes(tabId)); + if (group) { + useLayoutStore.getState().setActiveTabInGroup({ + workspaceId, + groupId: group.id, + tabId, + activateGroup: true, + }); } - // Tab not found in layout (may have been closed) — workspace activation - // above is sufficient. + focusWorkspace(workspaceId, "preserve"); + if (agentView.mode === "agents") agentView.setMode("workspace"); }); } diff --git a/tests/unit/renderer/state/operations/notification-seen.test.ts b/tests/unit/renderer/state/operations/notification-seen.test.ts new file mode 100644 index 000000000..4bbef39ac --- /dev/null +++ b/tests/unit/renderer/state/operations/notification-seen.test.ts @@ -0,0 +1,93 @@ +import { expect, test } from "bun:test"; +import { sessionKey } from "../../../../../src/renderer/services/agent-sessions/model"; +import { startClaudeActiveContextSync } from "../../../../../src/renderer/state/claude-active-context-sync"; +import { startNotificationClickListener } from "../../../../../src/renderer/state/notification-click"; +import { useActiveStore } from "../../../../../src/renderer/state/stores/active"; +import { useAgentViewStore } from "../../../../../src/renderer/state/stores/agent-view"; +import { useAppFocusStore } from "../../../../../src/renderer/state/stores/app-focus"; +import { useLayoutStore } from "../../../../../src/renderer/state/stores/layout"; +import { useSessionSeenStore } from "../../../../../src/renderer/state/stores/session-seen"; + +for (const mode of ["workspace", "agents"] as const) { + test(`a notification click marks the intended tab seen without visiting intermediate tabs in ${mode} mode`, () => { + const from = crypto.randomUUID(); + const to = crypto.randomUUID(); + const fromTab = crypto.randomUUID(); + const intermediate = crypto.randomUUID(); + const target = crypto.randomUUID(); + const agentTab = crypto.randomUUID(); + const leaf = crypto.randomUUID(); + const contextCalls: unknown[] = []; + const originalWindow = globalThis.window; + const beforeMode = useAgentViewStore.getState(); + const beforeLayouts = useLayoutStore.getState().byWorkspace; + const beforeSeen = useSessionSeenStore.getState().byWorkspace; + const beforeActive = useActiveStore.getState().activeWorkspaceId; + const beforeFocused = useAppFocusStore.getState().focused; + let notify: ((payload: unknown) => void) | undefined; + Object.assign(globalThis, { + window: { + ipc: { + call: async (channel: string, method: string, body: unknown) => { + if (channel === "claude" && method === "markSeen") contextCalls.push(body); + }, + listen: (_channel: string, _event: string, cb: (payload: unknown) => void) => { + notify = cb; + return () => {}; + }, + }, + }, + }); + + useActiveStore.setState({ activeWorkspaceId: from }); + useAppFocusStore.setState({ focused: true }); + useSessionSeenStore.setState({ byWorkspace: {} }); + useAgentViewStore.setState({ + mode, + root: { + kind: "leaf", + id: leaf, + tabIds: [sessionKey(from, agentTab)], + activeTabId: sessionKey(from, agentTab), + }, + activeLeafId: leaf, + }); + useLayoutStore.setState({ + byWorkspace: { + [from]: { + root: { kind: "leaf", id: "from", tabIds: [fromTab], activeTabId: fromTab }, + activeGroupId: "from", + }, + [to]: { + root: { + kind: "leaf", + id: "to", + tabIds: [intermediate, target], + activeTabId: intermediate, + }, + activeGroupId: "to", + }, + }, + }); + const stopSync = startClaudeActiveContextSync(); + const stopNotifications = startNotificationClickListener(); + contextCalls.length = 0; + try { + notify?.({ workspaceId: to, tabId: target }); + expect(contextCalls).toEqual([{ workspaceId: to, tabId: target }]); + const seen = useSessionSeenStore.getState().byWorkspace; + expect(seen[to]?.[intermediate]).toBeUndefined(); + expect(seen[to]?.[target]).toBeNumber(); + if (mode === "agents") expect(seen[from]?.[fromTab]).toBeUndefined(); + } finally { + stopSync(); + stopNotifications(); + useLayoutStore.setState({ byWorkspace: beforeLayouts }); + useActiveStore.setState({ activeWorkspaceId: beforeActive }); + useAppFocusStore.setState({ focused: beforeFocused }); + useAgentViewStore.setState(beforeMode); + useSessionSeenStore.setState({ byWorkspace: beforeSeen }); + Object.assign(globalThis, { window: originalWindow }); + } + }); +} From 9b5628dffbb208cc71c54f4c48ad3153a353025b Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:23:18 +0900 Subject: [PATCH 071/208] fix(i18n): translate reserved shortcut conflict descriptions Co-Authored-By: Claude Opus 5.5 --- .../settings/panels/keybindings-panel.tsx | 5 +- src/shared/i18n/locales/en/settings.json | 52 +++++++++ src/shared/i18n/locales/ko/settings.json | 52 +++++++++ src/shared/keybindings/reserved-keys.ts | 104 +++++++++--------- tests/unit/shared/reserved-key-labels.test.ts | 23 ++++ 5 files changed, 182 insertions(+), 54 deletions(-) create mode 100644 tests/unit/shared/reserved-key-labels.test.ts diff --git a/src/renderer/components/settings/panels/keybindings-panel.tsx b/src/renderer/components/settings/panels/keybindings-panel.tsx index 4effc2b12..9a7324cdd 100644 --- a/src/renderer/components/settings/panels/keybindings-panel.tsx +++ b/src/renderer/components/settings/panels/keybindings-panel.tsx @@ -675,17 +675,18 @@ function KeybindingRecorder({ {conflicts.map((c, i) => { const key = `${c.kind}-${c.command ?? c.reserved?.accelerator ?? i}`; + const note = c.reserved ? t(`keybindings.reservedNote.${c.reserved.noteKey}`) : ""; let message: string; if (c.kind === "blocking" || c.kind === "overlap") { message = t(`keybindings.conflict.${c.kind}`, { command: c.command !== undefined ? commandLabel(c.command) : "?", }); } else if (c.kind === "system") { - message = t("keybindings.conflict.system", { note: c.reserved?.note ?? "" }); + message = t("keybindings.conflict.system", { note: note }); } else { message = t("keybindings.conflict.shadow", { owner: c.reserved !== undefined ? t(`keybindings.owner.${c.reserved.source}`) : "?", - note: c.reserved?.note ?? "", + note: note, }); } const severe = c.kind === "blocking" || c.kind === "system"; diff --git a/src/shared/i18n/locales/en/settings.json b/src/shared/i18n/locales/en/settings.json index b87db4ad8..5c5edcd69 100644 --- a/src/shared/i18n/locales/en/settings.json +++ b/src/shared/i18n/locales/en/settings.json @@ -410,6 +410,58 @@ "shadow": "Shadows {{owner}}: {{note}}", "system": "Reserved by the OS: {{note}}" }, + "reservedNote": { + "quitApplication": "Quit application", + "hideApplication": "Hide application", + "hideOthers": "Hide other applications", + "minimizeWindow": "Minimize window", + "copy": "Copy", + "cut": "Cut", + "paste": "Paste", + "selectAll": "Select all", + "undo": "Undo", + "redo": "Redo", + "toggleDevTools": "Toggle window DevTools", + "resetZoom": "Reset zoom", + "zoomOut": "Zoom out", + "zoomIn": "Zoom in", + "toggleLineComment": "Toggle line comment", + "addNextMatch": "Add selection to next find match", + "find": "Find", + "replace": "Replace", + "findNext": "Find next", + "undoCursor": "Undo cursor position", + "outdent": "Outdent line", + "indent": "Indent line", + "deleteLine": "Delete line", + "insertLineBelow": "Insert line below", + "moveLineUp": "Move line up", + "moveLineDown": "Move line down", + "copyLineUp": "Copy line up", + "copyLineDown": "Copy line down", + "editorPalette": "Editor command palette", + "nextProblem": "Go to next problem", + "definition": "Go to definition", + "references": "Go to references", + "interrupt": "SIGINT (interrupt)", + "shellEof": "EOF / exit shell", + "suspendJob": "Suspend job (SIGTSTP)", + "reverseSearch": "Reverse history search", + "lineStart": "Beginning of line", + "lineEnd": "End of line", + "deletePreviousWord": "Delete previous word", + "killLineBackward": "Kill line backward", + "killLineForward": "Kill line forward", + "clearScreen": "Clear screen", + "transpose": "Transpose characters", + "nextHistory": "Next history entry", + "previousHistory": "Previous history entry", + "operateNext": "Operate and get next", + "flowStop": "Flow control stop (XOFF)", + "flowResume": "Flow control resume (XON)", + "sigquit": "SIGQUIT", + "multiline": "Multi-line input (app)" + }, "owner": { "monaco": "the editor", "terminal": "the terminal/shell", diff --git a/src/shared/i18n/locales/ko/settings.json b/src/shared/i18n/locales/ko/settings.json index 1770cf507..543a5514e 100644 --- a/src/shared/i18n/locales/ko/settings.json +++ b/src/shared/i18n/locales/ko/settings.json @@ -410,6 +410,58 @@ "shadow": "{{owner}}의 “{{note}}” 키를 가립니다", "system": "OS 예약 키입니다: {{note}}" }, + "reservedNote": { + "quitApplication": "앱 종료", + "hideApplication": "앱 가리기", + "hideOthers": "다른 앱 가리기", + "minimizeWindow": "창 최소화", + "copy": "복사", + "cut": "잘라내기", + "paste": "붙여넣기", + "selectAll": "모두 선택", + "undo": "실행 취소", + "redo": "다시 실행", + "toggleDevTools": "창 개발자 도구 전환", + "resetZoom": "확대/축소 초기화", + "zoomOut": "축소", + "zoomIn": "확대", + "toggleLineComment": "줄 주석 전환", + "addNextMatch": "다음 검색 결과를 선택 항목에 추가", + "find": "찾기", + "replace": "바꾸기", + "findNext": "다음 찾기", + "undoCursor": "커서 위치 되돌리기", + "outdent": "내어쓰기", + "indent": "들여쓰기", + "deleteLine": "줄 삭제", + "insertLineBelow": "아래에 줄 삽입", + "moveLineUp": "줄을 위로 이동", + "moveLineDown": "줄을 아래로 이동", + "copyLineUp": "줄을 위로 복사", + "copyLineDown": "줄을 아래로 복사", + "editorPalette": "편집기 명령 팔레트", + "nextProblem": "다음 문제로 이동", + "definition": "정의로 이동", + "references": "참조로 이동", + "interrupt": "실행 중단 (SIGINT)", + "shellEof": "입력 종료 (EOF) 또는 셸 종료", + "suspendJob": "작업 일시 중지 (SIGTSTP)", + "reverseSearch": "명령 기록 역방향 검색", + "lineStart": "줄 시작으로 이동", + "lineEnd": "줄 끝으로 이동", + "deletePreviousWord": "이전 단어 삭제", + "killLineBackward": "줄 시작까지 삭제", + "killLineForward": "줄 끝까지 삭제", + "clearScreen": "화면 지우기", + "transpose": "문자 순서 바꾸기", + "nextHistory": "다음 명령 기록", + "previousHistory": "이전 명령 기록", + "operateNext": "현재 명령 실행 후 다음 기록 불러오기", + "flowStop": "흐름 제어 중지 (XOFF)", + "flowResume": "흐름 제어 재개 (XON)", + "sigquit": "종료 신호 (SIGQUIT)", + "multiline": "여러 줄 입력 (앱)" + }, "owner": { "monaco": "에디터", "terminal": "터미널/셸", diff --git a/src/shared/keybindings/reserved-keys.ts b/src/shared/keybindings/reserved-keys.ts index 21c182eb0..c84a19344 100644 --- a/src/shared/keybindings/reserved-keys.ts +++ b/src/shared/keybindings/reserved-keys.ts @@ -40,70 +40,70 @@ export type ReservedKeySource = "system" | "electron" | "monaco" | "terminal"; export interface ReservedKey { accelerator: AcceleratorString; source: ReservedKeySource; - /** Short English description of what the key does in its owner. */ - note: string; + /** Translation key for the action reserved by its owner. */ + noteKey: string; /** Restrict the reservation to one platform. Absent = both. */ platform?: "mac" | "non-mac"; } export const RESERVED_KEYS: readonly ReservedKey[] = [ // ── system (recorder-blocked) ─────────────────────────────────────── - { accelerator: "Cmd+Q", source: "system", note: "Quit application", platform: "mac" }, - { accelerator: "Cmd+H", source: "system", note: "Hide application", platform: "mac" }, - { accelerator: "Cmd+Alt+H", source: "system", note: "Hide other applications", platform: "mac" }, - { accelerator: "Cmd+M", source: "system", note: "Minimize window", platform: "mac" }, + { accelerator: "Cmd+Q", source: "system", noteKey: "quitApplication", platform: "mac" }, + { accelerator: "Cmd+H", source: "system", noteKey: "hideApplication", platform: "mac" }, + { accelerator: "Cmd+Alt+H", source: "system", noteKey: "hideOthers", platform: "mac" }, + { accelerator: "Cmd+M", source: "system", noteKey: "minimizeWindow", platform: "mac" }, // ── electron roles (Cocoa-registered accelerators) ────────────────── - { accelerator: "CmdOrCtrl+C", source: "electron", note: "Copy" }, - { accelerator: "CmdOrCtrl+X", source: "electron", note: "Cut" }, - { accelerator: "CmdOrCtrl+V", source: "electron", note: "Paste" }, - { accelerator: "CmdOrCtrl+A", source: "electron", note: "Select all" }, - { accelerator: "CmdOrCtrl+Z", source: "electron", note: "Undo" }, - { accelerator: "CmdOrCtrl+Shift+Z", source: "electron", note: "Redo" }, - { accelerator: "CmdOrCtrl+Alt+I", source: "electron", note: "Toggle window DevTools" }, - { accelerator: "CmdOrCtrl+0", source: "electron", note: "Reset zoom" }, - { accelerator: "CmdOrCtrl+-", source: "electron", note: "Zoom out" }, - { accelerator: "CmdOrCtrl+=", source: "electron", note: "Zoom in" }, + { accelerator: "CmdOrCtrl+C", source: "electron", noteKey: "copy" }, + { accelerator: "CmdOrCtrl+X", source: "electron", noteKey: "cut" }, + { accelerator: "CmdOrCtrl+V", source: "electron", noteKey: "paste" }, + { accelerator: "CmdOrCtrl+A", source: "electron", noteKey: "selectAll" }, + { accelerator: "CmdOrCtrl+Z", source: "electron", noteKey: "undo" }, + { accelerator: "CmdOrCtrl+Shift+Z", source: "electron", noteKey: "redo" }, + { accelerator: "CmdOrCtrl+Alt+I", source: "electron", noteKey: "toggleDevTools" }, + { accelerator: "CmdOrCtrl+0", source: "electron", noteKey: "resetZoom" }, + { accelerator: "CmdOrCtrl+-", source: "electron", noteKey: "zoomOut" }, + { accelerator: "CmdOrCtrl+=", source: "electron", noteKey: "zoomIn" }, // ── monaco editor defaults (editor focus) ─────────────────────────── - { accelerator: "CmdOrCtrl+/", source: "monaco", note: "Toggle line comment" }, - { accelerator: "CmdOrCtrl+D", source: "monaco", note: "Add selection to next find match" }, - { accelerator: "CmdOrCtrl+F", source: "monaco", note: "Find" }, - { accelerator: "CmdOrCtrl+Alt+F", source: "monaco", note: "Replace" }, - { accelerator: "CmdOrCtrl+G", source: "monaco", note: "Find next" }, - { accelerator: "CmdOrCtrl+U", source: "monaco", note: "Undo cursor position" }, - { accelerator: "CmdOrCtrl+[", source: "monaco", note: "Outdent line" }, - { accelerator: "CmdOrCtrl+]", source: "monaco", note: "Indent line" }, - { accelerator: "CmdOrCtrl+Shift+K", source: "monaco", note: "Delete line" }, - { accelerator: "CmdOrCtrl+Enter", source: "monaco", note: "Insert line below" }, - { accelerator: "Alt+Up", source: "monaco", note: "Move line up" }, - { accelerator: "Alt+Down", source: "monaco", note: "Move line down" }, - { accelerator: "Shift+Alt+Up", source: "monaco", note: "Copy line up" }, - { accelerator: "Shift+Alt+Down", source: "monaco", note: "Copy line down" }, - { accelerator: "F1", source: "monaco", note: "Editor command palette" }, - { accelerator: "F8", source: "monaco", note: "Go to next problem" }, - { accelerator: "F12", source: "monaco", note: "Go to definition" }, - { accelerator: "Shift+F12", source: "monaco", note: "Go to references" }, + { accelerator: "CmdOrCtrl+/", source: "monaco", noteKey: "toggleLineComment" }, + { accelerator: "CmdOrCtrl+D", source: "monaco", noteKey: "addNextMatch" }, + { accelerator: "CmdOrCtrl+F", source: "monaco", noteKey: "find" }, + { accelerator: "CmdOrCtrl+Alt+F", source: "monaco", noteKey: "replace" }, + { accelerator: "CmdOrCtrl+G", source: "monaco", noteKey: "findNext" }, + { accelerator: "CmdOrCtrl+U", source: "monaco", noteKey: "undoCursor" }, + { accelerator: "CmdOrCtrl+[", source: "monaco", noteKey: "outdent" }, + { accelerator: "CmdOrCtrl+]", source: "monaco", noteKey: "indent" }, + { accelerator: "CmdOrCtrl+Shift+K", source: "monaco", noteKey: "deleteLine" }, + { accelerator: "CmdOrCtrl+Enter", source: "monaco", noteKey: "insertLineBelow" }, + { accelerator: "Alt+Up", source: "monaco", noteKey: "moveLineUp" }, + { accelerator: "Alt+Down", source: "monaco", noteKey: "moveLineDown" }, + { accelerator: "Shift+Alt+Up", source: "monaco", noteKey: "copyLineUp" }, + { accelerator: "Shift+Alt+Down", source: "monaco", noteKey: "copyLineDown" }, + { accelerator: "F1", source: "monaco", noteKey: "editorPalette" }, + { accelerator: "F8", source: "monaco", noteKey: "nextProblem" }, + { accelerator: "F12", source: "monaco", noteKey: "definition" }, + { accelerator: "Shift+F12", source: "monaco", noteKey: "references" }, // ── terminal / shell (terminal focus) ─────────────────────────────── - { accelerator: "Ctrl+C", source: "terminal", note: "SIGINT (interrupt)" }, - { accelerator: "Ctrl+D", source: "terminal", note: "EOF / exit shell" }, - { accelerator: "Ctrl+Z", source: "terminal", note: "Suspend job (SIGTSTP)" }, - { accelerator: "Ctrl+R", source: "terminal", note: "Reverse history search" }, - { accelerator: "Ctrl+A", source: "terminal", note: "Beginning of line" }, - { accelerator: "Ctrl+E", source: "terminal", note: "End of line" }, - { accelerator: "Ctrl+W", source: "terminal", note: "Delete previous word" }, - { accelerator: "Ctrl+U", source: "terminal", note: "Kill line backward" }, - { accelerator: "Ctrl+K", source: "terminal", note: "Kill line forward" }, - { accelerator: "Ctrl+L", source: "terminal", note: "Clear screen" }, - { accelerator: "Ctrl+T", source: "terminal", note: "Transpose characters" }, - { accelerator: "Ctrl+N", source: "terminal", note: "Next history entry" }, - { accelerator: "Ctrl+P", source: "terminal", note: "Previous history entry" }, - { accelerator: "Ctrl+O", source: "terminal", note: "Operate and get next" }, - { accelerator: "Ctrl+S", source: "terminal", note: "Flow control stop (XOFF)" }, - { accelerator: "Ctrl+Q", source: "terminal", note: "Flow control resume (XON)" }, - { accelerator: "Ctrl+\\", source: "terminal", note: "SIGQUIT" }, - { accelerator: "Shift+Enter", source: "terminal", note: "Multi-line input (app)" }, + { accelerator: "Ctrl+C", source: "terminal", noteKey: "interrupt" }, + { accelerator: "Ctrl+D", source: "terminal", noteKey: "shellEof" }, + { accelerator: "Ctrl+Z", source: "terminal", noteKey: "suspendJob" }, + { accelerator: "Ctrl+R", source: "terminal", noteKey: "reverseSearch" }, + { accelerator: "Ctrl+A", source: "terminal", noteKey: "lineStart" }, + { accelerator: "Ctrl+E", source: "terminal", noteKey: "lineEnd" }, + { accelerator: "Ctrl+W", source: "terminal", noteKey: "deletePreviousWord" }, + { accelerator: "Ctrl+U", source: "terminal", noteKey: "killLineBackward" }, + { accelerator: "Ctrl+K", source: "terminal", noteKey: "killLineForward" }, + { accelerator: "Ctrl+L", source: "terminal", noteKey: "clearScreen" }, + { accelerator: "Ctrl+T", source: "terminal", noteKey: "transpose" }, + { accelerator: "Ctrl+N", source: "terminal", noteKey: "nextHistory" }, + { accelerator: "Ctrl+P", source: "terminal", noteKey: "previousHistory" }, + { accelerator: "Ctrl+O", source: "terminal", noteKey: "operateNext" }, + { accelerator: "Ctrl+S", source: "terminal", noteKey: "flowStop" }, + { accelerator: "Ctrl+Q", source: "terminal", noteKey: "flowResume" }, + { accelerator: "Ctrl+\\", source: "terminal", noteKey: "sigquit" }, + { accelerator: "Shift+Enter", source: "terminal", noteKey: "multiline" }, ]; /** diff --git a/tests/unit/shared/reserved-key-labels.test.ts b/tests/unit/shared/reserved-key-labels.test.ts new file mode 100644 index 000000000..cedf2b8f8 --- /dev/null +++ b/tests/unit/shared/reserved-key-labels.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from "bun:test"; +import i18next from "i18next"; +import { createI18n } from "../../../src/shared/i18n"; +import { detectConflicts } from "../../../src/shared/keybindings/conflicts"; + +test("system and terminal shortcut conflicts have Korean action descriptions", async () => { + const locale = i18next.createInstance(); + await locale.init(createI18n({ lng: "ko" }).options); + for (const [primary, expected] of [ + ["Cmd+Q", "앱 종료"], + ["Ctrl+R", "명령 기록 역방향 검색"], + ] as const) { + const conflict = detectConflicts({ + command: "test.action", + primary, + bindings: [], + isMac: true, + }).find(({ reserved }) => reserved); + expect(locale.t(`settings:keybindings.reservedNote.${conflict?.reserved?.noteKey}`)).toBe( + expected, + ); + } +}); From 59556ca3cfbe604bbedbcc0ab3719460f4232637 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:24:08 +0900 Subject: [PATCH 072/208] fix(i18n): localize the editor save palette action Co-Authored-By: Claude Opus 5.5 --- .../install-editor-integrations.ts | 3 +- src/renderer/services/editor/save/service.ts | 39 ++++++++++++------- .../editor/palette-save-label.test.ts | 32 +++++++++++++++ 3 files changed, 60 insertions(+), 14 deletions(-) create mode 100644 tests/unit/renderer/services/editor/palette-save-label.test.ts diff --git a/src/renderer/components/workspace/content/editor-mount/install-editor-integrations.ts b/src/renderer/components/workspace/content/editor-mount/install-editor-integrations.ts index ac7160097..464f78db1 100644 --- a/src/renderer/components/workspace/content/editor-mount/install-editor-integrations.ts +++ b/src/renderer/components/workspace/content/editor-mount/install-editor-integrations.ts @@ -53,7 +53,7 @@ export function installEditorIntegrations({ opener.openCodeEditor(source, resource, selectionOrPosition), }); - installEditorSaveAction(editor, input); + const saveAction = installEditorSaveAction(editor, input); // Install the conflict-resolution CodeLens + decoration provider. Activates // only when the current model contains Git conflict markers; disposal is @@ -73,6 +73,7 @@ export function installEditorIntegrations({ return { dispose() { openerDisposable.dispose(); + saveAction.dispose(); conflictCodelensDisposable.dispose(); dirtyDiffDisposable.dispose(); }, diff --git a/src/renderer/services/editor/save/service.ts b/src/renderer/services/editor/save/service.ts index 2ac6266d2..53cec7258 100644 --- a/src/renderer/services/editor/save/service.ts +++ b/src/renderer/services/editor/save/service.ts @@ -39,24 +39,37 @@ import { promoteAllPreviewTabsForFile } from "../tabs/promote-policy"; import type { EditorInput } from "../types"; import { SaveSequentializer, SaveSupersededError } from "./sequentializer"; +/** Registers the Monaco palette action in the editor's current UI language. */ export function installEditorSaveAction( editor: Monaco.editor.IStandaloneCodeEditor, input: EditorInput, ): Monaco.IDisposable { - return editor.addAction({ - id: "nexus.file.save", - label: "Save File", - // Intentionally NO `keybindings` here. ⌘S is owned by the global - // dispatcher (shared/keybindings → COMMANDS.fileSave), which wins at - // capture phase anyway. Registering a Monaco-side ⌘S as well would - // leave a ghost binding that resurfaces the moment the user rebinds - // fileSave to another key via the keybinding settings — Monaco would - // then fire save on the *old* key. The action stays registered so it - // remains discoverable/invocable from Monaco's F1 command palette. - run: () => { - runSaveAndReport(input); + const register = () => + editor.addAction({ + id: "nexus.file.save", + label: i18next.t("settings:keybindings.command.file.save"), + // The global keybinding dispatcher owns the save shortcut. + run: () => runSaveAndReport(input), + }); + let action: Monaco.IDisposable | undefined = register(); + + const refresh = () => { + action?.dispose(); + action = register(); + }; + const release = () => { + i18next.off("languageChanged", refresh); + action?.dispose(); + action = undefined; + }; + i18next.on("languageChanged", refresh); + const editorLifetime = editor.onDidDispose(release); + return { + dispose() { + editorLifetime.dispose(); + release(); }, - }); + }; } export interface SaveOptions { diff --git a/tests/unit/renderer/services/editor/palette-save-label.test.ts b/tests/unit/renderer/services/editor/palette-save-label.test.ts new file mode 100644 index 000000000..45ac0de16 --- /dev/null +++ b/tests/unit/renderer/services/editor/palette-save-label.test.ts @@ -0,0 +1,32 @@ +import { expect, mock, test } from "bun:test"; +import i18next from "i18next"; +import type * as Monaco from "monaco-editor"; +import { installEditorSaveAction } from "../../../../../src/renderer/services/editor/save/service"; +import { createI18n } from "../../../../../src/shared/i18n"; + +test("the editor save action follows the palette language on an open editor", async () => { + const originalLanguage = i18next.language; + await i18next.init(createI18n({ lng: "ko" }).options); + const dispose = mock(() => {}); + const labels: string[] = []; + const editor = { + addAction(action: Monaco.editor.IActionDescriptor) { + labels.push(action.label); + return { dispose }; + }, + onDidDispose() { + return { dispose() {} }; + }, + } as unknown as Monaco.editor.IStandaloneCodeEditor; + const installed = installEditorSaveAction(editor, { workspaceId: "ws", filePath: "/file" }); + try { + expect(labels).toEqual(["파일 저장"]); + await i18next.changeLanguage("en"); + expect(labels).toEqual(["파일 저장", "Save File"]); + expect(dispose).toHaveBeenCalledTimes(1); + } finally { + installed.dispose(); + await i18next.changeLanguage(originalLanguage ?? "en"); + } + expect(labels).toHaveLength(2); +}); From 1b5f75f0ad253b15be59c0106a71954282e7e52c Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:24:53 +0900 Subject: [PATCH 073/208] fix(i18n): hide raw git errors in commit tabs Co-Authored-By: Claude Opus 5.5 --- src/renderer/components/editor/commit-tab.tsx | 13 ++++++---- .../workspace/commit-tab-errors.test.ts | 24 +++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 tests/unit/renderer/components/workspace/commit-tab-errors.test.ts diff --git a/src/renderer/components/editor/commit-tab.tsx b/src/renderer/components/editor/commit-tab.tsx index 6d6fbf1d8..3b62c1d81 100644 --- a/src/renderer/components/editor/commit-tab.tsx +++ b/src/renderer/components/editor/commit-tab.tsx @@ -2,11 +2,14 @@ import i18next from "i18next"; import { type ReactNode, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import type { CommitDetail, CommitFileChange } from "../../../shared/git/types"; +import { createLogger } from "../../../shared/log/renderer"; import { ipcCallResult, unwrapGitResult } from "../../ipc/client"; import { closeTab, openDiffTab } from "../../state/operations/tabs"; import { useTabsStore } from "../../state/stores/tabs"; import { Button } from "../ui/button"; +const log = createLogger("commit-tab"); + const EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"; interface CommitTabProps { @@ -48,7 +51,9 @@ export function CommitTab({ workspaceId, sha, tabId }: CommitTabProps) { }) .catch((fetchError) => { if (controller.signal.aborted) return; - setError(commitTabErrorFrom(fetchError, sha)); + const error = commitTabErrorFrom(fetchError, sha); + if (!error.notFound) log.warn(`Commit details failed to load: ${String(fetchError)}`); + setError(error); }) .finally(() => { if (!controller.signal.aborted) setLoading(false); @@ -194,15 +199,13 @@ export function formatCommitTime(value: string, locale: string): string { /** * Converts IPC failures into commit-tab rendering state. */ -function commitTabErrorFrom(error: unknown, sha: string): CommitTabError { +export function commitTabErrorFrom(error: unknown, sha: string): CommitTabError { const notFound = isCommitNotFoundError(error); return { notFound, message: notFound ? i18next.t("editor.commit_not_found", { sha: sha.slice(0, 7) }) - : error instanceof Error - ? error.message - : i18next.t("editor.commit_load_failed"), + : i18next.t("editor.commit_load_failed"), }; } diff --git a/tests/unit/renderer/components/workspace/commit-tab-errors.test.ts b/tests/unit/renderer/components/workspace/commit-tab-errors.test.ts new file mode 100644 index 000000000..5f8d8ba18 --- /dev/null +++ b/tests/unit/renderer/components/workspace/commit-tab-errors.test.ts @@ -0,0 +1,24 @@ +import { expect, test } from "bun:test"; +import i18next from "i18next"; +import { commitTabErrorFrom } from "../../../../../src/renderer/components/editor/commit-tab"; +import { createI18n } from "../../../../../src/shared/i18n"; + +test("commit load uses translated messages for missing refs and other git failures", async () => { + const originalLanguage = i18next.language; + await i18next.init(createI18n({ lng: "ko" }).options); + try { + const sha = "abc123456789"; + const raw = new Error("fatal: cannot read /private/repo"); + expect(commitTabErrorFrom(raw, sha)).toEqual({ + notFound: false, + message: "커밋 세부정보 로드에 실패했습니다.", + }); + const missing = Object.assign(new Error("fatal: invalid object"), { kind: "ref-not-found" }); + expect(commitTabErrorFrom(missing, sha)).toEqual({ + notFound: true, + message: "커밋 abc1234을(를) 저장소에서 찾을 수 없습니다", + }); + } finally { + await i18next.changeLanguage(originalLanguage ?? "en"); + } +}); From e1b547c930fbb896e0bb535c949d6b4e67b42de2 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:24:53 +0900 Subject: [PATCH 074/208] fix(chat): keep MCP server names visible during sign-in Co-Authored-By: Claude Opus 5.5 --- src/renderer/components/chat/side-panel.tsx | 27 ++++++++++++--------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/renderer/components/chat/side-panel.tsx b/src/renderer/components/chat/side-panel.tsx index 5b6333eaa..42a74b3c3 100644 --- a/src/renderer/components/chat/side-panel.tsx +++ b/src/renderer/components/chat/side-panel.tsx @@ -1100,18 +1100,23 @@ function McpSection({ controller, state }: { controller: ChatController; state: key={server.name} title={signingIn ? t("chat.panel.mcp.signing_in_hint") : server.name} > - {server.name} {signingIn ? ( - - {t("chat.panel.mcp.signing_in")} - controller.reopenMcpSignIn()}> - {t("chat.panel.mcp.reopen")} - - controller.cancelMcpSignIn()}> - {t("chat.panel.mcp.cancel")} - - - ) : server.status === "needs-auth" ? ( +
    + {server.name} +
    + {t("chat.panel.mcp.signing_in")} + controller.reopenMcpSignIn()}> + {t("chat.panel.mcp.reopen")} + + controller.cancelMcpSignIn()}> + {t("chat.panel.mcp.cancel")} + +
    +
    + ) : ( + {server.name} + )} + {signingIn ? null : server.status === "needs-auth" ? ( controller.mcpAuthenticate(server.name).catch(fail)}> {t("chat.panel.mcp.sign_in")} From f12543dafe24526856552f47859dbd00ab047908 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 20:17:59 +0900 Subject: [PATCH 075/208] fix(renderer): use structured errors for workspace and storage actions Co-Authored-By: Claude Opus 5.5 --- src/main/features/cli/index.ts | 20 +++-- .../components/editor/browser/pick-button.tsx | 32 +++++--- .../settings/panels/notes-panel.tsx | 82 +++++++++++++++---- .../add-workspace/ssh-new-connection-view.tsx | 4 +- .../services/error-surface/surface-error.ts | 2 + .../workspace/ssh-new-connection-flow.test.ts | 29 +++++++ 6 files changed, 131 insertions(+), 38 deletions(-) diff --git a/src/main/features/cli/index.ts b/src/main/features/cli/index.ts index 35e0e0dc5..b059e13af 100644 --- a/src/main/features/cli/index.ts +++ b/src/main/features/cli/index.ts @@ -16,7 +16,7 @@ import type { CliUiOp, CliUiOps } from "../../../shared/cli/ui"; import { FS_READ_ABSOLUTE_BINARY_METHOD } from "../../../shared/fs/protocol"; import { FileReadBinaryResultSchema, FsStatSchema } from "../../../shared/fs/types"; import { ipcContract } from "../../../shared/ipc/contract"; -import { ipcOk } from "../../../shared/ipc/result"; +import { ipcErr, ipcOk } from "../../../shared/ipc/result"; import { createLogger } from "../../../shared/log/main"; import type { ListeningPort } from "../../../shared/pty/ports"; import type { WorkspaceLocation, WorkspaceMeta } from "../../../shared/types/workspace"; @@ -190,12 +190,18 @@ export function setupCliFeature(options: SetupCliFeatureOptions): CliFeature { waits: async () => ipcOk(waits.snapshot()), pickElement: async (args: unknown) => { const { tabId } = validateArgs(ipcContract.cli.call.pickElement.args, args); - const result = await browser.pick(tabId, { timeoutMs: BUTTON_PICK_MS }); - if ("cancelled" in result) return ipcOk({ cancelled: result.cancelled }); - // The click left the keyboard in the page; the agent's terminal is next. - options.getWindow()?.webContents.focus(); - const screenshot = await pickPicture(tabId, result.picked); - return ipcOk({ text: formatPick(result.picked, screenshot, shortId(tabId)) }); + try { + const result = await browser.pick(tabId, { timeoutMs: BUTTON_PICK_MS }); + if ("cancelled" in result) return ipcOk({ cancelled: result.cancelled }); + // The click left the keyboard in the page; the agent's terminal is next. + options.getWindow()?.webContents.focus(); + const screenshot = await pickPicture(tabId, result.picked); + return ipcOk({ text: formatPick(result.picked, screenshot, shortId(tabId)) }); + } catch (error) { + if (error instanceof CliError) + return ipcErr("pick-failed", error.message, { category: "failed" }); + throw error; + } }, cancelPick: async (args: unknown) => { browser.cancelPick(validateArgs(ipcContract.cli.call.cancelPick.args, args).tabId); diff --git a/src/renderer/components/editor/browser/pick-button.tsx b/src/renderer/components/editor/browser/pick-button.tsx index 0293658c0..add12fe98 100644 --- a/src/renderer/components/editor/browser/pick-button.tsx +++ b/src/renderer/components/editor/browser/pick-button.tsx @@ -24,16 +24,19 @@ import { } from "@/components/ui/dropdown-menu"; import { IconButton } from "@/components/ui/icon-button"; import { showToast } from "@/components/ui/toast"; +import { normaliseError } from "@/hooks/use-ipc-action"; import { ipcCallResult } from "@/ipc/client"; import { showTerminal } from "@/services/agent-sessions/actions"; import { type AgentSession, sessionKey } from "@/services/agent-sessions/model"; import { pasteForTerminal, pickTargets, targetLabels } from "@/services/browser/element-pick"; +import { surfaceError } from "@/services/error-surface/surface-error"; import { getTerminalController } from "@/services/terminal/terminal-registry"; import { useClaudeStatusStore } from "@/state/stores/claude-status"; import { useTabsStore } from "@/state/stores/tabs"; import { useWorkspacesStore } from "@/state/stores/workspaces"; import { copyTextViaIpc } from "@/utils/clipboard"; import { cn } from "@/utils/cn"; +import { ipcErrorToAppError } from "../../../../shared/ipc/result"; interface PickButtonProps { tabId: string; @@ -117,19 +120,24 @@ export function PickButton({ tabId, workspaceId }: PickButtonProps) { } pickingRef.current = true; setPicking(true); - const result = await ipcCallResult("cli", "pickElement", { tabId }); - pickingRef.current = false; - setPicking(false); - if (!result.ok) { - showToast({ kind: "error", message: t("browser.pick_failed", { message: result.message }) }); - return; + try { + const result = await ipcCallResult("cli", "pickElement", { tabId }); + if (!result.ok) { + surfaceError(ipcErrorToAppError(result), { surface: "toast" }); + return; + } + if (!("text" in result.value)) return; + const { text } = result.value; + const sessions = await agentSessions(workspaceId); + if (sessions.length === 0) copyInstead(text, t("browser.pick_no_agent")); + else if (sessions.length === 1 && sessions[0]) deliver(sessions[0], text); + else setChoice({ text, sessions }); + } catch (error) { + surfaceError(normaliseError(error), { surface: "toast" }); + } finally { + pickingRef.current = false; + setPicking(false); } - if (!("text" in result.value)) return; - const { text } = result.value; - const sessions = await agentSessions(workspaceId); - if (sessions.length === 0) copyInstead(text, t("browser.pick_no_agent")); - else if (sessions.length === 1 && sessions[0]) deliver(sessions[0], text); - else setChoice({ text, sessions }); }; const label = picking ? t("browser.cancel_pick") : t("browser.pick_element"); diff --git a/src/renderer/components/settings/panels/notes-panel.tsx b/src/renderer/components/settings/panels/notes-panel.tsx index 1cc036069..ec65ca7d9 100644 --- a/src/renderer/components/settings/panels/notes-panel.tsx +++ b/src/renderer/components/settings/panels/notes-panel.tsx @@ -7,12 +7,15 @@ import { FolderOpen, Trash2 } from "lucide-react"; import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { cn } from "@/utils/cn"; +import { ipcErrorToAppError } from "../../../../shared/ipc/result"; import type { NoteStorageEntry } from "../../../../shared/notes/types"; -import { ipcCallResult, unwrapIpcResult } from "../../../ipc/client"; +import { useIpcAction } from "../../../hooks/use-ipc-action"; +import { ipcCallResult } from "../../../ipc/client"; +import { surfaceError } from "../../../services/error-surface/surface-error"; import { notesApi } from "../../../services/notes/api"; import { formatBytes } from "../../notes/editor/asset-nodes"; +import { Button } from "../../ui/button"; import { showConfirmDialog } from "../../ui/confirm-dialog"; -import { showToast } from "../../ui/toast"; import { SettingsGroup, SettingsPage } from "../section"; type Entry = NoteStorageEntry & { workspaceIds: string[] }; @@ -30,17 +33,46 @@ export function NotesPanel() { const { t } = useTranslation("notes"); const [entries, setEntries] = useState(null); - const load = useCallback(async () => { - try { - setEntries(unwrapIpcResult(await ipcCallResult("notes", "storage", undefined)) as Entry[]); - } catch (e) { - showToast({ kind: "error", message: e instanceof Error ? e.message : String(e) }); + const { + run: runLoad, + state: loadState, + cancel: cancelLoad, + } = useIpcAction({ + onSuccess: setEntries, + }); + const load = useCallback(() => { + runLoad(async (signal) => { + const result = await ipcCallResult("notes", "storage", undefined, { signal }); + if (!result.ok) throw ipcErrorToAppError(result); + return result.value as Entry[]; + }); + }, [runLoad]); + useEffect(() => { + load(); + return notesApi.onChanged(() => { + cancelLoad(); + load(); + }); + }, [cancelLoad, load]); + + const loadError = loadState.status === "error" ? loadState.error : null; + const [loadMessage, setLoadMessage] = useState(null); + useEffect(() => { + if (!loadError) { + setLoadMessage(null); + return; } - }, []); + const present = surfaceError(loadError, { surface: "banner", onRetry: load }); + setLoadMessage( + present.surface === "banner" || present.surface === "inline" ? present.userMessage : null, + ); + }, [loadError, load]); + + const { run: runRemove, state: removeState } = useIpcAction({ onSuccess: load }); + const removeError = removeState.status === "error" ? removeState.error : null; useEffect(() => { - void load(); - return notesApi.onChanged(() => void load()); - }, [load]); + if (removeError) surfaceError(removeError, { surface: "toast" }); + }, [removeError]); const remove = async (entry: Entry) => { const ok = await showConfirmDialog({ @@ -53,12 +85,15 @@ export function NotesPanel() { variant: "destructive", }); if (!ok) return; - try { - unwrapIpcResult(await ipcCallResult("notes", "removeLocation", { key: entry.location.key })); - } catch (e) { - showToast({ kind: "error", message: e instanceof Error ? e.message : String(e) }); - } - void load(); + runRemove(async (signal) => { + const result = await ipcCallResult( + "notes", + "removeLocation", + { key: entry.location.key }, + { signal }, + ); + if (!result.ok) throw ipcErrorToAppError(result); + }); }; const sum = (entries ?? []).reduce((a, e) => a + total(e), 0); @@ -67,6 +102,18 @@ export function NotesPanel() { return ( + {loadError && ( +
    + {loadMessage && ( +

    + {loadMessage} +

    + )} + +
    + )} {entries === null ? null : entries.length === 0 ? (

    {t("storage.empty")}

    ) : ( @@ -129,6 +176,7 @@ export function NotesPanel() { aria-label={t("storage.remove")} title={t("storage.remove")} onClick={() => void remove(entry)} + disabled={removeState.status === "loading"} >