diff --git a/main/handlers/index.ts b/main/handlers/index.ts index 62ed71a5db..fa1a4ac9cb 100644 --- a/main/handlers/index.ts +++ b/main/handlers/index.ts @@ -30,6 +30,7 @@ import { registerSubagentHandlers } from "./subagents.js"; import { registerAssistantLiveHandlers } from "./assistant-live.js"; import { registerAidenRemoteHandlers } from "./aiden-remote.js"; import { registerPeerHostHandlers } from "./peer-hosts.js"; +import { registerLocalRunIpc } from "./local-runs-main.js"; import { registerBotHandlers } from "./bots.js"; import { registerBotRoutineHandlers } from "./bot-routines.js"; import { registerDiagnosticHandlers } from "./diagnostics.js"; @@ -84,6 +85,7 @@ export function registerHandlers(): void { registerAssistantLiveHandlers(); registerAidenRemoteHandlers(); registerPeerHostHandlers(); + registerLocalRunIpc(); if (hostPlatformCapabilities().bots) registerBotHandlers(); registerBtwHandlers(); registerTtsHandlers(); diff --git a/main/handlers/local-runs-main.ts b/main/handlers/local-runs-main.ts new file mode 100644 index 0000000000..674a0a325a --- /dev/null +++ b/main/handlers/local-runs-main.ts @@ -0,0 +1,51 @@ +import { ipcMain, logger } from "../platform.js"; +import { hostRunRegistry } from "../services/host-runs-main.js"; +import { llmClient } from "../services/llm-client.js"; +import { LocalRunObservers } from "../services/local-run-observers.js"; +import { rendererDocumentOwner } from "../services/renderer-document-owner.js"; +import { registerLocalRunHandlers } from "./local-runs.js"; + +let observers: LocalRunObservers | null = null; + +function localRunObservers(): LocalRunObservers { + observers ??= new LocalRunObservers({ + registry: hostRunRegistry, + setTimer: (callback, ms) => setTimeout(callback, ms), + clearTimer: (handle) => clearTimeout(handle as ReturnType), + }); + return observers; +} + +export function registerLocalRunIpc(): void { + registerLocalRunHandlers({ + handle: (channel, handler) => ipcMain.handle(channel, handler), + owner: (event) => { + const owner = rendererDocumentOwner( + event, + () => new Error("Watching a run requires an active application document."), + ); + return { + key: `${owner.id}:${owner.documentId}`, + isDestroyed: owner.isDestroyed, + send: owner.send, + onInvalidated: owner.onInvalidated, + }; + }, + observers: localRunObservers, + stopRun: (runId) => { + const summary = hostRunRegistry.summary(runId); + if (!summary || summary.state === "done" || summary.state === "failed" || summary.state === "cancelled") { + return false; + } + // The same host-authority stop Aiden Remote's run controls use. + const cancelled = llmClient.cancel(runId, "user_stop"); + if (cancelled) logger.info("chat", JSON.stringify({ event: "renderer_host_run_stop", runId })); + return cancelled; + }, + isRunSettled: (runId) => { + const state = hostRunRegistry.summary(runId)?.state; + const terminal = state === "done" || state === "failed" || state === "cancelled"; + return terminal && !llmClient.isGenerationLive(runId); + }, + }); +} diff --git a/main/handlers/local-runs.test.ts b/main/handlers/local-runs.test.ts new file mode 100644 index 0000000000..ef8769480a --- /dev/null +++ b/main/handlers/local-runs.test.ts @@ -0,0 +1,402 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { LocalRunFrameMessage } from "../../renderer/shared/local-run-frames.js"; +import type { PeerRunSubscription } from "../../renderer/shared/peer-host.js"; +import { HostRunRegistry } from "../services/host-run-registry.js"; +import { LOCAL_RUN_BATCH_MS, LocalRunObservers } from "../services/local-run-observers.js"; +import { registerLocalRunHandlers, type LocalRunOwner } from "./local-runs.js"; +import { LocalHostAdapter } from "../../renderer/lib/hosts/local-host-adapter.js"; +import { observeLocalRun } from "../../renderer/lib/hosts/observed-local-run.js"; +import { + detachedLifecycleChatProjection, + isDetachedLifecycleChatDraining, +} from "../../renderer/lib/chat-terminal-sync.js"; + +class FakeTimers { + private now = 0; + private next = 1; + private readonly pending = new Map void }>(); + set = (callback: () => void, ms: number): unknown => { + const id = this.next++; + this.pending.set(id, { at: this.now + ms, callback }); + return id; + }; + clear = (handle: unknown): void => { + this.pending.delete(handle as number); + }; + get size(): number { + return this.pending.size; + } + advance(ms: number): void { + this.now += ms; + for (const [id, timer] of [...this.pending].sort((a, b) => a[1].at - b[1].at)) { + if (timer.at > this.now || !this.pending.has(id)) continue; + this.pending.delete(id); + timer.callback(); + } + } +} + +/** One renderer main-frame document; `navigate` invalidates it like a reload. */ +class FakeDocument implements LocalRunOwner { + readonly messages: LocalRunFrameMessage[] = []; + /** The document's preload notification listener, when a test wires one. */ + deliver: ((payload: LocalRunFrameMessage) => void) | null = null; + private destroyed = false; + private readonly listeners = new Set<() => void>(); + constructor(readonly key: string) {} + isDestroyed(): boolean { + return this.destroyed; + } + send(channel: string, payload: LocalRunFrameMessage): void { + assert.equal(channel, "runs:local-frame"); + if (this.destroyed) throw new Error("Render frame was disposed."); + this.messages.push(structuredClone(payload)); + this.deliver?.(structuredClone(payload)); + } + onInvalidated(listener: () => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + navigate(): void { + this.destroyed = true; + for (const listener of [...this.listeners]) { + this.listeners.delete(listener); + listener(); + } + } + /** Every frame received so far, flattened to `type@sequence` or `state:`. */ + frames(): string[] { + return this.messages.flatMap((message) => + message.frames.map((frame) => + frame.kind === "event" ? `${frame.event.type}@${frame.event.sequence}` : `state:${frame.state}`, + ), + ); + } +} + +type FakeEvent = { document: FakeDocument | null }; + +function setup() { + const clock = { now: 1_000 }; + const registry = new HostRunRegistry({ now: () => clock.now, epoch: "epoch-local", deltaCoalesceMs: 0 }); + const timers = new FakeTimers(); + let ids = 0; + const observers = new LocalRunObservers({ + registry, + setTimer: timers.set, + clearTimer: timers.clear, + newId: () => `local-run-${++ids}`, + }); + const stops: string[] = []; + const live = new Set(); + const handlers = new Map unknown>(); + registerLocalRunHandlers({ + handle: (channel, handler) => handlers.set(channel, handler), + owner: (event) => { + if (!event.document) throw new Error("Run actions require an active application document."); + return event.document; + }, + observers: () => observers, + stopRun: (runId) => { + const summary = registry.summary(runId); + if (!summary || summary.state === "done" || summary.state === "failed" || summary.state === "cancelled") { + return false; + } + stops.push(runId); + registry.publish(runId, "chat:done", { cancelled: true }); + return true; + }, + isRunSettled: (runId) => { + const state = registry.summary(runId)?.state; + return (state === "done" || state === "failed" || state === "cancelled") && !live.has(runId); + }, + }); + const invoke = async (channel: string, from: FakeDocument | null, ...args: unknown[]) => { + const handler = handlers.get(channel); + assert.ok(handler, channel); + return handler({ document: from }, ...args); + }; + const observe = (from: FakeDocument, chatId: string, cursor?: unknown) => + invoke("runs:observeLocal", from, chatId, cursor) as Promise; + const frame = () => timers.advance(LOCAL_RUN_BATCH_MS); + return { clock, registry, timers, observers, stops, live, invoke, observe, frame }; +} + +const eventKeys = (subscription: PeerRunSubscription) => + subscription.events.map((event) => `${event.type}@${event.sequence}`); + +test("a phone-started run reaches the watching window live, one batch per frame, and ends with run.ended", async () => { + const { registry, observe, frame, timers } = setup(); + registry.begin({ runId: "run-1", chatId: "chat-1", origin: "remote" }); + registry.publish("run-1", "chat:delta", { delta: "Hel" }); + + const page = new FakeDocument("1:doc-a"); + const subscription = await observe(page, "chat-1"); + assert.equal(subscription.runId, "run-1"); + assert.equal(subscription.state, "streaming"); + assert.deepEqual(eventKeys(subscription), ["run.started@1", "text_delta@2"]); + assert.deepEqual(subscription.events[0]!.payload, { runId: "run-1", chatId: "chat-1", origin: "remote" }); + + registry.publish("run-1", "chat:delta", { delta: "lo" }); + registry.publish("run-1", "chat:delta", { delta: " there" }); + assert.equal(page.messages.length, 0, "nothing is sent before the frame boundary"); + frame(); + assert.equal(page.messages.length, 1, "deltas within one frame share one message"); + assert.equal(page.messages[0]!.subscriptionId, subscription.subscriptionId); + assert.deepEqual(page.frames(), ["text_delta@3", "text_delta@4"]); + assert.deepEqual( + page.messages[0]!.frames.map((entry) => (entry.kind === "event" ? entry.event.payload : null)), + [{ text: "lo" }, { text: " there" }], + ); + + registry.publish("run-1", "chat:done", { chat: { messages: [{ id: "assistant-1", role: "assistant" }] } }); + frame(); + assert.deepEqual(page.frames().slice(2), ["done@5", "run.ended@5", "state:ended"]); + const ended = page.messages[1]!.frames[1]!; + assert.ok(ended.kind === "event"); + assert.deepEqual(ended.event.payload, { runId: "run-1", chatId: "chat-1", state: "done" }); + assert.equal(timers.size, 0, "an ended run leaves no timer behind"); +}); + +test("a window watching one chat never receives another chat's frames", async () => { + const { registry, observe, frame } = setup(); + registry.begin({ runId: "run-1", chatId: "chat-1", origin: "remote" }); + registry.begin({ runId: "run-2", chatId: "chat-2", origin: "remote" }); + const page = new FakeDocument("1:doc-a"); + const other = new FakeDocument("2:doc-b"); + await observe(page, "chat-1"); + await observe(other, "chat-2"); + + registry.publish("run-2", "chat:delta", { delta: "for chat two" }); + registry.publish("run-1", "chat:delta", { delta: "for chat one" }); + frame(); + + assert.deepEqual(page.messages.map((message) => message.chatId), ["chat-1"]); + assert.deepEqual(page.frames(), ["text_delta@2"]); + assert.deepEqual(other.messages.map((message) => message.chatId), ["chat-2"]); + assert.deepEqual(other.frames(), ["text_delta@2"]); +}); + +test("a cursor resumes after the last delivered event and is ignored once the chat moved on", async () => { + const { clock, registry, observe } = setup(); + registry.begin({ runId: "run-1", chatId: "chat-1", origin: "remote" }); + for (const delta of ["a", "b", "c"]) registry.publish("run-1", "chat:delta", { delta }); + const page = new FakeDocument("1:doc-a"); + + const resumed = await observe(page, "chat-1", { runId: "run-1", sequence: 2 }); + assert.deepEqual(eventKeys(resumed), ["text_delta@3", "text_delta@4"]); + + // A cursor at the end of a finished run still yields the closing run.ended. + registry.publish("run-1", "chat:done", {}); + const caughtUp = await observe(page, "chat-1", { runId: "run-1", sequence: 5 }); + assert.deepEqual(eventKeys(caughtUp), ["run.ended@5"]); + assert.equal(caughtUp.state, "ended"); + + // Without a cursor, a finished run is already in the persisted transcript. + const late = await observe(page, "chat-1"); + assert.deepEqual(late.events, []); + assert.equal(late.state, "ended"); + + clock.now += 1_000; + registry.begin({ runId: "run-2", chatId: "chat-1", origin: "remote" }); + const moved = await observe(page, "chat-1", { runId: "run-1", sequence: 5 }); + assert.equal(moved.runId, "run-2"); + assert.deepEqual(eventKeys(moved), ["run.started@1"], "another run's cursor replays the new run whole"); + + const idle = await observe(page, "chat-idle"); + assert.equal(idle.runId, null); + assert.equal(idle.state, "idle"); +}); + +test("a parked observation picks up the chat's next run", async () => { + const { clock, registry, observe, frame } = setup(); + const page = new FakeDocument("1:doc-a"); + const subscription = await observe(page, "chat-1"); + assert.equal(subscription.state, "idle"); + + registry.begin({ runId: "run-1", chatId: "chat-1", origin: "remote" }); + registry.publish("run-1", "chat:delta", { delta: "hi" }); + frame(); + assert.deepEqual(page.frames(), ["state:streaming", "run.started@1", "text_delta@2"]); + const adopted = page.messages[0]!.frames[0]!; + assert.ok(adopted.kind === "state"); + assert.equal(adopted.runId, "run-1"); + + registry.publish("run-1", "chat:done", {}); + frame(); + clock.now += 1_000; + registry.begin({ runId: "run-2", chatId: "chat-1", origin: "remote" }); + frame(); + assert.deepEqual(page.frames().slice(3), [ + "done@3", + "run.ended@3", + "state:ended", + "state:streaming", + "run.started@1", + ]); +}); + +test("a document that goes away releases its observations and receives nothing more", async () => { + const { registry, observers, observe, invoke, frame, timers } = setup(); + registry.begin({ runId: "run-1", chatId: "chat-1", origin: "remote" }); + const page = new FakeDocument("1:doc-a"); + const second = new FakeDocument("2:doc-b"); + const mine = await observe(page, "chat-1"); + await observe(page, "chat-1"); + const theirs = await observe(second, "chat-1"); + assert.equal(observers.size, 3); + + assert.equal( + await invoke("runs:unobserveLocal", second, mine.subscriptionId), + false, + "a window cannot release another window's observation", + ); + + registry.publish("run-1", "chat:delta", { delta: "pending" }); + page.navigate(); + assert.equal(observers.size, 1, "navigation releases every observation of that document"); + frame(); + assert.equal(page.messages.length, 0, "a released observation's queued batch is dropped"); + assert.equal(second.messages.length, 1); + + // The reloaded document (same frame) cannot release the old observation again. + assert.equal(await invoke("runs:unobserveLocal", new FakeDocument("1:doc-a"), mine.subscriptionId), false); + + assert.equal(await invoke("runs:unobserveLocal", second, theirs.subscriptionId), true); + assert.equal(observers.size, 0); + registry.publish("run-1", "chat:delta", { delta: "nobody watching" }); + assert.equal(timers.size, 0, "with nobody watching, a delta schedules nothing"); +}); + +test("a document destroyed without navigation is released at its next flush", async () => { + const { registry, observers, observe, frame } = setup(); + registry.begin({ runId: "run-1", chatId: "chat-1", origin: "remote" }); + const page = new FakeDocument("1:doc-a"); + await observe(page, "chat-1"); + // Destroyed without its invalidation firing first (a crashed renderer). + (page as unknown as { destroyed: boolean }).destroyed = true; + registry.publish("run-1", "chat:delta", { delta: "x" }); + frame(); + assert.equal(page.messages.length, 0); + assert.equal(observers.size, 0); +}); + +test("only an active document with well-formed input can observe or stop a run", async () => { + const { registry, invoke, stops } = setup(); + registry.begin({ runId: "run-1", chatId: "chat-1", origin: "remote" }); + const page = new FakeDocument("1:doc-a"); + + await assert.rejects(invoke("runs:observeLocal", null, "chat-1"), /active application document/u); + await assert.rejects(invoke("runs:observeLocal", page, "../chat"), /Invalid chat identifier/u); + await assert.rejects(invoke("runs:observeLocal", page, "chat-1", { runId: "run-1", sequence: -1 }), /Invalid run cursor/u); + await assert.rejects(invoke("runs:observeLocal", page, "chat-1", "run-1"), /Invalid run cursor/u); + await assert.rejects(invoke("runs:stopLocal", page, 42), /Invalid run identifier/u); + + assert.equal(await invoke("runs:stopLocal", page, "run-1"), true); + assert.deepEqual(stops, ["run-1"]); + assert.equal(registry.summary("run-1")?.state, "cancelled"); + assert.equal(await invoke("runs:stopLocal", page, "run-1"), false, "a finished run cannot be stopped again"); + assert.equal(await invoke("runs:stopLocal", page, "run-unknown"), false); + + page.navigate(); + await assert.rejects(invoke("runs:stopLocal", page, "run-1"), /application document changed/u); + await assert.rejects(invoke("runs:observeLocal", page, "chat-1"), /application document changed/u); +}); + +test("a settled query names only runs that finished and that nothing still runs", async () => { + const { clock, registry, invoke, live } = setup(); + const page = new FakeDocument("1:doc-a"); + registry.begin({ runId: "run-old", chatId: "chat-1", origin: "renderer" }); + registry.publish("run-old", "chat:done", {}); + clock.now += 1_000; + registry.begin({ runId: "run-phone", chatId: "chat-1", origin: "remote" }); + registry.begin({ runId: "run-saving", chatId: "chat-2", origin: "renderer" }); + registry.publish("run-saving", "chat:done", {}); + live.add("run-saving"); + + assert.deepEqual( + await invoke("runs:settledLocal", page, ["run-old", "run-phone", "run-saving", "run-unknown", "run-old"]), + ["run-old"], + "the busy chat's newer run does not hold back the finished one; a run still persisting or unknown is not settled", + ); + await assert.rejects(invoke("runs:settledLocal", page, "run-old"), /Invalid run identifiers/u); + await assert.rejects(invoke("runs:settledLocal", page, ["../x"]), /Invalid run identifier/u); + await assert.rejects(invoke("runs:settledLocal", page, Array.from({ length: 65 }, (_, i) => `run-${i}`)), /Invalid run identifiers/u); + page.navigate(); + await assert.rejects(invoke("runs:settledLocal", page, ["run-old"]), /application document changed/u); +}); + +test("the watching window shows a phone's reply as it streams, stops it, and lets the saved reply replace it", async () => { + const { registry, invoke, frame, timers, observers } = setup(); + const page = new FakeDocument("1:doc-a"); + const listeners = new Set<(message: LocalRunFrameMessage) => void>(); + page.deliver = (message) => { + for (const listener of listeners) listener(message); + }; + // The renderer side exactly as the pane uses it, over this process's IPC handlers. + const adapter = new LocalHostAdapter({ + rename: async () => {}, + remove: async () => {}, + markRead: async () => true, + approve: async () => {}, + answerQuestionnaire: async () => ({ status: "expired" }), + respondRemoteApproval: async () => ({ resolved: true }), + respondRemoteQuestion: async () => ({ status: "answered" }), + admitRunInput: async () => ({ admitted: false, committed: false, reason: "run_not_active" }), + // This window did not start the phone's run, so its own Stop declines it. + stop: async () => false, + observeRun: (chatId) => invoke("runs:observeLocal", page, chatId, null) as Promise, + unobserveRun: (id) => invoke("runs:unobserveLocal", page, id) as Promise, + onRunFrame: (handler) => { + listeners.add(handler); + return () => listeners.delete(handler); + }, + stopHostRun: (runId) => invoke("runs:stopLocal", page, runId) as Promise, + }); + let reads = 0; + let settledReads = 0; + const chatId = "chat-phone"; + const observation = observeLocalRun({ + adapter, + chatId, + workspaceId: "workspace-1", + refetch: async () => { + reads++; + const state = registry.summary("run-phone")?.state; + if (state !== "cancelled" && state !== "done") return { kind: "read", messages: [{ role: "user" }] }; + settledReads++; + // The stopped reply was saved before the run settled. + return { kind: "read", messages: [{ role: "user" }, { role: "assistant", timeline: { generationId: "run-phone" } }] }; + }, + schedule: (publish) => publish(), + }); + await new Promise((settle) => setImmediate(settle)); + assert.equal(detachedLifecycleChatProjection(chatId, "workspace-1"), null, "nothing runs yet"); + + registry.begin({ runId: "run-phone", chatId, origin: "remote" }); + registry.publish("run-phone", "chat:delta", { delta: "Drafting " }); + frame(); + registry.publish("run-phone", "chat:reasoning-delta", { delta: "Weighing options" }); + registry.publish("run-phone", "chat:delta", { delta: "the summary" }); + frame(); + await new Promise((settle) => setImmediate(settle)); + const live = detachedLifecycleChatProjection(chatId, "workspace-1"); + assert.equal(live?.content, "Drafting the summary", "the reply is on screen before the run settles"); + assert.equal(live?.reasoning, "Weighing options"); + assert.equal(registry.summary("run-phone")?.state, "working", "the run is still going"); + assert.equal(reads, 1, "the phone's saved message is read once when its run starts"); + + assert.equal(await adapter.cancel(chatId, { runId: "run-phone" }), true); + frame(); + await new Promise((settle) => setImmediate(settle)); + assert.equal(registry.summary("run-phone")?.state, "cancelled"); + assert.equal(settledReads, 1, "the finished turn is re-read once"); + assert.equal(detachedLifecycleChatProjection(chatId, "workspace-1"), null); + assert.equal(isDetachedLifecycleChatDraining(chatId, "workspace-1"), false); + + observation.close(); + await new Promise((settle) => setImmediate(settle)); + assert.equal(observers.size, 0, "closing the pane releases its observation in main"); + assert.equal(timers.size, 0); +}); diff --git a/main/handlers/local-runs.ts b/main/handlers/local-runs.ts new file mode 100644 index 0000000000..d766a1a9be --- /dev/null +++ b/main/handlers/local-runs.ts @@ -0,0 +1,98 @@ +import { isSafeSubagentIdentifier } from "../../renderer/shared/subagent-runs.js"; +import { + parseLocalRunCursor, + type LOCAL_RUN_FRAME_CHANNEL, + type LocalRunFrameMessage, +} from "../../renderer/shared/local-run-frames.js"; +import type { LocalRunObservers } from "../services/local-run-observers.js"; + +/** The renderer document that made a request. */ +export interface LocalRunOwner { + /** Stable for one document; a reload or navigation is a new owner. */ + readonly key: string; + isDestroyed(): boolean; + send(channel: typeof LOCAL_RUN_FRAME_CHANNEL, payload: LocalRunFrameMessage): void; + /** Runs once when the document goes away; returns a detach function. */ + onInvalidated(listener: () => void): () => void; +} + +export interface LocalRunHandlerDependencies { + handle(channel: string, handler: (event: Event, ...args: unknown[]) => unknown): void; + /** Throws for a sender that is not the current main frame. */ + owner(event: Event): LocalRunOwner; + observers(): LocalRunObservers; + /** + * Host-authority Stop for a run this process hosts, whoever started it: the + * same control a paired phone with `runs:control` has. Resolves false when + * the run is unknown or already finished. + */ + stopRun(runId: string): boolean; + /** + * Whether a generation has finished for good: the host journal holds its + * terminal state and nothing in this process is still running it. Unknown + * runs are not proof, so they report false. + */ + isRunSettled(runId: string): boolean; +} + +/** Bound on one settled query; a document retains far fewer detached streams. */ +const MAX_SETTLED_QUERY = 64; + +const INACTIVE = "The application document changed."; + +function identifier(value: unknown, label: string): string { + if (!isSafeSubagentIdentifier(value)) throw new Error(`Invalid ${label}.`); + return value; +} + +/** + * The Mac's own live mirror of runs it hosts but this document did not start + * (a phone's turn, another window's). Frames go only to the subscribing + * document and stop with it. + */ +export function registerLocalRunHandlers(dependencies: LocalRunHandlerDependencies): void { + const { handle } = dependencies; + + const active = (event: Event): LocalRunOwner => { + const owner = dependencies.owner(event); + if (owner.isDestroyed()) throw new Error(INACTIVE); + return owner; + }; + + handle("runs:observeLocal", (event, chatId, cursor) => { + const owner = active(event); + const id = identifier(chatId, "chat identifier"); + const after = parseLocalRunCursor(cursor); + return dependencies.observers().observe( + { + key: owner.key, + isDestroyed: () => owner.isDestroyed(), + // A literal so the IPC inventory sees it; the parameter type pins it to the shared constant. + send: (message) => owner.send("runs:local-frame", message), + onInvalidated: (listener) => owner.onInvalidated(listener), + }, + id, + after, + ); + }); + + handle("runs:unobserveLocal", (event, subscriptionId) => { + const owner = dependencies.owner(event); + const id = identifier(subscriptionId, "run subscription"); + return dependencies.observers().unobserve(owner.key, id); + }); + + handle("runs:stopLocal", (event, runId) => { + active(event); + return dependencies.stopRun(identifier(runId, "run identifier")); + }); + + // Lets a document drop a drain marker it holds for a run that ended while + // the chat stayed busy with a newer run (a phone's turn right after it). + handle("runs:settledLocal", (event, runIds) => { + active(event); + if (!Array.isArray(runIds) || runIds.length > MAX_SETTLED_QUERY) throw new Error("Invalid run identifiers."); + const ids = runIds.map((runId) => identifier(runId, "run identifier")); + return [...new Set(ids)].filter((runId) => dependencies.isRunSettled(runId)); + }); +} diff --git a/main/services/aiden-remote-host-runs.ts b/main/services/aiden-remote-host-runs.ts index 8f64bb2440..c5b684c41e 100644 --- a/main/services/aiden-remote-host-runs.ts +++ b/main/services/aiden-remote-host-runs.ts @@ -25,6 +25,7 @@ import { import { openCursorSse, sseFrame, type CursorSseHandle, type CursorSsePull } from "./aiden-remote-sse.js"; import type { HostRunEvent, + HostRunRead, HostRunRegistry, HostRunSummary, } from "./host-run-registry.js"; @@ -177,7 +178,7 @@ function ownRecord(value: unknown): Record | undefined { * observers keep the mobile summary projection; controllers get the details * they need to decide. */ -type RunProjection = "full" | "observer" | "phone"; +export type RunProjection = "full" | "observer" | "phone"; function projectPayload( type: string, @@ -197,6 +198,83 @@ function projectPayload( }; } +/** + * One journal event in the run-stream wire vocabulary: `run_started` becomes + * `run.started`, a provider restart becomes a `reset` snapshot, and approval + * payloads take the reader's projection. The Remote SSE stream and the local + * renderer mirror share it. + */ +export function hostRunWireEvent( + event: HostRunEvent, + chatId: string, + projection: RunProjection, +): AidenRemoteRunEvent { + const type = event.type === "run_started" ? "run.started" : event.type; + const payload = event.type === "run_started" + ? { runId: event.runId, chatId, origin: event.payload.origin } + : event.type === "snapshot" + ? { runId: event.runId, chatId, reason: "reset", nextSequence: event.sequence + 1 } + : projectPayload(event.type, event.payload, projection); + return { + protocolVersion: AIDEN_REMOTE_PROTOCOL_VERSION, + streamId: event.runId, + sequence: event.sequence, + timestamp: event.timestamp, + type, + terminal: event.terminal, + payload, + }; +} + +/** + * The `gap` snapshot a reader gets when its cursor fell behind retention: the + * run's state and every pending prompt, so it can rebuild attention and read + * the persisted transcript. It sits at the sequence before the oldest event. + */ +export function hostRunGapSnapshotEvent( + read: Extract, + projection: RunProjection, +): AidenRemoteRunEvent { + const summary = read.summary; + return { + protocolVersion: AIDEN_REMOTE_PROTOCOL_VERSION, + streamId: summary.runId, + sequence: read.nextSequence - 1, + timestamp: summary.updatedAt, + type: "snapshot", + terminal: false, + payload: { + runId: summary.runId, + chatId: summary.chatId, + reason: "gap", + epoch: read.epoch, + state: summary.state, + pendingApprovalIds: summary.pendingApprovalIds, + pendingQuestionIds: summary.pendingQuestionIds, + approvals: read.prompts + .filter((prompt) => prompt.type === "approval_required") + .map((prompt) => projectPayload(prompt.type, prompt.payload, projection)), + questions: read.prompts + .filter((prompt) => prompt.type === "question_required") + .map((prompt) => prompt.payload), + nextSequence: read.nextSequence, + }, + }; +} + +/** The synthesized last event of a terminal run, repeating its final sequence. */ +export function hostRunEndedEvent(summary: HostRunSummary): AidenRemoteRunEvent { + return { + protocolVersion: AIDEN_REMOTE_PROTOCOL_VERSION, + streamId: summary.runId, + sequence: summary.lastSequence, + timestamp: summary.updatedAt, + type: "run.ended", + terminal: true, + payload: { runId: summary.runId, chatId: summary.chatId, state: summary.state }, + }; +} + /** * Same policy as phone-owned stream approvals: an approval carrying host-only * details (anything but a scheduled-task summary or the Computer Use access @@ -360,27 +438,14 @@ export class AidenRemoteHostRunService { const frames: string[] = []; if (read.kind === "snapshot_required") { const resume = read.nextSequence - 1; - frames.push(this.frame(read.summary, resume, "snapshot", { - runId, - chatId: read.summary.chatId, - reason: "gap", - epoch: read.epoch, - state: read.summary.state, - pendingApprovalIds: read.summary.pendingApprovalIds, - pendingQuestionIds: read.summary.pendingQuestionIds, - approvals: read.prompts - .filter((prompt) => prompt.type === "approval_required") - .map((prompt) => projectPayload(prompt.type, prompt.payload, projection)), - questions: read.prompts - .filter((prompt) => prompt.type === "question_required") - .map((prompt) => prompt.payload), - nextSequence: read.nextSequence, - }, read.summary.updatedAt)); + const gap = hostRunGapSnapshotEvent(read, projection); + frames.push(sseFrame(String(gap.sequence), gap.type, gap)); cursor = resume; return { frames }; } for (const event of read.events) { - frames.push(this.eventFrame(event, read.summary.chatId, projection)); + const wire = hostRunWireEvent(event, read.summary.chatId, projection); + frames.push(sseFrame(String(wire.sequence), wire.type, wire)); cursor = event.sequence; } if ( @@ -388,11 +453,8 @@ export class AidenRemoteHostRunService { cursor === read.summary.lastSequence ) { endedSent = true; - frames.push(this.frame(read.summary, cursor, "run.ended", { - runId, - chatId: read.summary.chatId, - state: read.summary.state, - }, read.summary.updatedAt, true)); + const ended = hostRunEndedEvent(read.summary); + frames.push(sseFrame(String(ended.sequence), ended.type, ended)); return { frames, end: true }; } return { frames }; @@ -700,43 +762,4 @@ export class AidenRemoteHostRunService { outcome.error.details, ); } - - private eventFrame(event: HostRunEvent, chatId: string, projection: RunProjection): string { - const type = event.type === "run_started" ? "run.started" : event.type; - const payload = event.type === "run_started" - ? { runId: event.runId, chatId, origin: event.payload.origin } - : event.type === "snapshot" - ? { runId: event.runId, chatId, reason: "reset", nextSequence: event.sequence + 1 } - : projectPayload(event.type, event.payload, projection); - const wire: AidenRemoteRunEvent = { - protocolVersion: AIDEN_REMOTE_PROTOCOL_VERSION, - streamId: event.runId, - sequence: event.sequence, - timestamp: event.timestamp, - type, - terminal: event.terminal, - payload, - }; - return sseFrame(String(event.sequence), type, wire); - } - - private frame( - summary: HostRunSummary, - sequence: number, - type: string, - payload: Record, - timestamp: string, - terminal = false, - ): string { - const wire: AidenRemoteRunEvent = { - protocolVersion: AIDEN_REMOTE_PROTOCOL_VERSION, - streamId: summary.runId, - sequence, - timestamp, - type, - terminal, - payload, - }; - return sseFrame(String(sequence), type, wire); - } } diff --git a/main/services/llm-client.ts b/main/services/llm-client.ts index e2d6899cf4..fd4ee66f1c 100644 --- a/main/services/llm-client.ts +++ b/main/services/llm-client.ts @@ -4601,6 +4601,11 @@ export const llmClient = { return chatTurnAdmission.isAdmitted(chatId) || chatHasGenerationOwnership(chatId); }, + /** Whether this exact generation is still starting or running, whoever owns it. */ + isGenerationLive(streamId: string): boolean { + return active.has(streamId) || initializing.has(streamId); + }, + /** Detect only orphaned renderer ownership; normal visible generations never delay reads. */ isChatOwnedByInactiveRenderer(chatId: string): boolean { return ( diff --git a/main/services/local-run-observers.ts b/main/services/local-run-observers.ts new file mode 100644 index 0000000000..5cb934feb8 --- /dev/null +++ b/main/services/local-run-observers.ts @@ -0,0 +1,309 @@ +import { randomUUID } from "node:crypto"; +import type { + PeerRunEvent, + PeerRunStreamState, + PeerRunSubscription, +} from "../../renderer/shared/peer-host.js"; +import type { + LocalRunCursor, + LocalRunFrame, + LocalRunFrameMessage, +} from "../../renderer/shared/local-run-frames.js"; +import { + hostRunEndedEvent, + hostRunGapSnapshotEvent, + hostRunWireEvent, +} from "./aiden-remote-host-runs.js"; +import type { HostRunRegistry, HostRunState, HostRunSummary } from "./host-run-registry.js"; + +/** One frame batch per display frame: deltas arriving within it share one IPC message. */ +export const LOCAL_RUN_BATCH_MS = 16; +/** Journal events read per flush; a longer backlog continues on the next frame. */ +const MAX_EVENTS_PER_FLUSH = 256; + +export type LocalRunObserverRegistry = Pick< + HostRunRegistry, + "currentRunForChat" | "read" | "subscribe" | "onChange" +>; + +/** The renderer document that subscribed. Frames go to it alone. */ +export interface LocalRunObserverTarget { + /** Stable for one document; a reload or navigation is a new target. */ + readonly key: string; + isDestroyed(): boolean; + send(message: LocalRunFrameMessage): void; + /** Runs once when the document goes away; returns a detach function. */ + onInvalidated(listener: () => void): () => void; +} + +export interface LocalRunObserversOptions { + registry: LocalRunObserverRegistry; + setTimer(callback: () => void, ms: number): unknown; + clearTimer(handle: unknown): void; + batchMs?: number; + maxEventsPerFlush?: number; + newId?(): string; +} + +interface Observation { + readonly id: string; + readonly target: LocalRunObserverTarget; + readonly chatId: string; + runId: string | null; + /** The last journal sequence delivered for `runId`. */ + cursor: number; + ended: boolean; + state: PeerRunStreamState; + releaseRun: () => void; + queued: LocalRunFrame[]; + timer: unknown; +} + +function isTerminal(state: HostRunState): boolean { + return state === "done" || state === "failed" || state === "cancelled"; +} + +/** + * Mirrors this process's own host-run journal into renderer documents that + * are watching a chat they did not start. Each observation follows the chat's + * current run, batches its events into one message per frame, and is released + * when its document unsubscribes, navigates or is destroyed. With nobody + * watching, it holds no registry subscription and no change listener. + */ +export class LocalRunObservers { + private readonly observations = new Map(); + private readonly targets = new Map void; ids: Set }>(); + private offChange: (() => void) | null = null; + private readonly batchMs: number; + private readonly maxEventsPerFlush: number; + private readonly newId: () => string; + + constructor(private readonly options: LocalRunObserversOptions) { + this.batchMs = options.batchMs ?? LOCAL_RUN_BATCH_MS; + this.maxEventsPerFlush = options.maxEventsPerFlush ?? MAX_EVENTS_PER_FLUSH; + this.newId = options.newId ?? (() => `local-run-${randomUUID()}`); + } + + /** Live observations (diagnostics and tests). */ + get size(): number { + return this.observations.size; + } + + /** + * Starts following `chatId`'s current run. The result carries every event + * after `cursor` (or the whole retained run when the cursor names another + * run); later events arrive as batched frames. A run that had already ended + * before an observer without its cursor arrived is reported `ended` without + * a replay, since the persisted transcript already holds it. + */ + observe(target: LocalRunObserverTarget, chatId: string, cursor?: LocalRunCursor): PeerRunSubscription { + if (target.isDestroyed()) throw new Error("The application document changed."); + const observation: Observation = { + id: this.newId(), + target, + chatId, + runId: null, + cursor: 0, + ended: false, + state: "idle", + releaseRun: () => {}, + queued: [], + timer: undefined, + }; + this.observations.set(observation.id, observation); + this.bindTarget(target, observation.id); + this.offChange ??= this.options.registry.onChange((summary, removed) => this.runChanged(summary, removed)); + + const summary = this.options.registry.currentRunForChat(chatId); + let events: PeerRunEvent[] = []; + if (summary) { + const resumes = cursor !== undefined && cursor.runId === summary.runId && cursor.sequence <= summary.lastSequence; + observation.runId = summary.runId; + if (isTerminal(summary.state) && !resumes) { + observation.cursor = summary.lastSequence; + observation.ended = true; + observation.state = "ended"; + } else { + observation.cursor = resumes ? cursor.sequence : 0; + observation.state = "streaming"; + events = this.drain(observation); + // The subscription itself reports the resulting state. + observation.queued.length = 0; + if (!observation.ended) this.subscribeRun(observation); + } + } + return { + subscriptionId: observation.id, + key: observation.id, + runId: observation.runId, + chatId, + state: observation.state, + events, + truncated: false, + }; + } + + /** Stops one observation; only its own document may stop it. */ + unobserve(targetKey: string, subscriptionId: string): boolean { + const observation = this.observations.get(subscriptionId); + if (!observation || observation.target.key !== targetKey) return false; + this.release(observation); + return true; + } + + /** Releases everything a document was watching. */ + releaseTarget(targetKey: string): void { + const bound = this.targets.get(targetKey); + if (!bound) return; + for (const id of [...bound.ids]) { + const observation = this.observations.get(id); + if (observation) this.release(observation); + } + } + + private bindTarget(target: LocalRunObserverTarget, id: string): void { + let bound = this.targets.get(target.key); + if (!bound) { + const ids = new Set(); + bound = { ids, detach: () => {} }; + this.targets.set(target.key, bound); + bound.detach = target.onInvalidated(() => this.releaseTarget(target.key)); + } + bound.ids.add(id); + } + + private release(observation: Observation): void { + if (this.observations.get(observation.id) !== observation) return; + this.observations.delete(observation.id); + observation.releaseRun(); + observation.releaseRun = () => {}; + if (observation.timer !== undefined) this.options.clearTimer(observation.timer); + observation.timer = undefined; + const bound = this.targets.get(observation.target.key); + if (bound) { + bound.ids.delete(observation.id); + if (bound.ids.size === 0) { + this.targets.delete(observation.target.key); + bound.detach(); + } + } + if (this.observations.size === 0 && this.offChange) { + this.offChange(); + this.offChange = null; + } + } + + private subscribeRun(observation: Observation): void { + const runId = observation.runId; + if (runId === null) return; + observation.releaseRun = this.options.registry.subscribe(runId, () => this.schedule(observation)); + } + + private schedule(observation: Observation): void { + if (observation.timer !== undefined || this.observations.get(observation.id) !== observation) return; + observation.timer = this.options.setTimer(() => { + observation.timer = undefined; + this.flush(observation); + }, this.batchMs); + } + + private setState(observation: Observation, state: PeerRunStreamState): void { + if (observation.state === state) return; + observation.state = state; + observation.queued.push({ kind: "state", runId: observation.runId, state }); + } + + /** Reads what the journal holds past the cursor, closing the run when it is complete. */ + private drain(observation: Observation): PeerRunEvent[] { + const runId = observation.runId; + if (runId === null || observation.ended) return []; + const events: PeerRunEvent[] = []; + while (events.length < this.maxEventsPerFlush) { + let read; + try { + read = this.options.registry.read(runId, observation.cursor, this.maxEventsPerFlush - events.length); + } catch { + // The run was evicted while observed; the persisted transcript has the rest. + this.endRun(observation, "gone"); + return events; + } + if (read.kind === "snapshot_required") { + const gap = hostRunGapSnapshotEvent(read, "full"); + events.push(gap); + observation.cursor = gap.sequence; + continue; + } + for (const event of read.events) { + events.push(hostRunWireEvent(event, read.summary.chatId, "full")); + observation.cursor = event.sequence; + } + if (isTerminal(read.summary.state) && observation.cursor === read.summary.lastSequence) { + events.push(hostRunEndedEvent(read.summary)); + this.endRun(observation, "ended"); + return events; + } + if (read.events.length === 0 || observation.cursor === read.summary.lastSequence) return events; + } + // More remains than one flush carries; continue on the next frame. + this.schedule(observation); + return events; + } + + private endRun(observation: Observation, state: "ended" | "gone"): void { + observation.ended = true; + observation.releaseRun(); + observation.releaseRun = () => {}; + this.setState(observation, state); + } + + private flush(observation: Observation): void { + if (this.observations.get(observation.id) !== observation) return; + if (observation.target.isDestroyed()) { + this.releaseTarget(observation.target.key); + return; + } + const frames: LocalRunFrame[] = []; + for (const event of this.drain(observation)) frames.push({ kind: "event", event }); + // State changes (ended, gone, a newly adopted run) follow the events that caused them. + frames.push(...observation.queued.splice(0)); + if (observation.ended || observation.runId === null) this.adoptCurrentRun(observation, frames); + if (frames.length === 0) return; + try { + observation.target.send({ subscriptionId: observation.id, chatId: observation.chatId, frames }); + } catch { + // The document went away between the check and the send. + this.releaseTarget(observation.target.key); + } + } + + /** A parked observation picks up the chat's next run. */ + private adoptCurrentRun(observation: Observation, frames: LocalRunFrame[]): void { + const current = this.options.registry.currentRunForChat(observation.chatId); + if (!current || current.runId === observation.runId || isTerminal(current.state)) return; + observation.runId = current.runId; + observation.cursor = 0; + observation.ended = false; + observation.state = "streaming"; + frames.push({ kind: "state", runId: current.runId, state: "streaming" }); + for (const event of this.drain(observation)) frames.push({ kind: "event", event }); + frames.push(...observation.queued.splice(0)); + if (!observation.ended) this.subscribeRun(observation); + } + + private runChanged(summary: HostRunSummary, removed: boolean): void { + for (const observation of this.observations.values()) { + if (observation.chatId !== summary.chatId) continue; + if (removed) { + if (summary.runId === observation.runId && !observation.ended) { + this.endRun(observation, "gone"); + this.schedule(observation); + } + continue; + } + // A new run in a parked chat: deliver it on the next frame. + if (summary.runId !== observation.runId && (observation.runId === null || observation.ended)) { + this.schedule(observation); + } + } + } +} diff --git a/main/services/peer-remote-chat-control.test.ts b/main/services/peer-remote-chat-control.test.ts index b50aa3c06c..483abee061 100644 --- a/main/services/peer-remote-chat-control.test.ts +++ b/main/services/peer-remote-chat-control.test.ts @@ -412,6 +412,10 @@ test("the same session control drives a chat on this Mac and one on another Mac }, stop: async (runId) => local.cancel(runId), admitRunInput: (streamId, input) => local.admitInput({ streamId, chatId: "chat-1", mode: input.mode, text: input.text }), + observeRun: unused, + unobserveRun: unused, + onRunFrame: () => () => {}, + stopHostRun: unused, }); localRuns.begin({ runId: "run-1", chatId: "chat-1", origin: "renderer" }); localRuns.publish("run-1", "chat:approval", APPROVAL); diff --git a/package.json b/package.json index 65a40d6c32..c33139862e 100644 --- a/package.json +++ b/package.json @@ -60,10 +60,10 @@ "test:preflight": "npm run test:mcp && npm run test:artificial-analysis && npm run test:model-pad && tsx --test main/services/appearance-preview-core.test.ts main/services/generation-timeline.test.ts main/services/local-runtime-status.test.ts main/services/mcp-tool-result.test.ts main/services/pi-thinking-disclosure.integration.test.ts renderer/components/activity-feed.test.tsx renderer/components/context-meter.test.tsx renderer/components/chat-sidebar.test.tsx renderer/components/composer.test.tsx renderer/components/settings/providers-settings.test.tsx renderer/main/chat-transition.test.tsx renderer/components/reasoning-block.test.tsx renderer/components/reasoning-visibility-control.test.tsx renderer/components/thinking-control.test.tsx renderer/lib/agent-steps.test.ts renderer/lib/button-appearance-contract.test.ts renderer/lib/dialog-motion-contract.test.ts renderer/lib/inline-metadata-hierarchy.test.ts renderer/lib/scrollbar-gutter-contract.test.ts renderer/lib/scroll-follow.test.ts renderer/lib/text-entry-focus-contract.test.ts renderer/lib/pill-appearance.test.ts renderer/lib/reasoning-disclosure.test.ts renderer/lib/streaming-motion-contract.test.ts renderer/lib/streaming-reveal.test.ts renderer/lib/voice-recorder-core.test.ts renderer/lib/media-recorder-stop.test.ts renderer/lib/dictation-vad.test.ts renderer/lib/dictation-sounds.test.ts renderer/pill-preload-channels.test.ts renderer/shared/anthropic-thinking.test.ts renderer/shared/app-update.test.ts renderer/shared/claim-check.test.ts renderer/shared/codex-thinking.test.ts renderer/shared/context-pressure.test.ts renderer/shared/google-thinking.test.ts renderer/shared/provider-deployment.test.ts renderer/shared/assistant-turn-stats.test.ts renderer/lib/sticky-section.test.ts", "test:chat-row-states": "tsx --test renderer/shared/chat-row-state.test.ts renderer/components/chat-row-status.test.tsx renderer/components/chat-row-context.test.tsx renderer/lib/chat-row-context.test.ts renderer/lib/use-mark-chat-read.test.ts main/services/chat-read-markers.test.ts", "test:sidebar": "tsx --test renderer/components/chat-sidebar.test.tsx renderer/lib/sidebar-workspace-groups.test.ts renderer/lib/sidebar-chat-shortcuts.test.ts renderer/lib/held-modifier-reveal.test.ts renderer/lib/sidebar-organization.test.ts renderer/components/sidebar-organize-menu.test.tsx renderer/components/sidebar-remote.test.tsx renderer/lib/sidebar-remote-groups.test.ts renderer/lib/hosts/peer-host-feed-state.test.ts renderer/lib/hosts/use-peer-host-sidebar.test.tsx", - "test:remote-chat": "tsx --test renderer/lib/hosts/remote-chat-mapper.test.ts renderer/lib/hosts/remote-stream-translator.test.ts main/services/peer-remote-chat-view.test.ts renderer/main/remote-chat-view.test.tsx renderer/lib/hosts/chat-session-control.test.ts renderer/lib/hosts/local-host-adapter.test.ts main/services/peer-remote-chat-control.test.ts renderer/lib/hosts/remote-new-chat.test.ts renderer/lib/hosts/host-resources.test.ts renderer/lib/hosts/new-chat-targets.test.ts renderer/main/remote-new-chat-view.test.tsx main/services/peer-remote-new-chat.test.ts main/services/peer-remote-chat-fork.test.ts", + "test:remote-chat": "tsx --test renderer/lib/hosts/remote-chat-mapper.test.ts renderer/lib/hosts/remote-stream-translator.test.ts main/services/peer-remote-chat-view.test.ts renderer/main/remote-chat-view.test.tsx renderer/lib/hosts/chat-session-control.test.ts renderer/lib/hosts/local-host-adapter.test.ts renderer/lib/hosts/observed-local-run.test.ts main/services/peer-remote-chat-control.test.ts renderer/lib/hosts/remote-new-chat.test.ts renderer/lib/hosts/host-resources.test.ts renderer/lib/hosts/new-chat-targets.test.ts renderer/main/remote-new-chat-view.test.tsx main/services/peer-remote-new-chat.test.ts main/services/peer-remote-chat-fork.test.ts", "test:peer-hosts": "tsx --test main/services/peer-host-registry.test.ts main/services/peer-transport.test.ts main/services/peer-operation.test.ts main/services/peer-host-feed-cache.test.ts main/services/peer-run-subscriptions.test.ts main/services/peer-host-manager.test.ts main/handlers/peer-host-live.test.ts main/services/peer-bootstrap-transport.test.ts main/services/peer-host-pairing.test.ts main/services/peer-pairing-client.test.ts main/services/peer-discovery.test.ts main/handlers/peer-pairing.test.ts main/services/peer-lan-addresses.test.ts main/services/peer-multi-host-acceptance.test.ts", "pretest:aiden-remote": "npm run build:worktree-file-io", - "test:aiden-remote": "npm run test:peer-hosts && tsx --test main/services/aiden-remote-chat-progress.test.ts main/services/aiden-remote-chat-progress-authorize.test.ts main/handlers/aiden-remote.test.ts main/services/aiden-remote-chat-summaries.test.ts main/services/aiden-remote-approved-roots.test.ts main/services/aiden-remote-revocation.test.ts main/services/aiden-remote-bot-files.test.ts main/services/aiden-remote-bots.test.ts main/services/aiden-remote-bot-session.test.ts main/services/aiden-remote-chat-http.test.ts main/services/aiden-remote-chats.test.ts main/services/aiden-remote-files.test.ts main/services/aiden-remote-git.test.ts main/services/aiden-remote-models.test.ts main/services/aiden-remote-protocol.test.ts main/services/aiden-remote-opaque-handles.test.ts main/services/aiden-remote-operation-contract.test.ts main/services/aiden-remote-pairing.test.ts main/services/aiden-remote-pairing-requests.test.ts main/services/aiden-remote-pairing-requests-router.test.ts main/services/aiden-remote-pairing-request-host.test.ts main/services/aiden-remote-sealed-envelope.test.ts main/services/aiden-remote-ports.test.ts main/services/aiden-remote-router.test.ts main/services/aiden-remote-schedules.test.ts main/services/aiden-remote-service.test.ts main/services/aiden-remote-state.test.ts main/services/aiden-remote-streams.test.ts main/services/aiden-remote-tailscale-route.test.ts main/services/aiden-remote-tailscale.test.ts main/services/aiden-remote-tls-identity.test.ts main/services/aiden-remote-workspace-browser.test.ts main/services/aiden-remote-workspace-http.test.ts main/services/aiden-remote-workspaces.test.ts renderer/components/remote-connection-popover.test.tsx renderer/components/remote-pairing-request-sheet.test.tsx renderer/components/settings/remote-access-settings.test.tsx renderer/lib/remote-approval.test.ts renderer/lib/remote-connection-status.test.ts renderer/lib/remote-pairing-lifecycle.test.ts renderer/lib/settings-section.test.ts main/services/run-event-projection.test.ts main/services/host-run-registry.test.ts main/services/host-runs.test.ts main/services/aiden-remote-host-feed.test.ts main/services/aiden-remote-host-runs.test.ts main/services/repository-identity.test.ts && node --test scripts/aiden-remote-lan-transport-spike.test.mjs && tsx --test renderer/lib/peer-connections.test.ts renderer/components/settings/connections-settings.test.tsx", + "test:aiden-remote": "npm run test:peer-hosts && tsx --test main/services/aiden-remote-chat-progress.test.ts main/services/aiden-remote-chat-progress-authorize.test.ts main/handlers/aiden-remote.test.ts main/services/aiden-remote-chat-summaries.test.ts main/services/aiden-remote-approved-roots.test.ts main/services/aiden-remote-revocation.test.ts main/services/aiden-remote-bot-files.test.ts main/services/aiden-remote-bots.test.ts main/services/aiden-remote-bot-session.test.ts main/services/aiden-remote-chat-http.test.ts main/services/aiden-remote-chats.test.ts main/services/aiden-remote-files.test.ts main/services/aiden-remote-git.test.ts main/services/aiden-remote-models.test.ts main/services/aiden-remote-protocol.test.ts main/services/aiden-remote-opaque-handles.test.ts main/services/aiden-remote-operation-contract.test.ts main/services/aiden-remote-pairing.test.ts main/services/aiden-remote-pairing-requests.test.ts main/services/aiden-remote-pairing-requests-router.test.ts main/services/aiden-remote-pairing-request-host.test.ts main/services/aiden-remote-sealed-envelope.test.ts main/services/aiden-remote-ports.test.ts main/services/aiden-remote-router.test.ts main/services/aiden-remote-schedules.test.ts main/services/aiden-remote-service.test.ts main/services/aiden-remote-state.test.ts main/services/aiden-remote-streams.test.ts main/services/aiden-remote-tailscale-route.test.ts main/services/aiden-remote-tailscale.test.ts main/services/aiden-remote-tls-identity.test.ts main/services/aiden-remote-workspace-browser.test.ts main/services/aiden-remote-workspace-http.test.ts main/services/aiden-remote-workspaces.test.ts renderer/components/remote-connection-popover.test.tsx renderer/components/remote-pairing-request-sheet.test.tsx renderer/components/settings/remote-access-settings.test.tsx renderer/lib/remote-approval.test.ts renderer/lib/remote-connection-status.test.ts renderer/lib/remote-pairing-lifecycle.test.ts renderer/lib/settings-section.test.ts main/services/run-event-projection.test.ts main/services/host-run-registry.test.ts main/services/host-runs.test.ts main/services/aiden-remote-host-feed.test.ts main/services/aiden-remote-host-runs.test.ts main/handlers/local-runs.test.ts main/services/repository-identity.test.ts && node --test scripts/aiden-remote-lan-transport-spike.test.mjs && tsx --test renderer/lib/peer-connections.test.ts renderer/components/settings/connections-settings.test.tsx", "test:aiden-remote-chat-summaries": "tsx --test main/services/aiden-remote-chat-summaries.test.ts", "test:memory-policy": "tsx --test main/services/memory-policy.test.ts main/services/aiden-remote-memory-settings.test.ts renderer/components/settings/memory-settings.test.tsx", "test:aiden-service-boundary": "tsx --test main/services/empty-chat-migration.test.ts main/services/chat-first-message-commit.test.ts main/services/chat-application-service.test.ts main/services/chat-generation-owner.test.ts main/services/workspace-application-service.test.ts main/services/workspace-environment-application-service.test.ts main/services/workspace-worktree-application-service.test.ts main/services/scheduled-task-application-service.test.ts main/services/bot-application-service.test.ts", diff --git a/renderer/components/environment-subagents-contract.test.ts b/renderer/components/environment-subagents-contract.test.ts index 58c753348a..2d243b3ca2 100644 --- a/renderer/components/environment-subagents-contract.test.ts +++ b/renderer/components/environment-subagents-contract.test.ts @@ -590,10 +590,6 @@ test("the shell reconciles lifecycle-detached terminal chats without per-stream assert.match(pane, /React\.useSyncExternalStore\(\s+subscribeDetachedLifecycleStreams/u); assert.match(pane, /detachedLifecycleChatProjection\(chatId, effectiveWorkspaceId\)/u); assert.match(pane, /detachedGenerationDraining && !visibleDetachedProjection\s+\? "Response continues in the background…"/u); - assert.match( - pane, - /cachedMessages\?\.\[cachedMessages\.length - 1\]\?\.role === "assistant" \? null : detachedProjection/u, - ); assert.match(pane, /liveSubagents=\{displayedLiveSubagents\}/u); assert.match(pane, /streamingText=\{displayedStreamingText\}/u); assert.match( diff --git a/renderer/lib/chat-terminal-sync.test.ts b/renderer/lib/chat-terminal-sync.test.ts index 3df169d4bc..3c2e60472d 100644 --- a/renderer/lib/chat-terminal-sync.test.ts +++ b/renderer/lib/chat-terminal-sync.test.ts @@ -3,6 +3,7 @@ import test from "node:test"; import { captureDetachedLifecycleChat, clearInactiveDetachedLifecycleChat, + clearObservedRunProjection, detachedLifecycleChatProjection, detachedTextStreamingRemaining, fallbackDetachedLifecycleStream, @@ -13,13 +14,18 @@ import { preferLatestTerminalChat, reconcileChatReadUntilAuthoritative, rememberChatReadReconciliation, + publishObservedRunProjection, + releaseSettledDetachedLifecycleStreams, rememberDetachedLifecycleStream, subscribeChatReadReconciliations, + subscribeDetachedLifecycleStreams, subscribeChatSettlements, subscribeDetachedTerminalChats, + visibleDetachedLifecycleProjection, waitForDetachedLifecycleSettlement, } from "./chat-terminal-sync.js"; -import type { Chat } from "./types.js"; +import type { DetachedLifecycleProjection } from "./chat-terminal-sync.js"; +import type { Chat, ChatMessage } from "./types.js"; import type { SubagentRunSnapshotV1 } from "../shared/subagent-runs.js"; function chat(id: string, content: string): Chat { @@ -641,3 +647,180 @@ test("authoritative reconciliation stops without refetching after a deletion tom assert.equal(result, "deleted"); assert.equal(exactReads, 0); }); + +test("a settled detached stream stops draining while the phone's newer turn keeps the chat busy", async () => { + const finished = detached("mac-finished", "chat-phone-follow-up", "workspace-1"); + const stillRunning = detached("mac-still-running", "chat-phone-follow-up", "workspace-1"); + rememberDetachedLifecycleStream(finished); + rememberDetachedLifecycleStream(stillRunning); + // The finished stream's terminal never reached this document. + assert.equal(fallbackDetachedLifecycleStream(finished.streamId), true); + const captured = captureDetachedLifecycleChat(finished); + assert.ok(captured); + + // The phone's turn keeps the chat active, so the chat-level path cannot help: + // this is the stuck "Response continues in the background…" marker. + assert.equal(clearInactiveDetachedLifecycleChat(captured, new Set([finished.chatId])), false); + assert.equal(isDetachedLifecycleChatDraining(finished.chatId, finished.workspaceId), true); + + const order: string[] = []; + const released = await releaseSettledDetachedLifecycleStreams( + { chatId: finished.chatId, workspaceId: finished.workspaceId }, + { + settled: async (streamIds) => { + order.push(`settled:${[...streamIds].sort().join(",")}`); + return streamIds.filter((streamId) => streamId === finished.streamId); + }, + refreshChat: async (chatId) => { + // The transcript is re-read before the marker goes, so nothing flashes away. + order.push(`refresh:${chatId}:draining=${isDetachedLifecycleChatDraining(chatId, "workspace-1")}`); + }, + }, + ); + assert.equal(released, true); + assert.deepEqual(order, [ + "settled:mac-finished,mac-still-running", + "refresh:chat-phone-follow-up:draining=true", + ]); + // Only the confirmed stream is released; the unsettled one still drains. + assert.deepEqual(captureDetachedLifecycleChat(finished)?.streamIds, [stillRunning.streamId]); + + assert.equal( + await releaseSettledDetachedLifecycleStreams(finished, { + settled: async () => [], + refreshChat: async () => assert.fail("nothing settled, so nothing is re-read"), + }), + false, + ); + assert.equal(isDetachedLifecycleChatDraining(finished.chatId, finished.workspaceId), true); + assert.equal(clearInactiveDetachedLifecycleChat(captureDetachedLifecycleChat(stillRunning)!, new Set()), true); + assert.equal( + await releaseSettledDetachedLifecycleStreams(finished, { + settled: async () => assert.fail("a chat with no marker asks main nothing"), + refreshChat: async () => assert.fail("a chat with no marker is not re-read"), + }), + false, + ); +}); + +test("a settled stream's release survives a competing read cancelling its refresh", async () => { + const finished = detached("mac-cancelled-read", "chat-cancelled-read", "workspace-1"); + rememberDetachedLifecycleStream(finished); + assert.equal(fallbackDetachedLifecycleStream(finished.streamId), true); + + let reads = 0; + const released = await releaseSettledDetachedLifecycleStreams(finished, { + settled: async (streamIds) => streamIds, + refreshChat: async () => { + reads += 1; + // The observer's own read of the chat cancels the first one. + if (reads === 1) throw new Error("CancelledError"); + }, + }); + assert.equal(released, true); + assert.equal(reads, 2); + assert.equal(isDetachedLifecycleChatDraining(finished.chatId, finished.workspaceId), false); + + // A chat whose reads keep failing is not released on faith. + const unreadable = detached("mac-unreadable", "chat-unreadable", "workspace-1"); + rememberDetachedLifecycleStream(unreadable); + assert.equal(fallbackDetachedLifecycleStream(unreadable.streamId), true); + await assert.rejects( + releaseSettledDetachedLifecycleStreams(unreadable, { + settled: async (streamIds) => streamIds, + refreshChat: async () => { + throw new Error("offline"); + }, + }), + ); + assert.equal(isDetachedLifecycleChatDraining(unreadable.chatId, unreadable.workspaceId), true); + assert.equal(clearInactiveDetachedLifecycleChat(captureDetachedLifecycleChat(unreadable)!, new Set()), true); +}); + +test("an observed run shows as the chat's live projection until it is cleared", () => { + const owner = detached("phone-run", "chat-observed", "workspace-1"); + let notifications = 0; + const unsubscribe = subscribeDetachedLifecycleStreams(() => notifications++); + try { + assert.equal( + publishObservedRunProjection(owner, { text: "Hel", reasoning: "Thinking", timeline: null, textStreaming: true }, 1_000), + true, + ); + assert.equal(isDetachedLifecycleChatDraining(owner.chatId, owner.workspaceId), true); + const projection = detachedLifecycleChatProjection(owner.chatId, owner.workspaceId); + assert.equal(projection?.content, "Hel"); + assert.equal(projection?.reasoning, "Thinking"); + assert.equal(projection?.lastTextDeltaAt, 1_000); + assert.equal(projection?.observed, true); + + // Reasoning after text keeps the last prose time; an identical snapshot is not re-published. + publishObservedRunProjection(owner, { text: "Hel", reasoning: "Thinking more", timeline: null, textStreaming: false }, 2_000); + assert.equal(detachedLifecycleChatProjection(owner.chatId, owner.workspaceId)?.lastTextDeltaAt, 1_000); + const before = notifications; + assert.equal( + publishObservedRunProjection(owner, { text: "Hel", reasoning: "Thinking more", timeline: null, textStreaming: false }, 3_000), + false, + ); + assert.equal(notifications, before); + + // Another workspace's chat with the same id is a different chat. + assert.equal(detachedLifecycleChatProjection(owner.chatId, "workspace-2"), null); + // Clearing a different run leaves this one; clearing this one ends the drain. + assert.equal(clearObservedRunProjection(owner.chatId, owner.workspaceId, "another-run"), false); + assert.equal(clearObservedRunProjection(owner.chatId, owner.workspaceId, owner.streamId), true); + assert.equal(detachedLifecycleChatProjection(owner.chatId, owner.workspaceId), null); + assert.equal(isDetachedLifecycleChatDraining(owner.chatId, owner.workspaceId), false); + } finally { + unsubscribe(); + } +}); + +test("a run this document started is never mirrored over its own detached projection", () => { + const own = detached("own-detached-run", "chat-own-run", "workspace-1"); + rememberDetachedLifecycleStream(own, { content: "Mine", reasoning: "", timeline: null, artifacts: [], subagents: [] }); + assert.equal( + publishObservedRunProjection(own, { text: "Mine plus mirror", reasoning: "", timeline: null, textStreaming: true }), + false, + ); + const projection = detachedLifecycleChatProjection(own.chatId, own.workspaceId); + assert.equal(projection?.content, "Mine"); + assert.equal(projection?.observed, undefined); + assert.equal(clearInactiveDetachedLifecycleChat(captureDetachedLifecycleChat(own)!, new Set()), true); +}); + +test("a saved reply hides an own run, but a mirrored run only by its own reply", () => { + const projection = (streamId: string, observed: boolean): DetachedLifecycleProjection => ({ + ...detached(streamId), + content: "Streaming", + lastTextDeltaAt: null, + reasoning: "", + timeline: null, + artifacts: [], + subagents: [], + ...(observed ? { observed: true as const } : {}), + }); + const reply = (generationId?: string): ChatMessage => ({ + id: `reply-${generationId ?? "untimed"}`, + role: "assistant", + content: "Done", + createdAt: 2, + ...(generationId + ? { timeline: { version: 3, generationId, status: "completed", startedAt: 1, steps: [] } } + : {}), + }); + const prompt: ChatMessage = { id: "prompt", role: "user", content: "Next", createdAt: 3 }; + + const own = projection("run-new", false); + assert.equal(visibleDetachedLifecycleProjection(own, undefined), own); + assert.equal(visibleDetachedLifecycleProjection(own, [reply("run-old"), prompt]), own); + // An own run's text is already in the cached reply at handoff, whatever its timeline. + assert.equal(visibleDetachedLifecycleProjection(own, [reply()]), null); + + const mirrored = projection("run-new", true); + // A phone's turn starts while the cache still ends with the previous reply. + assert.equal(visibleDetachedLifecycleProjection(mirrored, [reply("run-old")]), mirrored); + assert.equal(visibleDetachedLifecycleProjection(mirrored, [reply()]), mirrored); + assert.equal(visibleDetachedLifecycleProjection(mirrored, [reply("run-old"), reply("run-new")]), null); + + assert.equal(visibleDetachedLifecycleProjection(null, [reply("run-new")]), null); +}); diff --git a/renderer/lib/chat-terminal-sync.ts b/renderer/lib/chat-terminal-sync.ts index 2c7ba55802..0c2c786738 100644 --- a/renderer/lib/chat-terminal-sync.ts +++ b/renderer/lib/chat-terminal-sync.ts @@ -1,4 +1,4 @@ -import type { Chat, ChatReadResponse } from "./types"; +import type { Chat, ChatMessage, ChatReadResponse } from "./types"; import { persistedChatWorkspaceId } from "../shared/chat-workspace"; import { isSafeSubagentIdentifier, @@ -23,6 +23,8 @@ const FALLBACK_RETRY_DELAY_MS = 100; const detachedLifecycleStreams = new Map(); const fallbackLifecycleStreams = new Map(); const detachedLifecycleProjections = new Map(); +/** Runs this window watches but did not start (a phone's turn), one per chat. */ +const observedRunProjections = new Map(); const fallbackSettlementInFlight = new Set(); const terminalSettlementInFlight = new Set(); const chatReadReconciliations = new Map(); @@ -50,6 +52,31 @@ export interface DetachedLifecycleProjection extends DetachedLifecycleStreamOwne /** Native (render_ui) visuals, kept beside the artifacts. */ uiVisuals?: readonly ChatUiVisualV1[]; subagents: readonly SubagentRunSnapshot[]; + /** + * Mirrored from this Mac's run journal for a run this window did not start. + * Stop uses host authority; Steer is not offered because run input is owner-checked. + */ + observed?: true; + /** + * The saved reply a mirrored run reported when it finished. A text-only + * reply carries no timeline, so this id is what marks it as the run's own. + */ + doneMessageId?: string; + /** A mirrored run has finished: its text is final and nothing more streams. */ + finished?: true; +} + +/** What a watching window knows about a run it mirrors. */ +export interface ObservedRunSnapshot { + text: string; + reasoning: string; + timeline: GenerationTimeline | null; + /** The newest content was a text delta. */ + textStreaming: boolean; + /** The assistant message the run saved, once it has finished. */ + doneMessageId?: string | null; + /** The run finished (done, failed or cancelled). */ + finished?: boolean; } export type DetachedLifecycleProjectionSeed = Omit< @@ -341,6 +368,9 @@ export function detachedLifecycleChatProjection( workspaceId: string | undefined, ): DetachedLifecycleProjection | null { const expectedWorkspaceId = persistedChatWorkspaceId(workspaceId); + // The observed run is the chat's current one on this Mac, so it is the newest. + const observed = observedRunProjections.get(chatReadReconciliationKey({ chatId, workspaceId: expectedWorkspaceId })); + if (observed) return observed; for (const projection of detachedLifecycleProjections.values()) { if (projection.chatId === chatId && projection.workspaceId === expectedWorkspaceId) { return projection; @@ -349,6 +379,42 @@ export function detachedLifecycleChatProjection( return null; } +/** + * A durable terminal message can reach the cache before detached ownership is + * cleared; during that handoff the projection is hidden so nothing is offered + * to stop or steer. A mirrored run (a phone's turn) can start while the cache + * still ends with the previous turn's reply, so only its own saved reply hides + * it: one stamped with its timeline, or (a text-only reply has none) the + * message the run reported saving. The observer clears it once a read holds + * that reply. + */ +export function visibleDetachedLifecycleProjection( + projection: DetachedLifecycleProjection | null, + cachedMessages: readonly ChatMessage[] | undefined, +): DetachedLifecycleProjection | null { + if (!projection) return null; + const last = cachedMessages?.[cachedMessages.length - 1]; + if (last?.role !== "assistant") return projection; + if ( + projection.observed === true && + last.timeline?.generationId !== projection.streamId && + (projection.doneMessageId === undefined || last.id !== projection.doneMessageId) + ) { + return projection; + } + return null; +} + +/** + * Whether the pane presents a shown projection's text as final. A route-detached + * run is shown complete, as it always has been; a mirrored run (a phone's turn) + * streams live, with the paced reveal, until the run finishes. + */ +export function detachedProjectionStreamComplete(projection: DetachedLifecycleProjection | null): boolean { + if (!projection) return false; + return projection.observed !== true || projection.finished === true; +} + export function isDetachedLifecycleChatDraining( chatId: string, workspaceId: string | undefined, @@ -360,10 +426,88 @@ export function isDetachedLifecycleChatDraining( ) || [...chatReadReconciliations.values()].some( (owner) => owner.chatId === chatId && owner.workspaceId === expectedWorkspaceId, - ) + ) || + observedRunProjections.has(chatReadReconciliationKey({ chatId, workspaceId: expectedWorkspaceId })) ); } +/** + * Shows a run this window is watching but did not start, live, through the + * same projection a route-detached run uses. A run this window owns keeps its + * own projection and is ignored here. Returns whether the projection changed. + */ +export function publishObservedRunProjection( + owner: DetachedLifecycleStreamOwner, + snapshot: ObservedRunSnapshot, + now: number = Date.now(), +): boolean { + if ( + !isSafeSubagentIdentifier(owner.streamId) || + !isSafeSubagentIdentifier(owner.chatId) || + !isSafeSubagentIdentifier(owner.workspaceId) + ) { + return false; + } + const normalized = { + streamId: owner.streamId, + chatId: owner.chatId, + workspaceId: persistedChatWorkspaceId(owner.workspaceId), + }; + const key = chatReadReconciliationKey(normalized); + if (detachedLifecycleStreams.has(normalized.streamId)) { + return clearObservedRunProjection(normalized.chatId, normalized.workspaceId, normalized.streamId); + } + const previous = observedRunProjections.get(key); + const sameRun = previous?.streamId === normalized.streamId; + const content = snapshot.text.slice(0, MAX_DETACHED_CONTENT_CHARS); + const reasoning = snapshot.reasoning.slice(0, MAX_DETACHED_REASONING_CHARS); + // The translator already validated the timeline; keep its identity so an unchanged one is not re-published. + const timeline = snapshot.timeline; + const textGrew = content.length > (sameRun ? previous.content.length : 0); + const next: DetachedLifecycleProjection = { + ...normalized, + content, + lastTextDeltaAt: + snapshot.textStreaming && textGrew ? now : sameRun ? previous.lastTextDeltaAt : null, + reasoning, + timeline: timeline?.generationId === normalized.streamId ? timeline : null, + artifacts: [], + uiVisuals: [], + subagents: [], + observed: true, + ...(snapshot.doneMessageId ? { doneMessageId: snapshot.doneMessageId } : {}), + ...(snapshot.finished ? { finished: true as const } : {}), + }; + if ( + sameRun && + previous.content === next.content && + previous.reasoning === next.reasoning && + previous.timeline === next.timeline && + previous.lastTextDeltaAt === next.lastTextDeltaAt && + previous.doneMessageId === next.doneMessageId && + previous.finished === next.finished + ) { + return false; + } + observedRunProjections.set(key, next); + emitRegistryChange(); + return true; +} + +/** Drops a chat's observed run, or only `streamId` when given. */ +export function clearObservedRunProjection( + chatId: string, + workspaceId: string | undefined, + streamId?: string, +): boolean { + const key = chatReadReconciliationKey({ chatId, workspaceId: persistedChatWorkspaceId(workspaceId) }); + const current = observedRunProjections.get(key); + if (!current || (streamId !== undefined && current.streamId !== streamId)) return false; + observedRunProjections.delete(key); + emitRegistryChange(); + return true; +} + function ownsLifecycleChat( owner: ChatSettlementNotification, chatId: string, @@ -415,9 +559,78 @@ export function clearInactiveDetachedLifecycleChat( ) { return false; } + return clearCapturedStreams(owner, owner.streamIds); +} + +/** + * Drops the captured streams that main reports finished for good, even while + * the chat is busy with a newer run (a phone's turn that followed a + * route-detached one). Call it only after the chat cache has been re-read, so + * the transcript already holds what those streams persisted. + */ +export function clearSettledDetachedLifecycleStreams( + owner: DetachedLifecycleChatReconciliation, + settledStreamIds: readonly string[], +): boolean { + if ( + !isSafeSubagentIdentifier(owner.chatId) || + !isSafeSubagentIdentifier(owner.workspaceId) || + !owner.streamIds.every(isSafeSubagentIdentifier) + ) { + return false; + } + const settled = new Set(settledStreamIds); + return clearCapturedStreams(owner, owner.streamIds.filter((streamId) => settled.has(streamId))); +} + +export interface SettledStreamRelease { + /** Which of these streams main reports finished for good. */ + settled(streamIds: readonly string[]): Promise; + /** Re-reads the chat (and its list row) so the cache holds what they persisted. */ + refreshChat(chatId: string): Promise; +} + +/** Bound on one settled query, matching main's. */ +const MAX_SETTLED_QUERY = 64; +/** Re-reads tried before a release gives way to the chat-level idle path. */ +const SETTLED_REFRESH_ATTEMPTS = 3; + +/** + * A per-stream settlement for a chat that is still busy (a phone's turn began + * right after a route-detached one) used to leave the detached marker in + * place until the whole chat went idle, so the pane said "Response continues + * in the background…" for a run that had already finished. This releases + * exactly the captured streams main confirms settled, after a fresh read. + */ +export async function releaseSettledDetachedLifecycleStreams( + owner: ChatSettlementNotification, + io: SettledStreamRelease, +): Promise { + const captured = captureDetachedLifecycleChat(owner); + if (!captured || captured.streamIds.length === 0) return false; + const settled = await io.settled(captured.streamIds.slice(-MAX_SETTLED_QUERY)); + if (settled.length === 0) return false; + // A competing read of the same chat (the observer's) cancels this one, so a + // rejected read is tried again rather than leaving the marker until idle. + for (let attempt = 1; ; attempt += 1) { + try { + await io.refreshChat(captured.chatId); + break; + } catch (error) { + if (attempt >= SETTLED_REFRESH_ATTEMPTS) throw error; + await new Promise((resolve) => globalThis.setTimeout(resolve, FALLBACK_RETRY_DELAY_MS)); + } + } + return clearSettledDetachedLifecycleStreams(captured, settled); +} + +function clearCapturedStreams( + owner: DetachedLifecycleChatReconciliation, + streamIds: readonly string[], +): boolean { const workspaceId = persistedChatWorkspaceId(owner.workspaceId); let changed = false; - for (const streamId of owner.streamIds) { + for (const streamId of streamIds) { const detachedOwner = detachedLifecycleStreams.get(streamId); if (detachedOwner && ownsLifecycleChat(detachedOwner, owner.chatId, workspaceId)) { detachedLifecycleStreams.delete(streamId); diff --git a/renderer/lib/hosts/local-host-adapter.test.ts b/renderer/lib/hosts/local-host-adapter.test.ts index 812db6ded8..1c58c7a104 100644 --- a/renderer/lib/hosts/local-host-adapter.test.ts +++ b/renderer/lib/hosts/local-host-adapter.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { LOCAL_HOST_ID } from "../../shared/peer-host"; +import { LOCAL_HOST_ID, type PeerRunEvent, type PeerRunSubscription } from "../../shared/peer-host"; +import type { LocalRunFrameMessage } from "../../shared/local-run-frames"; import { ChatSessionControl } from "./chat-session-control"; import { ChatIntentLedger } from "./chat-intent-ledger"; import { LocalHostAdapter, type LocalChatApis } from "./local-host-adapter"; @@ -35,6 +36,19 @@ function recordingApis(overrides: Partial = {}) { calls.push(["admitRunInput", ...args]); return { admitted: true, queue: "steer" as const, committed: true, messageId: "m9" }; }, + observeRun: async (...args) => { + calls.push(["observeRun", ...args]); + return { subscriptionId: "sub-1", key: "sub-1", runId: null, chatId: args[0], state: "idle", events: [], truncated: false }; + }, + unobserveRun: async (...args) => { + calls.push(["unobserveRun", ...args]); + return true; + }, + onRunFrame: () => () => {}, + stopHostRun: async (...args) => { + calls.push(["stopHostRun", ...args]); + return true; + }, ...overrides, }; return { apis, calls }; @@ -44,7 +58,7 @@ test("this Mac is always online and offers its local panels", () => { const adapter = new LocalHostAdapter(recordingApis().apis); assert.equal(adapter.hostId, LOCAL_HOST_ID); assert.equal(adapter.status().availability, "online"); - for (const capability of ["send", "cancel", "respondApproval", "answerQuestion", "steer", "rename", "remove", "localPanels"] as const) { + for (const capability of ["send", "cancel", "respondApproval", "answerQuestion", "steer", "rename", "remove", "localPanels", "observe"] as const) { assert.ok(adapter.capabilities().has(capability), capability); } }); @@ -139,3 +153,139 @@ test("local turns never go through the host send path", async () => { }); assert.deepEqual(calls, []); }); + +function runEvent(runId: string, sequence: number, type: string, payload: Record = {}): PeerRunEvent { + return { protocolVersion: 1, streamId: runId, sequence, timestamp: new Date(sequence).toISOString(), type, terminal: false, payload }; +} + +/** A frame transport whose `observeRun` resolves only when the test says so. */ +function frameTransport() { + const handlers = new Set<(message: LocalRunFrameMessage) => void>(); + let resolve: (subscription: PeerRunSubscription) => void = () => {}; + const observed = new Promise((settle) => { + resolve = settle; + }); + return { + emit: (message: LocalRunFrameMessage) => { + for (const handler of handlers) handler(message); + }, + listeners: () => handlers.size, + resolve: (subscription: PeerRunSubscription) => resolve(subscription), + overrides: { + observeRun: () => observed, + onRunFrame: (handler: (message: LocalRunFrameMessage) => void) => { + handlers.add(handler); + return () => handlers.delete(handler); + }, + } satisfies Partial, + }; +} + +function recordingObserver() { + const seen: string[] = []; + return { + seen, + observer: { + onSubscription: (subscription: PeerRunSubscription) => + seen.push(`subscription:${subscription.runId}:${subscription.events.map((event) => event.sequence).join(",")}`), + onEvent: (event: PeerRunEvent) => seen.push(`${event.type}@${event.sequence}`), + onState: (state: string) => seen.push(`state:${state}`), + onError: (error: { message: string }) => seen.push(`error:${error.message}`), + }, + }; +} + +test("frames that beat the subscription are replayed after its buffered events, for this subscription only", async () => { + const transport = frameTransport(); + const { apis } = recordingApis(transport.overrides); + const { seen, observer } = recordingObserver(); + const close = new LocalHostAdapter(apis).observe("c1", observer); + + transport.emit({ subscriptionId: "sub-1", chatId: "c1", frames: [{ kind: "event", event: runEvent("run-1", 3, "text_delta", { text: "lo" }) }] }); + transport.emit({ subscriptionId: "sub-other", chatId: "c1", frames: [{ kind: "event", event: runEvent("run-9", 1, "text_delta") }] }); + transport.emit({ subscriptionId: "sub-1", chatId: "c2", frames: [{ kind: "event", event: runEvent("run-2", 1, "text_delta") }] }); + assert.deepEqual(seen, [], "nothing is delivered before the subscription"); + + transport.resolve({ + subscriptionId: "sub-1", + key: "sub-1", + runId: "run-1", + chatId: "c1", + state: "streaming", + events: [runEvent("run-1", 1, "run.started"), runEvent("run-1", 2, "text_delta", { text: "Hel" })], + truncated: false, + }); + await new Promise((settle) => setImmediate(settle)); + transport.emit({ + subscriptionId: "sub-1", + chatId: "c1", + frames: [ + { kind: "event", event: runEvent("run-1", 4, "done") }, + { kind: "state", runId: "run-1", state: "ended" }, + ], + }); + + assert.deepEqual(seen, ["subscription:run-1:1,2", "text_delta@3", "done@4", "state:ended"]); + close(); + transport.emit({ subscriptionId: "sub-1", chatId: "c1", frames: [{ kind: "event", event: runEvent("run-1", 5, "text_delta") }] }); + assert.equal(seen.length, 4, "a closed observation hears nothing more"); + assert.equal(transport.listeners(), 0); +}); + +test("an observation closed before main answered is released as soon as it does", async () => { + const transport = frameTransport(); + const { apis, calls } = recordingApis(transport.overrides); + const { seen, observer } = recordingObserver(); + const close = new LocalHostAdapter(apis).observe("c1", observer); + close(); + transport.resolve({ subscriptionId: "sub-7", key: "sub-7", runId: "run-1", chatId: "c1", state: "streaming", events: [], truncated: false }); + await new Promise((settle) => setImmediate(settle)); + assert.deepEqual(calls, [["unobserveRun", "sub-7"]]); + assert.deepEqual(seen, []); +}); + +test("a refused observation reports an error instead of hanging", async () => { + const { apis } = recordingApis({ + observeRun: async () => { + throw new Error("The application document changed."); + }, + }); + const { seen, observer } = recordingObserver(); + new LocalHostAdapter(apis).observe("c1", observer); + await new Promise((settle) => setImmediate(settle)); + assert.deepEqual(seen, ["error:The application document changed."]); +}); + +test("Stop uses host authority only for a run this window is watching but does not own", async () => { + const { apis, calls } = recordingApis({ + observeRun: async (chatId) => ({ + subscriptionId: "sub-1", + key: "sub-1", + runId: "run-phone", + chatId, + state: "streaming", + events: [], + truncated: false, + }), + }); + const adapter = new LocalHostAdapter(apis); + assert.equal(await adapter.cancel("c1", { runId: "run-phone" }), false, "an unwatched run is not escalated"); + + const close = adapter.observe("c1", recordingObserver().observer); + await new Promise((settle) => setImmediate(settle)); + assert.equal(await adapter.cancel("c1", { runId: "run-phone" }), true); + assert.equal(await adapter.cancel("c1", { runId: "run-elsewhere" }), false); + close(); + assert.equal(await adapter.cancel("c1", { runId: "run-phone" }), false, "closing the observation drops the authority"); + + assert.deepEqual( + calls.filter(([route]) => route === "stop" || route === "stopHostRun"), + [ + ["stop", "run-phone"], + ["stop", "run-phone"], + ["stopHostRun", "run-phone"], + ["stop", "run-elsewhere"], + ["stop", "run-phone"], + ], + ); +}); diff --git a/renderer/lib/hosts/local-host-adapter.ts b/renderer/lib/hosts/local-host-adapter.ts index 955d422c91..4e9f98e2cf 100644 --- a/renderer/lib/hosts/local-host-adapter.ts +++ b/renderer/lib/hosts/local-host-adapter.ts @@ -2,9 +2,11 @@ import { admitChatRunInput, aidenRemoteApi, chatsApi, + localRunsApi, stopDetachedGeneration, } from "../ipc"; -import { LOCAL_HOST_ID } from "../../shared/peer-host"; +import type { LocalRunFrame, LocalRunFrameMessage } from "../../shared/local-run-frames"; +import { LOCAL_HOST_ID, type PeerRunSubscription } from "../../shared/peer-host"; import type { ChatRunInputAdmissionResult } from "../../shared/chat-run-input"; import { HostChatControlError, @@ -14,6 +16,7 @@ import { type HostChatCancelInput, type HostChatCapability, type HostChatInput, + type HostChatObserver, type HostChatQuestionInput, type HostChatQuestionResult, type HostChatRenameInput, @@ -35,6 +38,12 @@ export interface LocalChatApis { respondRemoteQuestion: typeof aidenRemoteApi.respondQuestion; stop: (streamId: string) => Promise; admitRunInput: typeof admitChatRunInput; + /** Mirror of a run this Mac hosts for the chat (a phone's turn, another window's). */ + observeRun: (chatId: string) => Promise; + unobserveRun: (subscriptionId: string) => Promise; + onRunFrame: (handler: (message: LocalRunFrameMessage) => void) => () => void; + /** Host-authority Stop for an observed run this window does not own. */ + stopHostRun: (runId: string) => Promise; } const defaultApis: LocalChatApis = { @@ -49,6 +58,10 @@ const defaultApis: LocalChatApis = { aidenRemoteApi.respondQuestion(chatId, promptId, response), stop: (streamId) => stopDetachedGeneration(streamId), admitRunInput: (streamId, input) => admitChatRunInput(streamId, input), + observeRun: (chatId) => localRunsApi.observe(chatId), + unobserveRun: (subscriptionId) => localRunsApi.unobserve(subscriptionId), + onRunFrame: (handler) => localRunsApi.onFrame(handler), + stopHostRun: (runId) => localRunsApi.stop(runId), }; const LOCAL_CAPABILITIES: ReadonlySet = new Set([ @@ -61,6 +74,7 @@ const LOCAL_CAPABILITIES: ReadonlySet = new Set>(); constructor(apis: LocalChatApis = defaultApis) { this.apis = apis; @@ -111,8 +127,71 @@ export class LocalHostAdapter implements HostChatAdapter { return Promise.resolve({ ok: false, error: NOT_A_HOST_READ }); } - observe(): () => void { - return () => {}; + /** + * Follows the chat's current run on this Mac while this window is not the + * one running it. Frames that land before the subscription resolves are + * held, then replayed after its buffered events, so nothing is lost or + * reordered. + */ + observe(chatId: string, observer: HostChatObserver): () => void { + let closed = false; + let subscriptionId: string | null = null; + let pending: LocalRunFrameMessage[] | null = []; + const runs = new Set(); + this.observedRuns.add(runs); + const deliver = (frame: LocalRunFrame) => { + if (closed) return; + if (frame.kind === "event") { + runs.add(frame.event.streamId); + observer.onEvent(frame.event); + } else { + if (frame.runId) runs.add(frame.runId); + observer.onState(frame.state); + } + }; + const offFrames = this.apis.onRunFrame((message) => { + if (closed || message.chatId !== chatId) return; + if (pending) pending.push(message); + else if (message.subscriptionId === subscriptionId) for (const frame of message.frames) deliver(frame); + }); + this.apis.observeRun(chatId).then( + (subscription) => { + if (closed) { + void this.apis.unobserveRun(subscription.subscriptionId).catch(() => {}); + return; + } + subscriptionId = subscription.subscriptionId; + if (subscription.runId) runs.add(subscription.runId); + observer.onSubscription(subscription); + const held = pending ?? []; + pending = null; + for (const message of held) { + if (message.subscriptionId !== subscriptionId) continue; + for (const frame of message.frames) deliver(frame); + } + }, + (error: unknown) => { + pending = null; + if (!closed) { + observer.onError?.({ + code: "failed", + message: error instanceof Error ? error.message : "Couldn't follow this chat's response.", + }); + } + }, + ); + return () => { + if (closed) return; + closed = true; + offFrames(); + this.observedRuns.delete(runs); + if (subscriptionId) void this.apis.unobserveRun(subscriptionId).catch(() => {}); + }; + } + + private isObserved(runId: string): boolean { + for (const runs of this.observedRuns) if (runs.has(runId)) return true; + return false; } async markRead(chatId: string, throughMessageId?: string): Promise> { @@ -129,8 +208,13 @@ export class LocalHostAdapter implements HostChatAdapter { return Promise.reject(new HostChatControlError({ code: "unsupported", message: "Local chats send through their own generation." })); } - cancel(_chatId: string, input: HostChatCancelInput): Promise { - return this.apis.stop(input.runId); + async cancel(_chatId: string, input: HostChatCancelInput): Promise { + // This window's own generations stop through their owner check. A run it + // only observes (a phone's turn) stops with the host authority a paired + // phone's Stop has. + const stopped = await this.apis.stop(input.runId); + if (stopped || !this.isObserved(input.runId)) return stopped; + return this.apis.stopHostRun(input.runId); } async respondApproval(chatId: string, input: HostChatApprovalInput): Promise { diff --git a/renderer/lib/hosts/observed-local-run.test.ts b/renderer/lib/hosts/observed-local-run.test.ts new file mode 100644 index 0000000000..ea81376889 --- /dev/null +++ b/renderer/lib/hosts/observed-local-run.test.ts @@ -0,0 +1,549 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { PeerRunEvent, PeerRunSubscription } from "../../shared/peer-host"; +import type { LocalRunFrame, LocalRunFrameMessage } from "../../shared/local-run-frames"; +import { + captureDetachedLifecycleChat, + clearInactiveDetachedLifecycleChat, + detachedLifecycleChatProjection, + detachedProjectionStreamComplete, + isDetachedLifecycleChatDraining, + rememberDetachedLifecycleStream, + visibleDetachedLifecycleProjection, +} from "../chat-terminal-sync"; +import type { ChatMessage } from "../types"; +import { LocalHostAdapter, type LocalChatApis } from "./local-host-adapter"; +import { + createObservedRunLifecycle, + observeLocalRun, + OBSERVED_READ_RETRY_MS, + type ObservedChatRead, + type ObservedTranscriptMessage, +} from "./observed-local-run"; + +const WORKSPACE = "workspace-1"; + +function runEvent(runId: string, sequence: number, type: string, payload: Record = {}): PeerRunEvent { + return { + protocolVersion: 1, + streamId: runId, + sequence, + timestamp: new Date(sequence).toISOString(), + type, + terminal: type === "done" || type === "error" || type === "cancelled", + payload, + }; +} + +/** This Mac's main process as the renderer sees it: one observation and its frame channel. */ +function fakeMain(subscription: Omit) { + const handlers = new Set<(message: LocalRunFrameMessage) => void>(); + const calls: unknown[][] = []; + const unused = async (): Promise => { + throw new Error("not part of this flow"); + }; + const apis: LocalChatApis = { + rename: unused, + remove: unused, + markRead: unused, + approve: unused, + answerQuestionnaire: unused, + respondRemoteApproval: unused, + respondRemoteQuestion: unused, + admitRunInput: unused, + // The phone's run is not this window's, so the owner-checked Stop declines it. + stop: async (runId) => { + calls.push(["stop", runId]); + return false; + }, + stopHostRun: async (runId) => { + calls.push(["stopHostRun", runId]); + return true; + }, + observeRun: async (chatId) => { + calls.push(["observeRun", chatId]); + return { ...subscription, subscriptionId: "sub-1", key: "sub-1", truncated: false }; + }, + unobserveRun: async (id) => { + calls.push(["unobserveRun", id]); + return true; + }, + onRunFrame: (handler) => { + handlers.add(handler); + return () => handlers.delete(handler); + }, + }; + return { + calls, + adapter: new LocalHostAdapter(apis), + send: (...frames: LocalRunFrame[]) => { + for (const handler of handlers) handler({ subscriptionId: "sub-1", chatId: subscription.chatId ?? "", frames }); + }, + }; +} + +/** + * The persisted chat and the pane's cached copy of it. Each read is held until + * the test settles it, as a slow or cancelled IPC read would be. + */ +function chatReads() { + const saved: ObservedTranscriptMessage[] = [{ role: "user" }]; + let cache: readonly ObservedTranscriptMessage[] = []; + const pending: Array<(outcome: ObservedChatRead) => void> = []; + let requested = 0; + return { + saved, + cache: () => cache, + requested: () => requested, + count: () => pending.length, + refetch: () => { + requested++; + return new Promise((resolve) => pending.push(resolve)); + }, + /** Lets every outstanding read finish with what is saved now. */ + finishAll: async () => { + while (pending.length > 0) { + cache = [...saved]; + pending.shift()!({ kind: "read", messages: cache }); + await tick(); + } + }, + /** Lets the oldest outstanding read finish with what is saved now. */ + finishNext: async () => { + cache = [...saved]; + pending.shift()!({ kind: "read", messages: cache }); + await tick(); + }, + /** A competing read cancelled the oldest outstanding one. */ + failNext: async () => { + pending.shift()!({ kind: "failed" }); + await tick(); + }, + }; +} + +const reply = (runId: string): ObservedTranscriptMessage => ({ role: "assistant", timeline: { generationId: runId } }); + +const tick = () => new Promise((settle) => setImmediate(settle)); + +test("a phone's turn on this Mac streams into the open chat live and gives way to the saved reply", async () => { + const chatId = "chat-phone-turn"; + const main = fakeMain({ + runId: "run-phone", + chatId, + state: "streaming", + events: [runEvent("run-phone", 1, "run.started", { chatId, origin: "remote" }), runEvent("run-phone", 2, "text_delta", { text: "Hel" })], + }); + const reads = chatReads(); + const observation = observeLocalRun({ + adapter: main.adapter, + chatId, + workspaceId: WORKSPACE, + refetch: reads.refetch, + now: () => 1_000, + schedule: (publish) => publish(), + }); + await tick(); + + // The phone's message was saved before the run began, so the chat is re-read once. + assert.equal(reads.count(), 1); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "Hel"); + assert.equal(isDetachedLifecycleChatDraining(chatId, WORKSPACE), true); + + main.send( + { kind: "event", event: runEvent("run-phone", 3, "reasoning_delta", { text: "Checking the plan" }) }, + { kind: "event", event: runEvent("run-phone", 4, "text_delta", { text: "lo there" }) }, + ); + const live = detachedLifecycleChatProjection(chatId, WORKSPACE); + assert.equal(live?.content, "Hello there", "text arrives before the run settles"); + assert.equal(live?.reasoning, "Checking the plan"); + assert.equal(live?.observed, true); + assert.equal(detachedProjectionStreamComplete(live), false, "a running reply is revealed as it streams"); + + // Stop from this window reaches the phone's run with host authority. + assert.equal(await main.adapter.cancel(chatId, { runId: live!.streamId }), true); + assert.deepEqual(main.calls.filter(([route]) => route !== "observeRun"), [ + ["stop", "run-phone"], + ["stopHostRun", "run-phone"], + ]); + + main.send( + { kind: "event", event: runEvent("run-phone", 5, "cancelled") }, + { kind: "event", event: runEvent("run-phone", 6, "run.ended", { chatId, state: "cancelled" }) }, + { kind: "state", runId: "run-phone", state: "ended" }, + ); + // Until the saved reply is read, the streamed one stays rather than flashing away. + assert.equal(reads.count(), 1); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "Hello there"); + assert.equal( + detachedProjectionStreamComplete(detachedLifecycleChatProjection(chatId, WORKSPACE)), + true, + "the ended run's text is final", + ); + reads.saved.push(reply("run-phone")); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE), null); + assert.equal(isDetachedLifecycleChatDraining(chatId, WORKSPACE), false); + + // The same observation picks up the chat's next run. + main.send( + { kind: "state", runId: "run-next", state: "streaming" }, + { kind: "event", event: runEvent("run-next", 1, "run.started", { chatId, origin: "remote" }) }, + { kind: "event", event: runEvent("run-next", 2, "text_delta", { text: "Again" }) }, + ); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.streamId, "run-next"); + + observation.close(); + await tick(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE), null, "closing drops the mirror"); + assert.equal(isDetachedLifecycleChatDraining(chatId, WORKSPACE), false); + assert.deepEqual(main.calls[main.calls.length - 1], ["unobserveRun", "sub-1"]); + main.send({ kind: "event", event: runEvent("run-next", 3, "text_delta", { text: " more" }) }); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE), null); +}); + +test("a run that had already finished before the chat was opened shows nothing", async () => { + const chatId = "chat-finished-before"; + const main = fakeMain({ runId: "run-old", chatId, state: "ended", events: [] }); + const reads = chatReads(); + const observation = observeLocalRun({ adapter: main.adapter, chatId, workspaceId: WORKSPACE, refetch: reads.refetch, schedule: (publish) => publish() }); + await tick(); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE), null); + assert.equal(isDetachedLifecycleChatDraining(chatId, WORKSPACE), false); + observation.close(); +}); + +test("a run with undelivered text shows its activity without a partial reply", async () => { + const chatId = "chat-gap"; + const main = fakeMain({ + runId: "run-gap", + chatId, + state: "streaming", + events: [ + runEvent("run-gap", 1, "run.started", { chatId }), + runEvent("run-gap", 40, "snapshot", { reason: "gap", state: "running" }), + runEvent("run-gap", 41, "text_delta", { text: "tail only" }), + ], + }); + const reads = chatReads(); + const observation = observeLocalRun({ adapter: main.adapter, chatId, workspaceId: WORKSPACE, refetch: reads.refetch, schedule: (publish) => publish() }); + await tick(); + await reads.finishAll(); + const projection = detachedLifecycleChatProjection(chatId, WORKSPACE); + assert.equal(projection?.streamId, "run-gap", "Stop stays available"); + assert.equal(projection?.content, ""); + observation.close(); +}); + +test("this window's own route-detached run keeps its own projection", async () => { + const chatId = "chat-own-run"; + const own = { streamId: "run-own", chatId, workspaceId: WORKSPACE }; + rememberDetachedLifecycleStream(own, { content: "Mine so far", reasoning: "", timeline: null, artifacts: [], subagents: [] }); + const main = fakeMain({ + runId: "run-own", + chatId, + state: "streaming", + events: [runEvent("run-own", 1, "run.started", { chatId }), runEvent("run-own", 2, "text_delta", { text: "Mine so far and more" })], + }); + const reads = chatReads(); + const observation = observeLocalRun({ adapter: main.adapter, chatId, workspaceId: WORKSPACE, refetch: reads.refetch, schedule: (publish) => publish() }); + await tick(); + await reads.finishAll(); + const projection = detachedLifecycleChatProjection(chatId, WORKSPACE); + assert.equal(projection?.content, "Mine so far"); + assert.equal(projection?.observed, undefined); + assert.equal(detachedProjectionStreamComplete(projection), true, "a returning route shows its run's text as written"); + observation.close(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "Mine so far", "closing leaves the owner's projection"); + assert.equal(clearInactiveDetachedLifecycleChat(captureDetachedLifecycleChat(own)!, new Set()), true); +}); + +test("a phone's reply stays on screen when the chat goes idle before the run's end arrives", async () => { + const chatId = "chat-idle-first"; + const target = { chatId, workspaceId: WORKSPACE }; + const main = fakeMain({ + runId: "run-idle", + chatId, + state: "streaming", + events: [runEvent("run-idle", 1, "run.started", { chatId, origin: "remote" }), runEvent("run-idle", 2, "text_delta", { text: "All done" })], + }); + const reads = chatReads(); + const lifecycle = createObservedRunLifecycle((observed) => + observeLocalRun({ adapter: main.adapter, ...observed, refetch: reads.refetch, schedule: (publish) => publish() }), + ); + lifecycle.update({ target, active: true }); + await tick(); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "All done"); + + // Main saves the reply, then reports the chat idle before the next frame batch carries the run's end. + reads.saved.push(reply("run-idle")); + lifecycle.update({ target, active: false }); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "All done", "no flash on idle"); + assert.equal(main.calls.some(([route]) => route === "unobserveRun"), false); + + main.send( + { kind: "event", event: runEvent("run-idle", 3, "done") }, + { kind: "event", event: runEvent("run-idle", 4, "run.ended", { chatId, state: "done" }) }, + { kind: "state", runId: "run-idle", state: "ended" }, + ); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "All done", "kept until the reply is read"); + await reads.finishAll(); + assert.ok(reads.cache().some((message) => message.role === "assistant"), "the saved reply is in the cache"); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE), null); + assert.deepEqual(main.calls[main.calls.length - 1], ["unobserveRun", "sub-1"], "then the observation ends"); + lifecycle.dispose(); +}); + +test("leaving the chat or starting a turn in the pane stops the mirror at once", async () => { + const chatId = "chat-leave"; + const main = fakeMain({ + runId: "run-leave", + chatId, + state: "streaming", + events: [runEvent("run-leave", 1, "run.started", { chatId }), runEvent("run-leave", 2, "text_delta", { text: "Partial" })], + }); + const reads = chatReads(); + let starts = 0; + const lifecycle = createObservedRunLifecycle((observed) => { + starts++; + return observeLocalRun({ adapter: main.adapter, ...observed, refetch: reads.refetch, schedule: (publish) => publish() }); + }); + lifecycle.update({ target: { chatId, workspaceId: WORKSPACE }, active: true }); + await tick(); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "Partial"); + + // The pane starts its own turn: its own stream takes over the chat. + lifecycle.update({ target: null, active: true }); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE), null); + assert.deepEqual(main.calls[main.calls.length - 1], ["unobserveRun", "sub-1"]); + + // Another busy chat starts a fresh observation; an idle one starts nothing. + lifecycle.update({ target: { chatId: "chat-other", workspaceId: WORKSPACE }, active: false }); + assert.equal(starts, 1); + lifecycle.update({ target: { chatId: "chat-other", workspaceId: WORKSPACE }, active: true }); + assert.equal(starts, 2); + lifecycle.dispose(); + await tick(); +}); + +test("a finished run is replaced only by a read that holds its saved reply", async () => { + const chatId = "chat-competing-read"; + const main = fakeMain({ + runId: "run-race", + chatId, + state: "streaming", + events: [runEvent("run-race", 1, "run.started", { chatId }), runEvent("run-race", 2, "text_delta", { text: "Answer" })], + }); + const reads = chatReads(); + const observation = observeLocalRun({ + adapter: main.adapter, + chatId, + workspaceId: WORKSPACE, + refetch: reads.refetch, + schedule: (publish) => publish(), + delay: async () => {}, + }); + await tick(); + await reads.finishAll(); + main.send( + { kind: "event", event: runEvent("run-race", 3, "done") }, + { kind: "state", runId: "run-race", state: "ended" }, + ); + // Another refresh of the same chat cancels this read. + await reads.failNext(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "Answer"); + // The retry lands before the reply was saved. + await reads.finishNext(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "Answer", "an older transcript is not the reply"); + reads.saved.push(reply("run-race")); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE), null); + assert.equal(reads.count(), 0, "no further reads once the reply is in"); + observation.close(); +}); + +test("a failed read of a phone's new turn is retried until its message lands", async () => { + const chatId = "chat-started-read"; + const main = fakeMain({ + runId: "run-start", + chatId, + state: "streaming", + events: [runEvent("run-start", 1, "run.started", { chatId, origin: "remote" })], + }); + const reads = chatReads(); + const observation = observeLocalRun({ + adapter: main.adapter, + chatId, + workspaceId: WORKSPACE, + refetch: reads.refetch, + schedule: (publish) => publish(), + delay: async () => {}, + }); + await tick(); + // Every scheduled attempt fails: the first read and each retry. + for (let attempt = 0; attempt <= OBSERVED_READ_RETRY_MS.length; attempt++) await reads.failNext(); + assert.equal(reads.count(), 0, "retries are bounded"); + assert.deepEqual(reads.cache(), []); + + // The next frame from the run asks again, and that read brings in the phone's message. + main.send({ kind: "event", event: runEvent("run-start", 2, "text_delta", { text: "Hi" }) }); + assert.equal(reads.count(), 1); + await reads.finishAll(); + assert.deepEqual(reads.cache(), [{ role: "user" }]); + main.send({ kind: "event", event: runEvent("run-start", 3, "text_delta", { text: " there" }) }); + assert.equal(reads.count(), 0, "a completed read is not repeated"); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "Hi there"); + observation.close(); +}); + +test("a text-only reply without timeline is recognized as the run's saved reply", async () => { + const chatId = "chat-text-only"; + const main = fakeMain({ + runId: "run-text-only", + chatId, + state: "streaming", + events: [ + runEvent("run-text-only", 1, "run.started", { chatId, origin: "remote" }), + runEvent("run-text-only", 2, "text_delta", { text: "Answer" }), + ], + }); + const reads = chatReads(); + const observation = observeLocalRun({ + adapter: main.adapter, + chatId, + workspaceId: WORKSPACE, + refetch: reads.refetch, + schedule: (publish) => publish(), + }); + await tick(); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "Answer"); + + // Send the done event with messageId, which triggers a refetch. + main.send({ kind: "event", event: runEvent("run-text-only", 3, "done", { messageId: "msg-text-only" }) }); + await tick(); + // A refetch is requested, but the reply is not in the cache yet, so it will retry. + assert.equal(reads.count() > 0, true, "refetch is requested after done event"); + + // Add the text-only reply without timeline but with matching messageId to the saved transcript. + reads.saved.push({ role: "assistant", id: "msg-text-only" }); + await reads.finishAll(); + // The projection should be cleared because the text-only saved reply should be recognized as the run's reply via doneMessageId match. + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE), null, "text-only reply is recognized as the run's saved reply"); + assert.equal(isDetachedLifecycleChatDraining(chatId, WORKSPACE), false); + + main.send( + { kind: "event", event: runEvent("run-text-only", 4, "run.ended", { chatId, state: "done" }) }, + { kind: "state", runId: "run-text-only", state: "ended" }, + ); + observation.close(); +}); + +test("a phone's text-only reply cached by another read replaces the mirror at once", async () => { + const chatId = "chat-text-only-cached"; + const main = fakeMain({ + runId: "run-text-cached", + chatId, + state: "streaming", + events: [ + runEvent("run-text-cached", 1, "run.started", { chatId, origin: "remote" }), + runEvent("run-text-cached", 2, "text_delta", { text: "Answer" }), + ], + }); + const reads = chatReads(); + const observation = observeLocalRun({ + adapter: main.adapter, + chatId, + workspaceId: WORKSPACE, + refetch: reads.refetch, + schedule: (publish) => publish(), + }); + await tick(); + await reads.finishAll(); + const prompt: ChatMessage = { id: "prompt", role: "user", content: "Hi", createdAt: 1 }; + const previous: ChatMessage = { id: "msg-previous", role: "assistant", content: "Earlier", createdAt: 0 }; + const saved: ChatMessage = { id: "msg-text-cached", role: "assistant", content: "Answer", createdAt: 2 }; + const shown = (cache: readonly ChatMessage[]) => + visibleDetachedLifecycleProjection(detachedLifecycleChatProjection(chatId, WORKSPACE), cache); + assert.equal(shown([previous, prompt])?.content, "Answer", "the live reply shows under its prompt"); + + main.send({ kind: "event", event: runEvent("run-text-cached", 3, "done", { messageId: saved.id }) }); + await tick(); + // The chat's settle notice re-read the transcript before the observer's own read returned. + assert.equal(shown([previous, prompt, saved]), null, "the saved reply is not shown twice"); + assert.equal(shown([prompt, previous])?.content, "Answer", "an earlier text-only reply does not hide it"); + + await reads.finishAll(); + observation.close(); +}); + +test("a retained observer survives an obsolete idle-release read", async () => { + const chatId = "chat-release-race"; + const target = { chatId, workspaceId: WORKSPACE }; + const main = fakeMain({ + runId: "run-release-race", + chatId, + state: "streaming", + events: [runEvent("run-release-race", 1, "run.started", { chatId, origin: "remote" }), runEvent("run-release-race", 2, "text_delta", { text: "Initial" })], + }); + const reads = chatReads(); + const graceTimers: Array<() => void> = []; + const lifecycle = createObservedRunLifecycle((observed) => + observeLocalRun({ + adapter: main.adapter, + ...observed, + refetch: reads.refetch, + schedule: (publish) => publish(), + delay: async () => {}, + }), + ); + + // Patch setTimeout for grace period detection + const originalSetTimeout = global.setTimeout; + global.setTimeout = ((callback: () => void, ms: number) => { + if (ms === 5000) graceTimers.push(callback); + return originalSetTimeout(callback, ms); + }) as typeof setTimeout; + + try { + lifecycle.update({ target, active: true }); + await tick(); + await reads.finishAll(); + + // Report the chat idle. A grace-period read will be scheduled. + lifecycle.update({ target, active: false }); + await tick(); + assert.equal(graceTimers.length > 0, true, "grace-period timer is scheduled"); + + // Before the grace read fires, report the chat active again (retain). + lifecycle.update({ target, active: true }); + + // Start a new turn on the phone. + main.send( + { kind: "state", runId: "run-next", state: "streaming" }, + { kind: "event", event: runEvent("run-next", 1, "run.started", { chatId, origin: "remote" }) }, + { kind: "event", event: runEvent("run-next", 2, "text_delta", { text: "New answer" }) }, + ); + await tick(); + await reads.finishAll(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "New answer", "new run is shown"); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.streamId, "run-next"); + + // Now fire the grace read from the old run. Without the fix, it would close the observer, + // clearing the newer run's projection and blocking follow-up sends. + // After the fix, the observer stays open because the release authority was revoked. + for (const callback of graceTimers) callback(); + await tick(); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.content, "New answer", "new run projection survives the obsolete grace read"); + assert.equal(detachedLifecycleChatProjection(chatId, WORKSPACE)?.streamId, "run-next"); + + lifecycle.dispose(); + } finally { + global.setTimeout = originalSetTimeout; + } +}); diff --git a/renderer/lib/hosts/observed-local-run.ts b/renderer/lib/hosts/observed-local-run.ts new file mode 100644 index 0000000000..f3eb9b835f --- /dev/null +++ b/renderer/lib/hosts/observed-local-run.ts @@ -0,0 +1,301 @@ +import { + clearObservedRunProjection, + publishObservedRunProjection, +} from "../chat-terminal-sync"; +import type { HostChatAdapter } from "./host-chat-adapter"; +import { + applyRemoteRunEvent, + applyRemoteRunStreamState, + applyRemoteRunSubscription, + handOffRemoteRun, + initialRemoteRunView, + type RemoteRunStep, + type RemoteRunView, +} from "./remote-stream-translator"; + +/** The persisted transcript fields that say which run wrote a reply. */ +export interface ObservedTranscriptMessage { + readonly role: string; + readonly id?: string; + readonly timeline?: { readonly generationId: string } | null; +} + +/** What one re-read of the persisted chat produced. */ +export type ObservedChatRead = + | { readonly kind: "read"; readonly messages: readonly ObservedTranscriptMessage[] } + /** The chat was deleted or no longer exists: there is no reply to wait for. */ + | { readonly kind: "gone" } + /** The read failed or a competing read cancelled it; it proves nothing. */ + | { readonly kind: "failed" }; + +export interface ObserveLocalRunOptions { + adapter: Pick; + chatId: string; + workspaceId: string; + /** Re-reads the persisted chat into the cache (a new turn's message, a finished reply). */ + refetch(): Promise; + now?: () => number; + /** Defers publishing to the end of the current frame batch. */ + schedule?: (callback: () => void) => void; + /** Waits before retrying a read that failed or predates the saved reply. */ + delay?: (ms: number) => Promise; +} + +export interface ObservedLocalRun { + /** Stops at once and drops the projection (the pane left or took over). */ + close(): void; + /** + * The chat went idle: keep showing the run until its saved reply is in the + * cache, then stop. Closes at once when nothing is shown. + */ + release(): void; + /** The chat became busy again before a release finished. */ + retain(): void; + readonly closed: boolean; +} + +/** Backoff between reads that did not return what the projection waits for. */ +export const OBSERVED_READ_RETRY_MS: readonly number[] = [100, 400, 1_500, 4_000]; + +/** Bound on how long a release waits for the run's end to arrive. */ +export const OBSERVED_RELEASE_GRACE_MS = 5_000; + +function settled(view: RemoteRunView): boolean { + return view.status === "done" || view.status === "error" || view.status === "cancelled"; +} + +function hasReplyFrom( + messages: readonly ObservedTranscriptMessage[], + runId: string, + doneMessageId: string | null = null, +): boolean { + return messages.some( + (message) => + message.role === "assistant" && + (message.timeline?.generationId === runId || (doneMessageId !== null && message.id === doneMessageId)), + ); +} + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * Mirrors the chat's current run on this Mac (one a paired phone or another + * window started) into the detached projection store, so the pane shows its + * live text, reasoning, timeline and Stop through the path a route-detached + * run already uses. The projection stays until a completed read has put the + * run's saved reply in the cache, so nothing flashes. + */ +export function observeLocalRun(options: ObserveLocalRunOptions): ObservedLocalRun { + const { adapter, chatId, workspaceId } = options; + const now = options.now ?? Date.now; + const schedule = options.schedule ?? queueMicrotask; + const delay = options.delay ?? wait; + let view = initialRemoteRunView(null, chatId); + let closed = false; + let publishQueued = false; + let reading = false; + let readRequested = false; + /** A read that never completed; the next frame asks again. */ + let readOwed = false; + let releasing = false; + let releaseGeneration = 0; + let releaseTimer: ReturnType | null = null; + let stopObserving: () => void = () => {}; + + const publish = () => { + publishQueued = false; + if (closed || view.runId === null || view.handedOff || view.status === "idle") return; + publishObservedRunProjection( + { streamId: view.runId, chatId, workspaceId }, + // A run with undelivered text shows no partial reply; the persisted one replaces it. + { + text: view.incomplete ? "" : view.text, + reasoning: view.incomplete ? "" : view.reasoning, + timeline: view.timeline, + textStreaming: view.textStreaming, + doneMessageId: view.doneMessageId, + finished: settled(view), + }, + now(), + ); + }; + + const showing = () => view.runId !== null && !view.handedOff && view.status !== "idle"; + + const close = () => { + if (closed) return; + closed = true; + if (releaseTimer !== null) clearTimeout(releaseTimer); + releaseTimer = null; + stopObserving(); + if (view.runId !== null) clearObservedRunProjection(chatId, workspaceId, view.runId); + }; + + const closeIfReleased = () => { + if (releasing && !showing() && !reading) close(); + }; + + const handOff = (runId: string) => { + view = handOffRemoteRun(view); + clearObservedRunProjection(chatId, workspaceId, runId); + }; + + const read = async (): Promise => { + try { + return await options.refetch(); + } catch { + return { kind: "failed" }; + } + }; + + const drainReads = async () => { + if (reading) return; + reading = true; + let attempt = 0; + try { + while (readRequested && !closed) { + readRequested = false; + const runAtRead = view.runId; + const settledAtRead = settled(view); + // With no reply text on screen, nothing can flash: any completed read will do. + const mirroredReply = !view.incomplete && view.text.length > 0; + // Capture doneMessageId before the async read, as view may change. + const doneMessageIdAtRead = view.doneMessageId; + const outcome = await read(); + if (closed) return; + const waitingForReply = settledAtRead && runAtRead !== null && view.runId === runAtRead; + const complete = + outcome.kind === "gone" || + (outcome.kind === "read" && + (!waitingForReply || !mirroredReply || hasReplyFrom(outcome.messages, runAtRead!, doneMessageIdAtRead))); + if (complete) { + readOwed = false; + attempt = 0; + if (waitingForReply) handOff(runAtRead!); + continue; + } + if (attempt < OBSERVED_READ_RETRY_MS.length) { + await delay(OBSERVED_READ_RETRY_MS[attempt]!); + attempt++; + readRequested = true; + continue; + } + attempt = 0; + if (waitingForReply) { + // The reply was never saved; the persisted transcript is all there is. + handOff(runAtRead!); + } else { + readOwed = true; + } + } + } finally { + reading = false; + } + closeIfReleased(); + }; + + const requestRead = () => { + readRequested = true; + void drainReads(); + }; + + const apply = (step: RemoteRunStep) => { + if (closed) return; + const previousRun = view.runId; + view = step.view; + if (previousRun !== null && previousRun !== view.runId) { + clearObservedRunProjection(chatId, workspaceId, previousRun); + } + if (!publishQueued) { + publishQueued = true; + schedule(publish); + } + if (step.refetch || readOwed) requestRead(); + else closeIfReleased(); + }; + + stopObserving = adapter.observe(chatId, { + onSubscription: (subscription) => apply(applyRemoteRunSubscription(view, subscription)), + onEvent: (event) => apply(applyRemoteRunEvent(view, event)), + onState: (state) => apply(applyRemoteRunStreamState(view, state)), + onError: () => { + // Nothing to mirror; the pane keeps its persisted transcript. + closeIfReleased(); + }, + }); + + return { + close, + release: () => { + if (closed || releasing) return; + releasing = true; + if (!showing() && !reading) { + close(); + return; + } + // The run's end normally follows within one frame batch; if it never + // arrives, a final read replaces the mirror before it goes. + const release = ++releaseGeneration; + releaseTimer = setTimeout(() => { + releaseTimer = null; + if (closed || !releasing) return; + void read().then(() => { + // A retain() during the read revokes this release, even if a newer + // release has started since. + if (!closed && releasing && release === releaseGeneration) close(); + }); + }, OBSERVED_RELEASE_GRACE_MS); + }, + retain: () => { + if (closed) return; + releasing = false; + releaseGeneration += 1; + if (releaseTimer !== null) clearTimeout(releaseTimer); + releaseTimer = null; + }, + get closed() { + return closed; + }, + }; +} + +export interface ObservedRunTarget { + readonly chatId: string; + readonly workspaceId: string; +} + +export interface ObservedRunLifecycleState { + /** The pane's chat, or null while it shows a draft or runs its own turn. */ + readonly target: ObservedRunTarget | null; + /** Main reports the chat busy. */ + readonly active: boolean; +} + +/** + * Keeps at most one observation per pane. It starts when the chat becomes + * busy, stops at once when the pane switches chat or runs its own turn, and + * lets a run that just ended stay on screen until its saved reply replaces it. + */ +export function createObservedRunLifecycle(start: (target: ObservedRunTarget) => ObservedLocalRun) { + let current: { target: ObservedRunTarget; run: ObservedLocalRun } | null = null; + const stop = () => { + current?.run.close(); + current = null; + }; + return { + update({ target, active }: ObservedRunLifecycleState): void { + const moved = + current !== null && + (target === null || current.target.chatId !== target.chatId || current.target.workspaceId !== target.workspaceId); + if (current && (moved || current.run.closed)) stop(); + if (target === null) return; + if (active) { + if (current) current.run.retain(); + else current = { target, run: start(target) }; + } else { + current?.run.release(); + } + }, + dispose: stop, + }; +} diff --git a/renderer/lib/hosts/use-observed-local-run.ts b/renderer/lib/hosts/use-observed-local-run.ts new file mode 100644 index 0000000000..d9752373f3 --- /dev/null +++ b/renderer/lib/hosts/use-observed-local-run.ts @@ -0,0 +1,56 @@ +import * as React from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { chatsApi } from "../ipc"; +import { queryKeys } from "../queries"; +import { isChatCacheDeleted } from "../chat-deletion-cache"; +import { localHostAdapter } from "./local-host-adapter"; +import { createObservedRunLifecycle, observeLocalRun, type ObservedChatRead } from "./observed-local-run"; + +type ObservedRunLifecycle = ReturnType; + +/** + * Mirrors a run this Mac hosts for the visible chat while this pane is not + * the one running it (a paired phone's turn, another window's). Observation + * starts while main reports the chat `active`; when the chat goes idle the + * finished run stays until its saved reply is in the cache. `chatId` null (a + * draft, or the pane running its own turn) stops it at once, so nobody + * watching costs nothing. + */ +export function useObservedLocalRun(chatId: string | null, workspaceId: string | undefined, active: boolean): void { + const queryClient = useQueryClient(); + const lifecycleRef = React.useRef(null); + + React.useEffect(() => { + const lifecycle = createObservedRunLifecycle((target) => + observeLocalRun({ + adapter: localHostAdapter, + chatId: target.chatId, + workspaceId: target.workspaceId, + refetch: async (): Promise => { + const chatKey = queryKeys.chat(target.chatId); + if (isChatCacheDeleted(target.chatId)) return { kind: "gone" }; + await queryClient.cancelQueries({ queryKey: chatKey, exact: true }); + if (isChatCacheDeleted(target.chatId)) return { kind: "gone" }; + // A competing read cancelling this one rejects; the observer retries. + const chat = await queryClient.fetchQuery({ + queryKey: chatKey, + queryFn: () => chatsApi.get(target.chatId), + staleTime: 0, + }); + void queryClient.invalidateQueries({ queryKey: queryKeys.chats }); + return chat ? { kind: "read", messages: chat.messages } : { kind: "gone" }; + }, + }), + ); + lifecycleRef.current = lifecycle; + return () => { + lifecycle.dispose(); + if (lifecycleRef.current === lifecycle) lifecycleRef.current = null; + }; + }, [queryClient]); + + // Declared after the lifecycle so it runs once one exists. + React.useEffect(() => { + lifecycleRef.current?.update({ target: chatId && workspaceId ? { chatId, workspaceId } : null, active }); + }, [active, chatId, workspaceId, queryClient]); +} diff --git a/renderer/lib/ipc.ts b/renderer/lib/ipc.ts index d91f7d8acb..41dcee4eb7 100644 --- a/renderer/lib/ipc.ts +++ b/renderer/lib/ipc.ts @@ -226,6 +226,7 @@ import type { PeerRunTarget, } from "../shared/peer-host"; import type { PeerOperation } from "../shared/peer-operation"; +import type { LocalRunCursor, LocalRunFrameMessage } from "../shared/local-run-frames"; import { invoke, onNotification } from "./ipc-bridge"; export { invoke, onNotification } from "./ipc-bridge"; @@ -239,6 +240,23 @@ export interface AppInfo { } +/** + * Runs this Mac hosts but this window did not start (a paired phone's turn, + * another window's). Frames arrive batched, only for this window's own + * observations. + */ +export const localRunsApi = { + observe: (chatId: string, cursor?: LocalRunCursor) => + invoke("runs:observeLocal", chatId, cursor ?? null), + unobserve: (subscriptionId: string) => invoke("runs:unobserveLocal", subscriptionId), + onFrame: (handler: (message: LocalRunFrameMessage) => void) => + onNotification("runs:local-frame", handler), + /** Host-authority Stop for a run this window observes; false when it already finished. */ + stop: (runId: string) => invoke("runs:stopLocal", runId), + /** The given runs that have finished for good on this Mac. */ + settled: (runIds: readonly string[]) => invoke("runs:settledLocal", [...runIds]), +}; + export const peerHostsApi = { list: () => invoke("remote:peersList"), pair: (payload: string) => invoke("remote:peersPair", payload), diff --git a/renderer/main/chat-pane.tsx b/renderer/main/chat-pane.tsx index 9950d13c29..57b97f9f81 100644 --- a/renderer/main/chat-pane.tsx +++ b/renderer/main/chat-pane.tsx @@ -38,6 +38,8 @@ import * as React from "react"; import { useNavigate } from "@tanstack/react-router"; import { useMarkChatRead } from "../lib/use-mark-chat-read"; import { localHostAdapter } from "../lib/hosts/local-host-adapter"; +import { useObservedLocalRun } from "../lib/hosts/use-observed-local-run"; +import { useActiveChatIds } from "../lib/use-chat-activity"; import { useChatSession } from "../lib/hosts/use-chat-session"; import { LOCAL_HOST_ID } from "../shared/peer-host"; import { useQueryClient } from "@tanstack/react-query"; @@ -175,8 +177,10 @@ import { persistedChatWorkspaceId } from "../shared/chat-workspace"; import { detachedTextStreamingRemaining, detachedLifecycleChatProjection, + detachedProjectionStreamComplete, isDetachedLifecycleChatDraining, subscribeDetachedLifecycleStreams, + visibleDetachedLifecycleProjection, } from "../lib/chat-terminal-sync"; import { ASSISTANT_WORKSPACE_ID, @@ -273,11 +277,11 @@ export function ChatPane({ chatId }: { chatId: string }) { () => detachedLifecycleChatProjection(chatId, effectiveWorkspaceId), () => null, ); - // A durable terminal message can reach the cache before detached ownership is - // cleared. During that handoff there is no longer a response to stop or steer. - const cachedMessages = chat.data?.messages; - const visibleDetachedProjection = - cachedMessages?.[cachedMessages.length - 1]?.role === "assistant" ? null : detachedProjection; + const visibleDetachedProjection = visibleDetachedLifecycleProjection(detachedProjection, chat.data?.messages); + // Run input is admitted only for the document that owns the run, so a + // mirrored run (a phone's turn) offers Stop and queueing but not Steer. + const observedRunVisible = visibleDetachedProjection?.observed === true; + const steerableDetachedProjection = observedRunVisible ? null : visibleDetachedProjection; const terminal = useWorkspaceTerminal(); const git = useGitInfo(effectiveWorkspace?.id); const environmentPanel = useEnvironmentPanel(); @@ -829,6 +833,15 @@ export function ChatPane({ chatId }: { chatId: string }) { const imageArtifactRecoveryUnavailable = chat.data?.imageArtifactRecoveryUnavailable === true; const isGenerating = streamingText !== null && !hasUnpersistedResponse; const contextLiveGeneration = isGenerating || isStartingGeneration; + // A run this pane did not start (a paired phone's turn) streams in live + // once main reports the chat busy, and stays until its saved reply lands. + // A draft or this pane's own turn stops it; an idle chat holds nothing. + const activeChatIds = useActiveChatIds(); + useObservedLocalRun( + draft || isGenerating || isStartingGeneration ? null : chatId, + effectiveWorkspaceId, + activeChatIds.has(chatId), + ); const thinkingDisabledReason = isStartingGeneration || isGenerating ? "Available after this response" @@ -1880,7 +1893,7 @@ export function ChatPane({ chatId }: { chatId: string }) { if (text.length > MAX_RUN_INPUT_TEXT) { throw new Error("Guidance is too long to steer. Queue it as a follow-up instead."); } - const streamId = generationRef.current?.streamId ?? visibleDetachedProjection?.streamId; + const streamId = generationRef.current?.streamId ?? steerableDetachedProjection?.streamId; if (!streamId || isStoppingGeneration || stopRequestedRef.current) { throw new Error("The current response has ended. Send your message normally."); } @@ -1903,17 +1916,17 @@ export function ChatPane({ chatId }: { chatId: string }) { throw new Error(steerRejectionMessage(receipt.reason)); } }, - [admitSteer, isStoppingGeneration, visibleDetachedProjection], + [admitSteer, isStoppingGeneration, steerableDetachedProjection], ); const canSteerQueued = !draft && - (canStopGeneration || Boolean(visibleDetachedProjection)) && + (canStopGeneration || Boolean(steerableDetachedProjection)) && !isStoppingGeneration; const steerQueued = React.useCallback( async (id: string) => { - const streamId = generationRef.current?.streamId ?? visibleDetachedProjection?.streamId; + const streamId = generationRef.current?.streamId ?? steerableDetachedProjection?.streamId; if (!streamId || isStoppingGeneration || stopRequestedRef.current) { toast.error("The current response has ended. The message stays queued."); return; @@ -1935,7 +1948,7 @@ export function ChatPane({ chatId }: { chatId: string }) { ); } }, - [admitSteer, isStoppingGeneration, messageQueue, visibleDetachedProjection], + [admitSteer, isStoppingGeneration, messageQueue, steerableDetachedProjection], ); const cancelAgentForContextChange = React.useCallback(() => { @@ -2779,7 +2792,7 @@ export function ChatPane({ chatId }: { chatId: string }) { freezeWhileSending={Boolean(draft)} firstMessageSaving={draft?.sending === true} onQueue={draft ? undefined : queueMessage} - onSteer={draft ? undefined : steerMessage} + onSteer={draft || observedRunVisible ? undefined : steerMessage} hasQueuedMessages={queuedState.messages.length > 0} compactionHeld={queuedState.holdReason === "compaction"} forkSummaryHold={ @@ -3063,7 +3076,7 @@ export function ChatPane({ chatId }: { chatId: string }) { streamingVisualDrafts={visualDrafts} streamingUiVisuals={displayedStreamingUiVisuals} streamingUiDrafts={uiDrafts} - streamComplete={streamComplete || visibleDetachedProjection !== null} + streamComplete={streamComplete || detachedProjectionStreamComplete(visibleDetachedProjection)} persistedHandoffMessageId={persistedHandoffMessageId} onStreamHandoffComplete={() => streamHandoffRef.current?.()} timeline={displayedGenerationTimeline} diff --git a/renderer/main/chat-transition.test.tsx b/renderer/main/chat-transition.test.tsx index 8453fbcf50..f2392d1a2a 100644 --- a/renderer/main/chat-transition.test.tsx +++ b/renderer/main/chat-transition.test.tsx @@ -350,7 +350,8 @@ test("revisited generations expose Stop and queue/steer without admitting a seco const pane = source("./chat-pane.tsx"); const send = between(pane, "const handleSend = React.useCallback(", "const handleStop = React.useCallback"); const stop = between(pane, "const handleStop = React.useCallback", "const { queue: messageQueue"); - assert.match(pane, /cachedMessages\?\.\[cachedMessages\.length - 1\]\?\.role === "assistant" \? null : detachedProjection/u); + // The visibility rule is now tested behaviorally in chat-terminal-sync.test.ts: + // "a saved reply hides an own run, but a mirrored run only by its own reply" assert.match(pane, /detachedGenerationDraining && !visibleDetachedProjection\s*\? "Response continues in the background/u); assert.match(pane, /isGenerating=\{isGenerating \|\| isStartingGeneration \|\| Boolean\(visibleDetachedProjection\)\}/u); assert.match(pane, /canStopGeneration=\{\(canStopGeneration \|\| Boolean\(visibleDetachedProjection\)\) && !isStoppingGeneration\}/u); diff --git a/renderer/main/root-view.tsx b/renderer/main/root-view.tsx index 54b3cfa52f..fabf6ed8aa 100644 --- a/renderer/main/root-view.tsx +++ b/renderer/main/root-view.tsx @@ -3,7 +3,7 @@ import { Outlet, useNavigate, useRouterState } from "@tanstack/react-router"; import { PairingRequestSheet } from "../components/remote-pairing-request-sheet"; import { useQueryClient } from "@tanstack/react-query"; import * as React from "react"; -import { appApi, chatsApi, onNotification } from "../lib/ipc"; +import { appApi, chatsApi, localRunsApi, onNotification } from "../lib/ipc"; import { useTheme } from "../lib/use-theme"; import { useActiveWorkspace, WorkspaceProvider } from "../lib/workspace-context"; import { WorkspaceTerminalProvider, useWorkspaceTerminal } from "../components/terminal-drawer"; @@ -29,6 +29,7 @@ import { pendingDetachedLifecycleChats, preferLatestTerminalChat, reconcileChatReadUntilAuthoritative, + releaseSettledDetachedLifecycleStreams, subscribeChatReadReconciliations, subscribeChatSettlements, subscribeDetachedTerminalChats, @@ -344,8 +345,24 @@ function RootContent() { () => subscribeChatSettlements(onNotification, (settlement) => { void reconcileDetachedLifecycleChat(settlement); + // Main settles each stream on its own. One that ended while the chat + // stays busy (a phone's turn right after it) is released now instead + // of draining until the whole chat goes idle. + void releaseSettledDetachedLifecycleStreams(settlement, { + settled: (streamIds) => localRunsApi.settled(streamIds), + refreshChat: async (chatId) => { + const chatKey = queryKeys.chat(chatId); + if (isChatCacheDeleted(chatId)) return; + await queryClient.cancelQueries({ queryKey: chatKey, exact: true }); + if (isChatCacheDeleted(chatId)) return; + await queryClient.fetchQuery({ queryKey: chatKey, queryFn: () => chatsApi.get(chatId), staleTime: 0 }); + await queryClient.refetchQueries({ queryKey: queryKeys.chats, type: "all" }); + }, + }).catch(() => { + // Not proof of settlement; the chat-level idle path still releases it. + }); }), - [reconcileDetachedLifecycleChat], + [queryClient, reconcileDetachedLifecycleChat], ); React.useEffect(() => { diff --git a/renderer/preload-channels.ts b/renderer/preload-channels.ts index 1b7ba9a486..4cca2ed386 100644 --- a/renderer/preload-channels.ts +++ b/renderer/preload-channels.ts @@ -31,6 +31,7 @@ export const INVOKE_PREFIXES = [ "profile:", "pullRequests:", "remote:", + "runs:", "schedule:", "settings:", "shortcut:", @@ -119,6 +120,7 @@ export const NOTIFICATION_CHANNEL_VALUES = [ "remote:approval-changed", "remote:host-feed", "remote:peer-run-frame", + "runs:local-frame", "remote:peer-host-state", "remote:pairing-requests-changed", "remote:peer-discovery", diff --git a/renderer/shared/local-run-frames.ts b/renderer/shared/local-run-frames.ts new file mode 100644 index 0000000000..6a9c54ae0a --- /dev/null +++ b/renderer/shared/local-run-frames.ts @@ -0,0 +1,39 @@ +import type { PeerRunEvent, PeerRunStreamState } from "./peer-host"; +import { isSafeSubagentIdentifier } from "./subagent-runs"; + +/** + * This Mac's renderer mirroring a run its own process hosts (one a paired + * phone, another window or a headless caller started). The wire vocabulary is + * the Remote run stream's, so the same translator folds both. + */ + +/** Notification channel carrying batched frames to the one subscribing document. */ +export const LOCAL_RUN_FRAME_CHANNEL = "runs:local-frame" as const; + +/** Where a re-subscribing observer left off; ignored once the chat has moved to another run. */ +export interface LocalRunCursor { + runId: string; + sequence: number; +} + +export type LocalRunFrame = + | { kind: "event"; event: PeerRunEvent } + | { kind: "state"; runId: string | null; state: PeerRunStreamState }; + +/** Every frame of one ~16ms batch, in journal order. */ +export interface LocalRunFrameMessage { + subscriptionId: string; + chatId: string; + frames: LocalRunFrame[]; +} + +/** `undefined` for no cursor; throws for anything malformed. */ +export function parseLocalRunCursor(value: unknown): LocalRunCursor | undefined { + if (value === undefined || value === null) return undefined; + if (typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid run cursor."); + const { runId, sequence } = value as Record; + if (!isSafeSubagentIdentifier(runId) || !Number.isSafeInteger(sequence) || (sequence as number) < 0) { + throw new Error("Invalid run cursor."); + } + return { runId, sequence: sequence as number }; +} diff --git a/scripts/ci-test-registry.json b/scripts/ci-test-registry.json index ec8e793c09..1c11822762 100644 --- a/scripts/ci-test-registry.json +++ b/scripts/ci-test-registry.json @@ -307,6 +307,7 @@ "main/handlers/assistant-live-status.test.ts", "main/handlers/bot-params.test.ts", "main/handlers/bots.contract.test.ts", + "main/handlers/local-runs.test.ts", "main/handlers/mcp-provider-auth.test.ts", "main/handlers/peer-host-live.test.ts", "main/handlers/peer-pairing.test.ts", @@ -763,6 +764,7 @@ "renderer/lib/hosts/host-resources.test.ts", "renderer/lib/hosts/local-host-adapter.test.ts", "renderer/lib/hosts/new-chat-targets.test.ts", + "renderer/lib/hosts/observed-local-run.test.ts", "renderer/lib/hosts/peer-host-feed-state.test.ts", "renderer/lib/hosts/remote-chat-mapper.test.ts", "renderer/lib/hosts/remote-new-chat.test.ts",