Skip to content

: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.

fix(desktop): auto-recover cloud task stream after subscription error (#83192)

Thomas Obermüller1e9231a924d1
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 12253645b9a4..c6d9ff3f8cf8 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -121,6 +121,19 @@ const LOCAL_SESSION_RECONNECT_BACKOFF = {
initialDelayMs: 1_000,
maxDelayMs: 5_000,
};
+const CLOUD_SUBSCRIPTION_RECOVERY_BACKOFF = {
+ initialDelayMs: 1_000,
+ maxDelayMs: 30_000,
+};
+/**
+ * Recovery keeps retrying past this point (a later attempt can still succeed,
+ * e.g. after the main process finishes restarting), but from here on the
+ * session shows the retryable error banner instead of stalling silently.
+ */
+const CLOUD_SUBSCRIPTION_RECOVERY_NOTIFY_ATTEMPTS = 3;
+const CLOUD_SUBSCRIPTION_ERROR_TITLE = "Stream connection lost";
+const CLOUD_SUBSCRIPTION_ERROR_MESSAGE =
+ "Lost connection to the cloud run. Reconnecting…";
const LOCAL_SESSION_RECOVERY_MESSAGE =
"Lost connection to the agent. Reconnecting…";
const LOCAL_SESSION_RECOVERY_FAILED_MESSAGE =
@@ -259,6 +272,14 @@ interface CloudTaskWatcher {
bufferedResumeUpdates: CloudTaskUpdatePayload[];
processCloudUpdate: (update: CloudTaskUpdatePayload) => void;
subscription: { unsubscribe: () => void };
+ /** Bumped on every attach, so a replaced subscription's late callbacks are ignored. */
+ subscriptionGeneration: number;
+ subscriptionRecoveryAttempts: number;
+ subscriptionRecoveryTimeoutId: ReturnType<typeof setTimeout> | null;
+ subscriptionRecoveryInFlight: boolean;
+ /** An error that arrived mid-recovery, retried once that recovery settles. */
+ subscriptionRecoveryQueued: boolean;
+ subscriptionErrorSurfaced: boolean;
onStatusChange?: () => void;
}
@@ -6333,38 +6354,23 @@ export class SessionService {
bufferedResumeUpdates: [],
processCloudUpdate,
subscription: { unsubscribe: () => undefined },
+ subscriptionGeneration: 0,
+ subscriptionRecoveryAttempts: 0,
+ subscriptionRecoveryTimeoutId: null,
+ subscriptionRecoveryInFlight: false,
+ subscriptionRecoveryQueued: false,
+ subscriptionErrorSurfaced: false,
onStatusChange,
};
this.cloudTaskWatchers.set(taskId, watcher);
// Subscribe before starting the main-process watcher so the first replayed
// SSE/log burst cannot race ahead of the renderer subscription.
- watcher.subscription = this.d.trpc.cloudTask.onUpdate.subscribe(
- { taskId, runId },
- {
- onData: (update: CloudTaskUpdatePayload) => {
- const activeWatcher = this.cloudTaskWatchers.get(taskId);
- if (!activeWatcher || activeWatcher.runId !== runId) {
- return;
- }
- if (activeWatcher.bufferResumeUpdates) {
- activeWatcher.bufferedResumeUpdates.push(update);
- return;
- }
- activeWatcher.processCloudUpdate(update);
- },
- 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 },
- );
- },
- },
+ watcher.subscription = this.attachCloudTaskSubscription(
+ taskId,
+ runId,
+ startToken,
+ watcher.subscriptionGeneration,
);
if (shouldHydrateSession) {
@@ -7056,6 +7062,213 @@ export class SessionService {
return watcher?.runId === runId && watcher.startToken === startToken;
}
+ private attachCloudTaskSubscription(
+ taskId: string,
+ runId: string,
+ startToken: number,
+ generation: number,
+ ): { unsubscribe: () => void } {
+ // Recovery replaces the subscription while the watcher stays current, so
+ // the generation is what tells a live handler from one belonging to the
+ // subscription we just discarded.
+ const isCurrentSubscription = () =>
+ this.isCurrentCloudTaskWatcher(taskId, runId, startToken) &&
+ this.cloudTaskWatchers.get(taskId)?.subscriptionGeneration === generation;
+
+ return this.d.trpc.cloudTask.onUpdate.subscribe(
+ { taskId, runId },
+ {
+ onData: (update: CloudTaskUpdatePayload) => {
+ const activeWatcher = this.cloudTaskWatchers.get(taskId);
+ if (!activeWatcher || activeWatcher.runId !== runId) {
+ return;
+ }
+ activeWatcher.subscriptionRecoveryAttempts = 0;
+ if (activeWatcher.bufferResumeUpdates) {
+ activeWatcher.bufferedResumeUpdates.push(update);
+ return;
+ }
+ activeWatcher.processCloudUpdate(update);
+ },
+ onError: (err: unknown) => {
+ if (!isCurrentSubscription()) return;
+ this.d.log.error("Cloud task subscription error", { taskId, err });
+ this.scheduleCloudSubscriptionRecovery(taskId, runId);
+ },
+ onComplete: () => {
+ if (!isCurrentSubscription()) return;
+ // A completion that passes the guard is host transport teardown
+ // (a committed navigation sweeping the transport's operations, not
+ // the run finishing — our own teardown deletes the watcher before
+ // unsubscribing): recover just like an error, or updates stop until
+ // an app reload.
+ this.d.log.warn("Cloud task subscription ended without an error", {
+ taskId,
+ runId,
+ });
+ this.scheduleCloudSubscriptionRecovery(taskId, runId);
+ },
+ },
+ );
+ }
+
+ /**
+ * The tRPC subscription carrying cloud updates died (an error in the host
+ * stream, or transport teardown). Without recovery the transcript silently
+ * stops advancing until an app reload rebuilds the subscription — none of
+ * the existing recovery triggers fire, because the session never reaches an
+ * error status. Rebuild both sides here: a fresh subscription, plus a watch
+ * call whose snapshot replay backfills whatever was missed while the
+ * channel was down (the dead subscription's server-side teardown may also
+ * have unwatched, and thereby stopped, the main-process watcher).
+ */
+ private scheduleCloudSubscriptionRecovery(
+ taskId: string,
+ runId: string,
+ ): void {
+ const watcher = this.cloudTaskWatchers.get(taskId);
+ if (!watcher || watcher.runId !== runId) return;
+ // A running recovery already rebuilds the subscription. Queue the failure
+ // for it to retry rather than starting a second, overlapping recovery: the
+ // main-process watcher is reference counted, so two watch calls against one
+ // teardown leave it running forever.
+ if (watcher.subscriptionRecoveryInFlight) {
+ watcher.subscriptionRecoveryQueued = true;
+ return;
+ }
+ if (watcher.subscriptionRecoveryTimeoutId) return;
+
+ const delay = getBackoffDelay(
+ watcher.subscriptionRecoveryAttempts,
+ CLOUD_SUBSCRIPTION_RECOVERY_BACKOFF,
+ );
+ watcher.subscriptionRecoveryTimeoutId = setTimeout(() => {
+ watcher.subscriptionRecoveryTimeoutId = null;
+ void this.recoverCloudSubscription(taskId, runId);
+ }, delay);
+ }
+
+ private async recoverCloudSubscription(
+ taskId: string,
+ runId: string,
+ ): Promise<void> {
+ const watcher = this.cloudTaskWatchers.get(taskId);
+ if (!watcher || watcher.runId !== runId) return;
+ const startToken = watcher.startToken;
+
+ watcher.subscriptionRecoveryAttempts += 1;
+ watcher.subscriptionRecoveryInFlight = true;
+ watcher.subscriptionRecoveryQueued = false;
+ // Bump the generation before unsubscribing: a transport that completes
+ // the old subscription synchronously on unsubscribe would otherwise pass
+ // the generation guard and queue a recovery against itself, forever.
+ watcher.subscriptionGeneration += 1;
+ watcher.subscription.unsubscribe();
+ watcher.subscription = this.attachCloudTaskSubscription(
+ taskId,
+ runId,
+ startToken,
+ watcher.subscriptionGeneration,
+ );
+
+ try {
+ await this.d.trpc.cloudTask.watch.mutate({
+ taskId,
+ runId,
+ apiHost: watcher.apiHost,
+ teamId: watcher.teamId,
+ resumeFromEntryCount: watcher.resumeFromEntryCount,
+ });
+
+ // Same compensation as the initial watch path: if teardown won while this
+ // watch request was in flight, the main-process watcher is now running
+ // with no renderer subscriber, so unwatch it.
+ if (!this.isCurrentCloudTaskWatcher(taskId, runId, startToken)) {
+ await this.d.trpc.cloudTask.unwatch.mutate({ taskId, runId });
+ return;
+ }
+
+ this.d.log.info("Cloud task subscription recovered", {
+ taskId,
+ attempts: watcher.subscriptionRecoveryAttempts,
+ });
+ this.clearCloudSubscriptionRecoveryError(taskId, runId);
+ } catch (err) {
+ if (!this.isCurrentCloudTaskWatcher(taskId, runId, startToken)) return;
+ this.d.log.warn("Cloud task subscription recovery failed", {
+ taskId,
+ attempt: watcher.subscriptionRecoveryAttempts,
+ err,
+ });
+ this.maybeSurfaceCloudSubscriptionError(taskId, runId);
+ watcher.subscriptionRecoveryQueued = true;
+ } finally {
+ watcher.subscriptionRecoveryInFlight = false;
+ // Either this attempt failed, or the rebuilt subscription died while the
+ // watch call was still in flight. Both mean the stream is still down.
+ if (
+ watcher.subscriptionRecoveryQueued &&
+ this.isCurrentCloudTaskWatcher(taskId, runId, startToken)
+ ) {
+ watcher.subscriptionRecoveryQueued = false;
+ this.scheduleCloudSubscriptionRecovery(taskId, runId);
+ }
+ }
+ }
+
+ private maybeSurfaceCloudSubscriptionError(
+ taskId: string,
+ runId: string,
+ ): void {
+ const watcher = this.cloudTaskWatchers.get(taskId);
+ if (!watcher || watcher.runId !== runId) return;
+ if (watcher.subscriptionErrorSurfaced) return;
+ if (
+ watcher.subscriptionRecoveryAttempts <
+ CLOUD_SUBSCRIPTION_RECOVERY_NOTIFY_ATTEMPTS
+ ) {
+ return;
+ }
+ const session = this.d.store.getSessions()[runId];
+ if (!session || session.status === "error") return;
+
+ watcher.subscriptionErrorSurfaced = true;
+ this.d.store.updateSession(runId, {
+ status: "error",
+ errorTitle: CLOUD_SUBSCRIPTION_ERROR_TITLE,
+ errorMessage: CLOUD_SUBSCRIPTION_ERROR_MESSAGE,
+ errorRetryable: true,
+ isPromptPending: false,
+ });
+ }
+
+ private clearCloudSubscriptionRecoveryError(
+ taskId: string,
+ runId: string,
+ ): void {
+ const watcher = this.cloudTaskWatchers.get(taskId);
+ if (!watcher || watcher.runId !== runId) return;
+ if (!watcher.subscriptionErrorSurfaced) return;
+
+ watcher.subscriptionErrorSurfaced = false;
+ const session = this.d.store.getSessions()[runId];
+ // Only clear the banner this recovery raised: a real task error can land
+ // (over the rebuilt subscription) before the watch call resolves, and
+ // wiping it would hide the actual failure.
+ if (
+ session?.status !== "error" ||
+ session.errorTitle !== CLOUD_SUBSCRIPTION_ERROR_TITLE
+ ) {
+ return;
+ }
+ this.d.store.updateSession(runId, {
+ status: "disconnected",
+ errorTitle: undefined,
+ errorMessage: undefined,
+ errorRetryable: undefined,
+ });
+ }
+
/**
* Fully stop a cloud task watcher. The tRPC subscription unwatches from the
* main process in its finally handler; the in-flight watch path below sends a
@@ -7066,6 +7279,10 @@ export class SessionService {
if (!watcher) return;
this.cloudTaskWatchers.delete(taskId);
+ if (watcher.subscriptionRecoveryTimeoutId) {
+ clearTimeout(watcher.subscriptionRecoveryTimeoutId);
+ watcher.subscriptionRecoveryTimeoutId = null;
+ }
watcher.subscription.unsubscribe();
this.cloudLogGapReconciler.forgetDeficiency(watcher.runId);
}
diff --git a/products/desktop/packages/core/src/sessions/sessionServiceCloudSubscriptionRecovery.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceCloudSubscriptionRecovery.test.ts
new file mode 100644
index 000000000000..2ea378604c8b
--- /dev/null
+++ b/products/desktop/packages/core/src/sessions/sessionServiceCloudSubscriptionRecovery.test.ts
@@ -0,0 +1,366 @@
+import type { AgentSession } from "@posthog/shared";
+import type { CloudTaskUpdatePayload } from "@posthog/shared/domain-types";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SessionService, type SessionServiceDeps } from "./sessionService";
+
+const TASK_ID = "task-1";
+const RUN_ID = "run-1";
+
+type SubscriptionHandlers = {
+ onData: (data: CloudTaskUpdatePayload) => void;
+ onError?: (err: unknown) => void;
+ onComplete?: () => void;
+};
+
+function makeSession(): AgentSession {
+ return {
+ taskRunId: RUN_ID,
+ taskId: TASK_ID,
+ taskTitle: "Test task",
+ channel: "",
+ events: [
+ {
+ type: "acp_message",
+ ts: 1,
+ message: { jsonrpc: "2.0", method: "noop" },
+ },
+ ],
+ processedLineCount: 1,
+ startedAt: 1,
+ status: "connected",
+ isPromptPending: false,
+ isCompacting: false,
+ promptStartedAt: null,
+ pendingPermissions: new Map(),
+ pausedDurationMs: 0,
+ messageQueue: [],
+ optimisticItems: [],
+ isCloud: true,
+ isTaskAuthor: true,
+ adapter: "claude",
+ cloudStatus: "in_progress",
+ };
+}
+
+function createHarness() {
+ const sessions: Record<string, AgentSession> = { [RUN_ID]: makeSession() };
+ const store = {
+ getSessions: () => sessions,
+ getSessionByTaskId: (taskId: string) =>
+ Object.values(sessions).find((s) => s.taskId === taskId),
+ setSession: vi.fn((session: AgentSession) => {
+ sessions[session.taskRunId] = session;
+ }),
+ updateSession: vi.fn(
+ (taskRunId: string, updates: Partial<AgentSession>) => {
+ const session = sessions[taskRunId];
+ if (session) Object.assign(session, updates);
+ },
+ ),
+ updateCloudStatus: vi.fn(),
+ appendEvents: vi.fn(),
+ clearTailOptimisticItems: vi.fn(),
+ clearMessageQueue: vi.fn(),
+ };
+
+ const subscriptions: Array<{
+ handlers: SubscriptionHandlers;
+ unsubscribe: ReturnType<typeof vi.fn>;
+ }> = [];
+ const subscribe = vi.fn((_input: unknown, handlers: SubscriptionHandlers) => {
+ // Model the worst-case transport, which completes the subscription
+ // synchronously when it is unsubscribed — no test may recover in a loop.
+ const unsubscribe = vi.fn(() => handlers.onComplete?.());
+ subscriptions.push({ handlers, unsubscribe });
+ return { unsubscribe };
+ });
+ const watchMutate = vi.fn().mockResolvedValue(undefined);
+ const unwatchMutate = vi.fn().mockResolvedValue(undefined);
+
+ const deps = {
+ store,
+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ getPersistedConfigOptions: () => undefined,
+ setPersistedConfigOptions: vi.fn(),
+ removePersistedConfigOptions: vi.fn(),
+ adapterStore: {
+ getAdapter: () => undefined,
+ setAdapter: vi.fn(),
+ removeAdapter: vi.fn(),
+ },
+ trpc: {
+ agent: {
+ getPreviewConfigOptions: {
+ query: vi.fn().mockRejectedValue(new Error("not in test")),
+ },
+ onSessionIdleKilled: {
+ subscribe: () => ({ unsubscribe: vi.fn() }),
+ },
+ },
+ cloudTask: {
+ onUpdate: { subscribe },
+ watch: { mutate: watchMutate },
+ unwatch: { mutate: unwatchMutate },
+ },
+ },
+ } as unknown as SessionServiceDeps;
+
+ const service = new SessionService(deps);
+ return {
+ service,
+ sessions,
+ store,
+ subscriptions,
+ watchMutate,
+ unwatchMutate,
+ };
+}
+
+function watchTask(service: SessionService) {
+ service.watchCloudTask(
+ TASK_ID,
+ RUN_ID,
+ "https://us.posthog.com",
+ 2,
+ undefined,
+ undefined,
+ undefined,
+ "claude",
+ undefined,
+ undefined,
+ undefined,
+ "in_progress",
+ );
+}
+
+async function flushMicrotasks() {
+ await vi.advanceTimersByTimeAsync(0);
+}
+
+describe("SessionService cloud subscription recovery", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("rebuilds the subscription and re-issues watch after a subscription error", async () => {
+ const { service, subscriptions, watchMutate } = createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+ expect(subscriptions).toHaveLength(1);
+ expect(watchMutate).toHaveBeenCalledTimes(1);
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(subscriptions[0].unsubscribe).toHaveBeenCalled();
+ expect(subscriptions).toHaveLength(2);
+ expect(watchMutate).toHaveBeenCalledTimes(2);
+ expect(watchMutate).toHaveBeenLastCalledWith({
+ taskId: TASK_ID,
+ runId: RUN_ID,
+ apiHost: "https://us.posthog.com",
+ teamId: 2,
+ resumeFromEntryCount: undefined,
+ });
+ });
+
+ it("recovers after the subscription completes without an error", async () => {
+ const { service, subscriptions, watchMutate } = createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+ expect(subscriptions).toHaveLength(1);
+ expect(watchMutate).toHaveBeenCalledTimes(1);
+
+ // Host transport teardown ends the subscription cleanly (no error).
+ subscriptions[0].handlers.onComplete?.();
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(subscriptions).toHaveLength(2);
+ expect(watchMutate).toHaveBeenCalledTimes(2);
+
+ // The recovery's own unsubscribe completes the old subscription; that
+ // must not schedule another recovery against the rebuilt one.
+ await vi.advanceTimersByTimeAsync(300_000);
+ expect(subscriptions).toHaveLength(2);
+ expect(watchMutate).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps retrying with backoff while the watch call fails", async () => {
+ const { service, subscriptions, watchMutate } = createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+ watchMutate.mockRejectedValue(new Error("main process unavailable"));
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(subscriptions).toHaveLength(2);
+
+ // Attempt counter is now 1, so the next retry waits 2s, not 1s.
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(subscriptions).toHaveLength(2);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(subscriptions).toHaveLength(3);
+ });
+
+ it("surfaces a retryable error after repeated failed recoveries and clears it on success", async () => {
+ const { service, sessions, subscriptions, watchMutate } = createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+ watchMutate.mockRejectedValue(new Error("main process unavailable"));
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ // Attempts 1 (1s), 2 (2s), 3 (4s) — banner appears on the third failure.
+ await vi.advanceTimersByTimeAsync(1_000 + 2_000);
+ expect(sessions[RUN_ID].status).not.toBe("error");
+ await vi.advanceTimersByTimeAsync(4_000);
+ expect(sessions[RUN_ID].status).toBe("error");
+ expect(sessions[RUN_ID].errorRetryable).toBe(true);
+
+ watchMutate.mockResolvedValue(undefined);
+ await vi.advanceTimersByTimeAsync(8_000);
+ expect(sessions[RUN_ID].status).toBe("disconnected");
+ expect(sessions[RUN_ID].errorTitle).toBeUndefined();
+ });
+
+ it("keeps a task error that lands while recovery is in flight", async () => {
+ const { service, sessions, store, subscriptions, watchMutate } =
+ createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+ watchMutate.mockRejectedValue(new Error("main process unavailable"));
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ await vi.advanceTimersByTimeAsync(1_000 + 2_000 + 4_000);
+ expect(sessions[RUN_ID].errorTitle).toBe("Stream connection lost");
+
+ store.updateSession(RUN_ID, {
+ status: "error",
+ errorTitle: "Task failed",
+ errorMessage: "The run crashed",
+ });
+ watchMutate.mockResolvedValue(undefined);
+ await vi.advanceTimersByTimeAsync(8_000);
+
+ expect(sessions[RUN_ID].status).toBe("error");
+ expect(sessions[RUN_ID].errorTitle).toBe("Task failed");
+ });
+
+ it("unwatches the main process when teardown wins the recovery race", async () => {
+ const { service, subscriptions, watchMutate, unwatchMutate } =
+ createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+
+ let resolveWatch = () => {};
+ watchMutate.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveWatch = () => resolve();
+ }),
+ );
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(watchMutate).toHaveBeenCalledTimes(2);
+
+ service.stopCloudTaskWatch(TASK_ID);
+ resolveWatch();
+ await flushMicrotasks();
+
+ expect(unwatchMutate).toHaveBeenCalledWith({
+ taskId: TASK_ID,
+ runId: RUN_ID,
+ });
+ });
+
+ it("stops recovering once the watch is torn down", async () => {
+ const { service, subscriptions, watchMutate } = createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ service.stopCloudTaskWatch(TASK_ID);
+ await vi.advanceTimersByTimeAsync(60_000);
+
+ expect(subscriptions).toHaveLength(1);
+ expect(watchMutate).toHaveBeenCalledTimes(1);
+ });
+
+ it("resets the backoff once data flows again", async () => {
+ const { service, subscriptions } = createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(subscriptions).toHaveLength(2);
+
+ subscriptions[1].handlers.onData({
+ taskId: TASK_ID,
+ runId: RUN_ID,
+ kind: "logs",
+ newEntries: [],
+ totalEntryCount: 1,
+ });
+
+ // A later error starts back at the initial delay instead of continuing
+ // the previous backoff sequence.
+ subscriptions[1].handlers.onError?.(new Error("stream died again"));
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(subscriptions).toHaveLength(3);
+ });
+
+ it("queues one retry instead of racing a second recovery", async () => {
+ const { service, subscriptions, watchMutate } = createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+
+ let resolveWatch = () => {};
+ watchMutate.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveWatch = () => resolve();
+ }),
+ );
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(subscriptions).toHaveLength(2);
+ expect(watchMutate).toHaveBeenCalledTimes(2);
+
+ // The rebuilt subscription dies while its watch call is still in flight.
+ // Recovering again now would leave the reference-counted main-process
+ // watcher with two watch calls against one teardown.
+ subscriptions[1].handlers.onError?.(new Error("stream died again"));
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(subscriptions).toHaveLength(2);
+ expect(watchMutate).toHaveBeenCalledTimes(2);
+
+ resolveWatch();
+ await flushMicrotasks();
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(subscriptions).toHaveLength(3);
+ expect(watchMutate).toHaveBeenCalledTimes(3);
+ });
+
+ it("ignores callbacks from a subscription recovery replaced", async () => {
+ const { service, subscriptions, watchMutate } = createHarness();
+ watchTask(service);
+ await flushMicrotasks();
+
+ subscriptions[0].handlers.onError?.(new Error("stream died"));
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(subscriptions).toHaveLength(2);
+
+ subscriptions[0].handlers.onError?.(new Error("late error"));
+ subscriptions[0].handlers.onComplete?.();
+ await vi.advanceTimersByTimeAsync(30_000);
+
+ expect(subscriptions).toHaveLength(2);
+ expect(watchMutate).toHaveBeenCalledTimes(2);
+ });
+});