:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): stop cancelled navigations killing live subscriptions (#83905)
Charles Vien02e35aa44710
diff --git a/products/desktop/apps/code/src/main/external-links.ts b/products/desktop/apps/code/src/main/external-links.tsindex cc0ea4b4b666..0dba8fd4434b 100644--- a/products/desktop/apps/code/src/main/external-links.ts+++ b/products/desktop/apps/code/src/main/external-links.ts@@ -14,6 +14,14 @@ function urlScheme(url: string): string {}}+function urlHost(url: string): string {+ try {+ return new URL(url).host;+ } catch {+ return "<unparseable>";+ }+}+// `shell.openExternal` dispatches to whatever app the OS registered for the// scheme, so it must never receive a scheme outside the http/https/mailto// allowlist: renderer content (including sandboxed MCP apps) can reach these@@ -101,6 +109,10 @@ export function setupExternalLinkHandlers(window.webContents.on("will-navigate", (event, url) => {if (isInAppNavigation(url, appHome)) return;event.preventDefault();+ log.info("Cancelled main-frame navigation, opening externally", {+ scheme: urlScheme(url),+ host: urlHost(url),+ });openExternalIfSafe(url);});diff --git a/products/desktop/apps/code/src/main/window.ts b/products/desktop/apps/code/src/main/window.tsindex 507d87d7e590..eb44b1bbf3e1 100644--- a/products/desktop/apps/code/src/main/window.ts+++ b/products/desktop/apps/code/src/main/window.ts@@ -367,6 +367,13 @@ export function createWindow(): void {cause: error.cause instanceof Error ? error.cause.stack : error.cause,});},+ onNavigationCleanup: ({ webContentsId, url, aborted }) => {+ trpcLog.info("Main-frame navigation committed", {+ webContentsId,+ url,+ abortedOperations: aborted,+ });+ },});const rendererFilePath = path.join(diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 8d694aff5f15..bbdf6d08a23b 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -127,6 +127,19 @@ const AUTO_RETRY_DELAY_MS = 10_000;const AUTH_RESTORE_MAX_RETRY_WAITS = 6;const MAX_SUPERSEDED_RUN_IDS = 100;const MAX_RESPONDED_PERMISSION_REQUEST_IDS = 500;+/**+ * A transport that ends a subscription with no error can be resubscribed, but+ * one that does so on every attempt must not be retried forever. The counter+ * resets as soon as an event arrives, so a healthy resubscribe costs nothing.+ */+const MAX_HOST_ENDED_RESUBSCRIBES = 3;+/**+ * A local turn that delivers nothing to this renderer for this long is logged+ * once, with whether the run is still subscribed, so a transcript that stops+ * updating can be told apart from an agent that is quietly working.+ */+const LOCAL_SILENCE_WARN_AFTER_MS = 60_000;+const LOCAL_SILENCE_CHECK_INTERVAL_MS = 30_000;/*** Streamed events are buffered and flushed on this cadence so a burst of tokens* coalesces into one processing pass (and roughly one render) instead of one@@ -182,7 +195,11 @@ type TrpcQuery = { query: (input?: any) => Promise<any> };type TrpcSubscription = {subscribe: (input: any,- handlers: { onData: (data: any) => void; onError?: (err: unknown) => void },+ handlers: {+ onData: (data: any) => void;+ onError?: (err: unknown) => void;+ onComplete?: () => void;+ },) => { unsubscribe: () => void };};@@ -1641,6 +1658,13 @@ export class SessionService {permission?: { unsubscribe: () => void };}>();+ /** Resubscribes since the run's last received event, per taskRunId. */+ private hostEndedResubscribes = new Map<string, number>();+ /** When each local run last delivered a session event to this renderer. */+ private lastSessionEventAt = new Map<string, number>();+ /** Runs already logged for their current stretch of silence. */+ private silenceLogged = new Set<string>();+ private silenceCheckHandle: ReturnType<typeof setInterval> | null = null;/** Active cloud task watchers, keyed by taskId */private cloudTaskWatchers = new Map<string, CloudTaskWatcher>();private cloudLogGapReconciler: CloudLogGapReconciler;@@ -2634,6 +2658,10 @@ export class SessionService {private lastAgentTextAt = new Map<string, number>();private enqueueSessionEvent(taskRunId: string, acpMsg: AcpMessage): void {+ this.hostEndedResubscribes.delete(taskRunId);+ this.lastSessionEventAt.set(taskRunId, Date.now());+ this.silenceLogged.delete(taskRunId);+ this.ensureSilenceCheck();if (isAgentTextStreamEvent(acpMsg)) {this.lastAgentTextAt.set(taskRunId, Date.now());}@@ -2673,6 +2701,47 @@ export class SessionService {}}+ private ensureSilenceCheck(): void {+ if (this.silenceCheckHandle !== null) return;+ this.silenceCheckHandle = setInterval(+ () => this.checkLocalSessionSilence(),+ LOCAL_SILENCE_CHECK_INTERVAL_MS,+ );+ }++ private checkLocalSessionSilence(): void {+ const now = Date.now();+ let anyPending = false;+ for (const session of Object.values(this.d.store.getSessions())) {+ if (session.isCloud || !session.isPromptPending) continue;+ if (session.status !== "connected") continue;+ anyPending = true;+ const { taskRunId } = session;+ if (this.silenceLogged.has(taskRunId)) continue;+ const lastSignalAt = Math.max(+ this.lastSessionEventAt.get(taskRunId) ?? 0,+ session.promptStartedAt ?? 0,+ );+ if (lastSignalAt === 0) continue;+ const silentForMs = now - lastSignalAt;+ if (silentForMs < LOCAL_SILENCE_WARN_AFTER_MS) continue;+ this.silenceLogged.add(taskRunId);+ this.d.log.warn("Local session silent while a prompt is pending", {+ taskRunId,+ taskId: session.taskId,+ silentForMs,+ subscribed: this.subscriptions.has(taskRunId),+ bufferedEvents: this.pendingSessionEvents.get(taskRunId)?.length ?? 0,+ eventCount: session.events.length,+ online: this.d.getIsOnline(),+ });+ }+ if (!anyPending && this.silenceCheckHandle !== null) {+ clearInterval(this.silenceCheckHandle);+ this.silenceCheckHandle = null;+ }+ }+// --- Transcript residency (memory eviction) ---/** taskRunIds whose transcript was freed and must be reloaded on next view. */@@ -2801,6 +2870,7 @@ export class SessionService {"Lost connection to the agent. Please retry or start a new session.",);},+ onComplete: () => this.resubscribeIfHostEnded(taskRunId, "event"),},);@@ -2817,6 +2887,8 @@ export class SessionService {error: err,});},+ onComplete: () =>+ this.resubscribeIfHostEnded(taskRunId, "permission"),},);@@ -2826,14 +2898,50 @@ export class SessionService {});}+ /**+ * A subscription completing without an error means the host tore down the+ * transport rather than the agent finishing: the renderer would otherwise+ * keep showing a "connected" session that never receives another event.+ * Our own teardown removes the entry from `subscriptions` before+ * unsubscribing, so the completion it triggers finds nothing to redo.+ */+ private resubscribeIfHostEnded(+ taskRunId: string,+ which: "event" | "permission",+ ): void {+ const current = this.subscriptions.get(taskRunId);+ if (!current) return;+ this.subscriptions.delete(taskRunId);+ current.event.unsubscribe();+ current.permission?.unsubscribe();++ const attempts = (this.hostEndedResubscribes.get(taskRunId) ?? 0) + 1;+ if (attempts > MAX_HOST_ENDED_RESUBSCRIBES) {+ this.d.log.error(+ "Session subscription keeps ending without an error, giving up",+ { taskRunId, which, attempts },+ );+ return;+ }+ this.hostEndedResubscribes.set(taskRunId, attempts);+ this.d.log.warn(+ "Session subscription ended without an error, resubscribing",+ { taskRunId, which, attempts },+ );+ this.subscribeToChannel(taskRunId);+ }+private unsubscribeFromChannel(taskRunId: string): void {// Apply anything still buffered before we stop listening, so a closing// channel doesn't drop its final events.this.flushSessionEventsForTask(taskRunId);const subscription = this.subscriptions.get(taskRunId);+ this.subscriptions.delete(taskRunId);subscription?.event.unsubscribe();subscription?.permission?.unsubscribe();- this.subscriptions.delete(taskRunId);+ this.hostEndedResubscribes.delete(taskRunId);+ this.lastSessionEventAt.delete(taskRunId);+ this.silenceLogged.delete(taskRunId);this.liveTurnContent.delete(taskRunId);this.agentSpokeAt.delete(taskRunId);this.lastAgentTextAt.delete(taskRunId);@@ -2868,6 +2976,13 @@ export class SessionService {this.sessionEventFlushHandle = null;}this.pendingSessionEvents.clear();+ this.hostEndedResubscribes.clear();+ this.lastSessionEventAt.clear();+ this.silenceLogged.clear();+ if (this.silenceCheckHandle !== null) {+ clearInterval(this.silenceCheckHandle);+ this.silenceCheckHandle = null;+ }for (const timer of this.eventEvictionTimers.values()) clearTimeout(timer);this.eventEvictionTimers.clear();this.evictedRunIds.clear();@@ -3888,6 +4003,8 @@ export class SessionService {promptStartedAt: Date.now(),pausedDurationMs: 0,});+ this.silenceLogged.delete(taskRunId);+ this.ensureSilenceCheck();const skillButtonId = this.d.h.extractSkillButtonId(blocks);if (skillButtonId) {@@ -6110,6 +6227,15 @@ export class SessionService {},onError: (err: unknown) =>this.d.log.error("Cloud task subscription error", { taskId, err }),+ onComplete: () => {+ if (!this.isCurrentCloudTaskWatcher(taskId, runId, startToken)) {+ return;+ }+ this.d.log.warn(+ "Cloud task subscription ended without an error, updates stop until the task is reopened",+ { taskId, runId },+ );+ },},);@@ -6601,8 +6727,8 @@ export class SessionService {const watcher = this.cloudTaskWatchers.get(taskId);if (!watcher) return;- watcher.subscription.unsubscribe();this.cloudTaskWatchers.delete(taskId);+ watcher.subscription.unsubscribe();this.cloudLogGapReconciler.forgetDeficiency(watcher.runId);}diff --git a/products/desktop/packages/core/src/sessions/sessionSubscriptionLifecycle.test.ts b/products/desktop/packages/core/src/sessions/sessionSubscriptionLifecycle.test.tsnew file mode 100644index 000000000000..3ecbed0d5b79--- /dev/null+++ b/products/desktop/packages/core/src/sessions/sessionSubscriptionLifecycle.test.ts@@ -0,0 +1,201 @@+import type { AgentSession } from "@posthog/shared";+import { describe, expect, it, vi } from "vitest";+import { SessionService, type SessionServiceDeps } from "./sessionService";++const RUN_ID = "run-1";++interface Handlers {+ onData: (payload: unknown) => void;+ onError?: (err: unknown) => void;+ onComplete?: () => void;+}++/** Mirrors the ipc link: tearing a subscription down completes its observer. */+function fakeSubscription() {+ const subscriptions: { handlers: Handlers; unsubscribe: () => void }[] = [];+ return {+ subscriptions,+ subscribe: vi.fn((_input: unknown, handlers: Handlers) => {+ const unsubscribe = vi.fn(() => handlers.onComplete?.());+ subscriptions.push({ handlers, unsubscribe });+ return { unsubscribe };+ }),+ };+}++function createHarness(sessionOverrides: Partial<AgentSession> = {}) {+ const sessions: Record<string, AgentSession> = {+ [RUN_ID]: {+ taskRunId: RUN_ID,+ taskId: "task-1",+ taskTitle: "Local Task",+ events: [],+ messageQueue: [],+ pendingPermissions: new Map(),+ status: "connected",+ isPromptPending: false,+ promptStartedAt: null,+ ...sessionOverrides,+ } as unknown as AgentSession,+ };+ const events = fakeSubscription();+ const permissions = fakeSubscription();+ const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };+ const deps = {+ store: {+ getSessions: () => sessions,+ getSessionByTaskId: (taskId: string) =>+ Object.values(sessions).find((s) => s.taskId === taskId),+ updateSession: vi.fn(),+ appendEvents: vi.fn(),+ replaceOptimisticWithEvent: vi.fn(),+ setPendingPermissions: vi.fn(),+ clearMessageQueue: vi.fn(),+ clearTailOptimisticItems: vi.fn(),+ appendOptimisticItem: vi.fn(),+ },+ log,+ getIsOnline: () => true,+ notifyAgentSession: vi.fn(),+ enqueueSpeech: vi.fn(),+ trpc: {+ agent: {+ onSessionEvent: { subscribe: events.subscribe },+ onPermissionRequest: { subscribe: permissions.subscribe },+ onSessionIdleKilled: { subscribe: () => ({ unsubscribe: vi.fn() }) },+ },+ },+ } as unknown as SessionServiceDeps;+ const service = new SessionService(deps);+ (+ service as unknown as { subscribeToChannel(taskRunId: string): void }+ ).subscribeToChannel(RUN_ID);+ return { service, events, permissions, log };+}++describe("session subscription lifecycle", () => {+ it("resubscribes when the host ends a subscription without an error", () => {+ const { events, permissions, log } = createHarness();++ events.subscriptions[0].handlers.onComplete?.();++ expect(events.subscribe).toHaveBeenCalledTimes(2);+ expect(permissions.subscribe).toHaveBeenCalledTimes(2);+ expect(permissions.subscriptions[0].unsubscribe).toHaveBeenCalledTimes(1);+ expect(log.warn).toHaveBeenCalledWith(+ "Session subscription ended without an error, resubscribing",+ { taskRunId: RUN_ID, which: "event", attempts: 1 },+ );+ });++ it("stops resubscribing when the host keeps ending the subscription", () => {+ const { events, log } = createHarness();++ for (let i = 0; i < 5; i++) {+ events.subscriptions.at(-1)?.handlers.onComplete?.();+ }++ expect(events.subscribe).toHaveBeenCalledTimes(4);+ expect(log.error).toHaveBeenCalledWith(+ "Session subscription keeps ending without an error, giving up",+ { taskRunId: RUN_ID, which: "event", attempts: 4 },+ );+ });++ it("forgets earlier resubscribes once events flow again", () => {+ vi.useFakeTimers();+ try {+ const { events, log } = createHarness();++ for (let i = 0; i < 3; i++) {+ events.subscriptions.at(-1)?.handlers.onComplete?.();+ }+ events.subscriptions.at(-1)?.handlers.onData({+ type: "acp_message",+ ts: 1,+ message: { jsonrpc: "2.0", method: "session/update", params: {} },+ });+ events.subscriptions.at(-1)?.handlers.onComplete?.();++ expect(events.subscribe).toHaveBeenCalledTimes(5);+ expect(log.error).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it("does not resubscribe when the service tears the channel down itself", () => {+ const { service, events, permissions, log } = createHarness();++ service.reset();++ expect(events.subscriptions[0].unsubscribe).toHaveBeenCalledTimes(1);+ expect(events.subscribe).toHaveBeenCalledTimes(1);+ expect(permissions.subscribe).toHaveBeenCalledTimes(1);+ expect(log.warn).not.toHaveBeenCalled();+ });++ describe("silence while a local prompt is pending", () => {+ const chunk = {+ type: "acp_message",+ ts: 1,+ message: {+ jsonrpc: "2.0",+ method: "session/update",+ params: {+ sessionId: RUN_ID,+ update: {+ sessionUpdate: "agent_message_chunk",+ content: { type: "text", text: "x" },+ },+ },+ },+ };++ it.each([+ {+ name: "logs one warning after a minute of silence",+ eventEvery: null,+ warnings: 1,+ },+ {+ name: "stays quiet while events keep arriving",+ eventEvery: 30_000,+ warnings: 0,+ },+ ])("$name", ({ eventEvery, warnings }) => {+ vi.useFakeTimers();+ try {+ const { events, log, service } = createHarness({+ isPromptPending: true,+ promptStartedAt: Date.now(),+ });+ // A first event starts the check, as the prompt echo does in the app.+ events.subscriptions[0].handlers.onData(chunk);++ for (let elapsed = 0; elapsed < 150_000; elapsed += 30_000) {+ vi.advanceTimersByTime(30_000);+ if (eventEvery !== null) {+ events.subscriptions[0].handlers.onData(chunk);+ }+ }++ const silenceWarnings = log.warn.mock.calls.filter(+ ([message]) =>+ message === "Local session silent while a prompt is pending",+ );+ expect(silenceWarnings).toHaveLength(warnings);+ if (warnings > 0) {+ expect(silenceWarnings[0][1]).toMatchObject({+ taskRunId: RUN_ID,+ subscribed: true,+ online: true,+ });+ }+ service.reset();+ } finally {+ vi.useRealTimers();+ }+ });+ });+});diff --git a/products/desktop/packages/electron-trpc/src/main/__tests__/createIPCHandler.test.ts b/products/desktop/packages/electron-trpc/src/main/__tests__/createIPCHandler.test.tsindex b348f3177088..b3311609d47c 100644--- a/products/desktop/packages/electron-trpc/src/main/__tests__/createIPCHandler.test.ts+++ b/products/desktop/packages/electron-trpc/src/main/__tests__/createIPCHandler.test.ts@@ -15,16 +15,29 @@ const t = trpc.initTRPC.create();const router = t.router({open: t.procedure.query(() => "ok"),secret: t.procedure.query(() => "secret"),+ ticks: t.procedure.subscription(async function* (opts) {+ let n = 0;+ while (!opts.signal?.aborted) {+ yield n++;+ await new Promise((resolve) => setTimeout(resolve, 1));+ }+ }),});+type WebContentsListener = (...args: unknown[]) => void;+function fakeWindow(id: number): {win: BrowserWindow;webContents: { id: number };+ emit: (event: string, ...args: unknown[]) => void;} {+ const listeners = new Map<string, WebContentsListener[]>();const webContents = {id,isDestroyed: () => false,- on: vi.fn(),+ on: vi.fn((event: string, listener: WebContentsListener) => {+ listeners.set(event, [...(listeners.get(event) ?? []), listener]);+ }),once: vi.fn(),};return {@@ -33,10 +46,17 @@ function fakeWindow(id: number): {webContents,} as unknown as BrowserWindow,webContents,+ emit: (event, ...args) => {+ for (const listener of listeners.get(event) ?? []) listener(...args);+ },};}-function requestFor(path: string, id: number) {+function requestFor(+ path: string,+ id: number,+ type: "query" | "subscription" = "query",+) {return {method: "request" as const,operation: {@@ -44,16 +64,24 @@ function requestFor(path: string, id: number) {id,input: undefined,path,- type: "query" as const,+ type,signal: undefined,},};}-function eventFrom(webContents: unknown) {+function replyTypes(reply: ReturnType<typeof vi.fn>): string[] {+ return reply.mock.calls.map(+ ([, message]) =>+ (message as { result?: { type?: string } }).result?.type ?? "error",+ );+}++function eventFrom(webContents: unknown, frameRoutingId?: number) {return {sender: webContents,- senderFrame: undefined,+ senderFrame:+ frameRoutingId === undefined ? undefined : { routingId: frameRoutingId },reply: vi.fn(),};}@@ -105,3 +133,84 @@ describe("createIPCHandler sender gating", () => {expect(mainEvent.reply).toHaveBeenCalled();});});++const MAIN_FRAME_ROUTING_ID = 1;++describe("createIPCHandler navigation cleanup", () => {+ test("a navigation that never commits leaves live subscriptions streaming", async () => {+ const { win, webContents, emit } = fakeWindow(1);+ createIPCHandler({ router, windows: [win] });++ const event = eventFrom(webContents, MAIN_FRAME_ROUTING_ID);+ ipcMain.emit(+ ELECTRON_TRPC_CHANNEL,+ event,+ requestFor("ticks", 1, "subscription"),+ );+ await vi.waitFor(() =>+ expect(replyTypes(event.reply)).toEqual(+ expect.arrayContaining(["started", "data"]),+ ),+ );++ // The renderer tried to leave (an external link); will-navigate cancelled+ // it after did-start-navigation had already fired.+ emit("did-start-navigation", {+ isMainFrame: true,+ isSameDocument: false,+ url: "https://example.com/",+ frame: { routingId: MAIN_FRAME_ROUTING_ID },+ });+ const before = event.reply.mock.calls.length;+ await vi.waitFor(() =>+ expect(event.reply.mock.calls.length).toBeGreaterThan(before),+ );+ expect(replyTypes(event.reply)).not.toContain("stopped");+ });++ test.each([+ { frame: "main frame", isMainFrame: true, aborted: 1 },+ { frame: "subframe", isMainFrame: false, aborted: 0 },+ ])(+ "a committed $frame navigation aborts $aborted in-flight operations",+ async ({ isMainFrame, aborted }) => {+ const { win, webContents, emit } = fakeWindow(1);+ const onNavigationCleanup = vi.fn();+ createIPCHandler({ router, windows: [win], onNavigationCleanup });++ const event = eventFrom(webContents, MAIN_FRAME_ROUTING_ID);+ ipcMain.emit(+ ELECTRON_TRPC_CHANNEL,+ event,+ requestFor("ticks", 1, "subscription"),+ );+ await vi.waitFor(() => expect(replyTypes(event.reply)).toContain("data"));++ emit(+ "did-frame-navigate",+ {},+ "file:///app/index.html",+ 200,+ "OK",+ isMainFrame,+ 4,+ isMainFrame ? MAIN_FRAME_ROUTING_ID + 7 : 12,+ );+ await flush();++ if (aborted > 0) {+ await vi.waitFor(() =>+ expect(replyTypes(event.reply)).toContain("stopped"),+ );+ expect(onNavigationCleanup).toHaveBeenCalledWith({+ webContentsId: 1,+ url: "file:///app/index.html",+ aborted,+ });+ } else {+ expect(replyTypes(event.reply)).not.toContain("stopped");+ expect(onNavigationCleanup).not.toHaveBeenCalled();+ }+ },+ );+});diff --git a/products/desktop/packages/electron-trpc/src/main/createIPCHandler.ts b/products/desktop/packages/electron-trpc/src/main/createIPCHandler.tsindex 123eef125868..b6bd9405238b 100644--- a/products/desktop/packages/electron-trpc/src/main/createIPCHandler.ts+++ b/products/desktop/packages/electron-trpc/src/main/createIPCHandler.ts@@ -25,17 +25,28 @@ export interface AttachWindowOptions {allowedPaths?: (path: string) => boolean;}+export interface NavigationCleanup {+ webContentsId: number;+ url: string;+ /** In-flight operations (queries, mutations, subscriptions) aborted. */+ aborted: number;+}++export type OnNavigationCleanup = (cleanup: NavigationCleanup) => void;+class IPCHandler<TRouter extends AnyTRPCRouter> {#windows: BrowserWindow[] = [];#pathFilters: Map<number, (path: string) => boolean> = new Map();#operations: Map<string, AbortController> = new Map();#listener: (event: IpcMainEvent, request: ETRPCRequest) => void;+ #onNavigationCleanup: OnNavigationCleanup | undefined;constructor({createContext,router,windows = [],onError,+ onNavigationCleanup,}: {createContext?: (opts: CreateContextOptions,@@ -43,7 +54,9 @@ class IPCHandler<TRouter extends AnyTRPCRouter> {router: TRouter;windows?: BrowserWindow[];onError?: OnProcedureError;+ onNavigationCleanup?: OnNavigationCleanup;}) {+ this.#onNavigationCleanup = onNavigationCleanup;for (const win of windows) {this.attachWindow(win);}@@ -122,31 +135,38 @@ class IPCHandler<TRouter extends AnyTRPCRouter> {});}- #cleanUpSubscriptions({- webContentsId,- frameRoutingId,- }: {- webContentsId: number;- frameRoutingId?: number;- }) {+ #cleanUpSubscriptions({ webContentsId }: { webContentsId: number }): number {+ let aborted = 0;for (const [key, sub] of this.#operations.entries()) {- if (key.startsWith(`${webContentsId}-${frameRoutingId ?? ""}`)) {+ if (key.startsWith(`${webContentsId}-`)) {sub.abort();this.#operations.delete(key);+ aborted += 1;}}+ return aborted;}+ // Operations belong to the document that issued them, so they are torn down+ // once a main-frame navigation has committed and that document is gone. The+ // commit fires before the new document can send its first request, so+ // sweeping every operation of the webContents here never touches the new+ // document's work. Sweeping earlier, on `did-start-navigation`, is wrong:+ // that fires before `will-navigate`, so a navigation the app cancels there+ // (an external link opened in the browser) would still abort every live+ // subscription while the document stays on screen, with no error the+ // renderer could react to. Subframes never issue operations, so their+ // navigations need no cleanup.#attachSubscriptionCleanupHandlers(win: BrowserWindow) {const webContentsId = win.webContents.id;- win.webContents.on("did-start-navigation", ({ isSameDocument, frame }) => {- if (!isSameDocument && frame) {- this.#cleanUpSubscriptions({- webContentsId: webContentsId,- frameRoutingId: frame.routingId,- });- }- });+ win.webContents.on(+ "did-frame-navigate",+ (_event, url, _httpResponseCode, _httpStatusText, isMainFrame) => {+ if (!isMainFrame) return;+ const aborted = this.#cleanUpSubscriptions({ webContentsId });+ this.#onNavigationCleanup?.({ webContentsId, url, aborted });+ },+ );win.webContents.on("destroyed", () => {this.detachWindow(win, webContentsId);});@@ -160,6 +180,7 @@ export const createIPCHandler = <TRouter extends AnyTRPCRouter>({router,windows = [],onError,+ onNavigationCleanup,}: {createContext?: (opts: CreateContextOptions,@@ -167,10 +188,17 @@ export const createIPCHandler = <TRouter extends AnyTRPCRouter>({router: TRouter;windows?: Electron.BrowserWindow[];onError?: OnProcedureError;+ onNavigationCleanup?: OnNavigationCleanup;}) => {if (currentHandler) {currentHandler.destroy();}- currentHandler = new IPCHandler({ createContext, router, windows, onError });+ currentHandler = new IPCHandler({+ createContext,+ router,+ windows,+ onError,+ onNavigationCleanup,+ });return currentHandler;};diff --git a/products/desktop/packages/host-router/src/routers/agent.router.ts b/products/desktop/packages/host-router/src/routers/agent.router.tsindex 1b1e32163d3c..4c85c6158c3d 100644--- a/products/desktop/packages/host-router/src/routers/agent.router.ts+++ b/products/desktop/packages/host-router/src/routers/agent.router.ts@@ -90,19 +90,11 @@ export const agentRouter = router({onSessionEvent: publicProcedure.input(subscribeSessionInput)- .subscription(async function* (opts) {- const service = opts.ctx.container.get<AgentService>(AGENT_SERVICE);- const targetTaskRunId = opts.input.taskRunId;- const iterable = service.toIterable(AgentServiceEvent.SessionEvent, {- signal: opts.signal,- });-- for await (const event of iterable) {- if (event.taskRunId === targetTaskRunId) {- yield event.payload;- }- }- }),+ .subscription((opts) =>+ opts.ctx.container+ .get<AgentService>(AGENT_SERVICE)+ .subscribeSessionEvents(opts.input.taskRunId, opts.signal),+ ),onPermissionRequest: publicProcedure.input(subscribeSessionInput)diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.test.tsindex e30eed1ea00d..2d5cd438aba5 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.test.ts@@ -742,6 +742,98 @@ describe("AgentService", () => {});});+ describe("session event subscriptions", () => {+ function serviceLog(svc: AgentService) {+ return (+ svc as unknown as {+ log: {+ info: ReturnType<typeof vi.fn>;+ warn: ReturnType<typeof vi.fn>;+ };+ }+ ).log;+ }++ function seedPendingSession(svc: AgentService, taskRunId: string) {+ (svc as unknown as { sessions: Map<string, unknown> }).sessions.set(+ taskRunId,+ { taskRunId, taskId: `task-for-${taskRunId}`, promptPending: true },+ );+ }++ function warnIfNoRendererListening(svc: AgentService, taskRunId: string) {+ (+ svc as unknown as { warnIfNoRendererListening(id: string): void }+ ).warnIfNoRendererListening(taskRunId);+ }++ it("delivers only the subscribed run's events and reports the close", async () => {+ const controller = new AbortController();+ const received: unknown[] = [];+ const consumed = (async () => {+ for await (const payload of service.subscribeSessionEvents(+ "run-1",+ controller.signal,+ )) {+ received.push(payload);+ }+ })();++ service.emit(AgentServiceEvent.SessionEvent, {+ taskRunId: "run-2",+ payload: "other",+ });+ service.emit(AgentServiceEvent.SessionEvent, {+ taskRunId: "run-1",+ payload: "mine",+ });+ controller.abort();+ await consumed;++ expect(received).toEqual(["mine"]);+ expect(serviceLog(service).info).toHaveBeenCalledWith(+ "Renderer session event subscription closed",+ expect.objectContaining({+ taskRunId: "run-1",+ delivered: 1,+ remainingSubscribers: 0,+ }),+ );+ });++ it("warns once a minute when a pending turn streams with nobody subscribed", () => {+ seedPendingSession(service, "run-1");++ warnIfNoRendererListening(service, "run-1");+ warnIfNoRendererListening(service, "run-1");++ expect(serviceLog(service).warn).toHaveBeenCalledTimes(1);+ expect(serviceLog(service).warn).toHaveBeenCalledWith(+ "Session events emitted while a prompt is pending but no renderer is subscribed",+ { taskRunId: "run-1", taskId: "task-for-run-1" },+ );+ });++ it("stays quiet while a renderer is subscribed", () => {+ seedPendingSession(service, "run-1");+ const controller = new AbortController();+ const consumed = (async () => {+ for await (const _ of service.subscribeSessionEvents(+ "run-1",+ controller.signal,+ )) {+ // drain+ }+ })();++ warnIfNoRendererListening(service, "run-1");+ controller.abort();++ expect(serviceLog(service).warn).not.toHaveBeenCalled();+ return consumed;+ });+ });+describe("idle timeout", () => {function injectSession(svc: AgentService,diff --git a/products/desktop/packages/workspace-server/src/services/agent/agent.ts b/products/desktop/packages/workspace-server/src/services/agent/agent.tsindex b6745de4c019..5f375b217685 100644--- a/products/desktop/packages/workspace-server/src/services/agent/agent.ts+++ b/products/desktop/packages/workspace-server/src/services/agent/agent.ts@@ -308,6 +308,9 @@ function extractSteeringCapability(init: unknown): string | undefined {return typeof steering === "string" ? steering : undefined;}+/** A streaming turn emits many events a second; warn once a minute, not per event. */+const NO_LISTENER_WARN_INTERVAL_MS = 60_000;+interface ManagedSession {taskRunId: string;taskId: string;@@ -393,6 +396,9 @@ export class AgentService extends TypedEventEmitter<AgentServiceEvents> {private sessions = new Map<string, ManagedSession>();private pendingPermissions = new Map<string, PendingPermission>();+ /** Live renderer session-event subscriptions per taskRunId. */+ private sessionEventSubscribers = new Map<string, number>();+ private lastNoListenerWarnAt = new Map<string, number>();private idleTimeouts = new Map<string,{ handle: ReturnType<typeof setTimeout>; deadline: number }@@ -1759,6 +1765,7 @@ For git operations while detached:);this.sessions.delete(taskRunId);+ this.lastNoListenerWarnAt.delete(taskRunId);const timeout = this.idleTimeouts.get(taskRunId);if (timeout) {@@ -1775,6 +1782,63 @@ For git operations while detached:}}+ /**+ * Streams a run's session events to one renderer subscriber. Tracks the+ * subscriber count per run so a turn that streams with nobody listening+ * (a dead renderer subscription) shows up in the log instead of only as a+ * transcript that never updates.+ */+ async *subscribeSessionEvents(+ taskRunId: string,+ signal?: AbortSignal,+ ): AsyncIterable<unknown> {+ this.sessionEventSubscribers.set(+ taskRunId,+ (this.sessionEventSubscribers.get(taskRunId) ?? 0) + 1,+ );+ const startedAt = Date.now();+ let delivered = 0;+ this.log.info("Renderer subscribed to session events", { taskRunId });+ try {+ for await (const event of this.toIterable(+ AgentServiceEvent.SessionEvent,+ { signal },+ )) {+ if (event.taskRunId !== taskRunId) continue;+ delivered += 1;+ yield event.payload;+ }+ } finally {+ const remaining = (this.sessionEventSubscribers.get(taskRunId) ?? 1) - 1;+ if (remaining > 0) {+ this.sessionEventSubscribers.set(taskRunId, remaining);+ } else {+ this.sessionEventSubscribers.delete(taskRunId);+ }+ this.log.info("Renderer session event subscription closed", {+ taskRunId,+ delivered,+ durationMs: Date.now() - startedAt,+ remainingSubscribers: Math.max(remaining, 0),+ promptPending: this.sessions.get(taskRunId)?.promptPending ?? false,+ });+ }+ }++ private warnIfNoRendererListening(taskRunId: string): void {+ if (this.sessionEventSubscribers.has(taskRunId)) return;+ const session = this.sessions.get(taskRunId);+ if (!session?.promptPending) return;+ const now = Date.now();+ const lastWarnedAt = this.lastNoListenerWarnAt.get(taskRunId) ?? 0;+ if (now - lastWarnedAt < NO_LISTENER_WARN_INTERVAL_MS) return;+ this.lastNoListenerWarnAt.set(taskRunId, now);+ this.log.warn(+ "Session events emitted while a prompt is pending but no renderer is subscribed",+ { taskRunId, taskId: session.taskId },+ );+ }+private createClientConnection(taskRunId: string,_channel: string,@@ -1789,6 +1853,7 @@ For git operations while detached:taskRunId,payload,});+ this.warnIfNoRendererListening(taskRunId);};const onAcpMessage = (message: unknown) => {diff --git a/products/desktop/packages/workspace-server/src/services/mcp-relay/mcp-relay.test.ts b/products/desktop/packages/workspace-server/src/services/mcp-relay/mcp-relay.test.tsindex 8e6e2cd37dcc..565c98c49737 100644--- a/products/desktop/packages/workspace-server/src/services/mcp-relay/mcp-relay.test.ts+++ b/products/desktop/packages/workspace-server/src/services/mcp-relay/mcp-relay.test.ts@@ -44,7 +44,10 @@ class TestMcpRelayService extends McpRelayServiceImpl {transports: FakeTransport[] = [];factoryCalls = 0;failNextStart = false;- protected override responseTimeoutMs = 25;+ // Generous by default: every test that responds does so after an await, so a+ // short timeout here races the real clock on a loaded runner. Only the test+ // that asserts the timeout path shortens it.+ override responseTimeoutMs = 30_000;constructor() {super(fakeLogger);@@ -276,6 +279,7 @@ describe("McpRelayServiceImpl", () => {it("resolves with -32001 when the server never responds", async () => {const service = makeService("srv");+ service.responseTimeoutMs = 25;const execution = await service.execute("run-1", "srv", {jsonrpc: "2.0",