: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): delay repeated session connection notices (#99819)
Paul D'Ambra54f2ce152148
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 782037bfdabf..f4cd6b96e02f 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -1765,6 +1765,11 @@ export function classifyTurnEventKind(export class SessionService {private connectingTasks = new Map<string, Promise<void>>();+ private connectingToastTimers = new Map<+ string,+ { startedAt: number; timer: ReturnType<typeof setTimeout> }+ >();+ private shownConnectingToastSessions = new Map<string, number>();private reconcilingTasks = new Set<string>();private reconcileSkipLogged = new Set<string>();private taskCreationMarks = new Map<string, number>();@@ -2251,6 +2256,11 @@ export class SessionService {}if (previous) {+ // A fast-painted connecting session can be replaced before reconnect finishes.+ // Keep its timestamp so the delayed notice stays attached to this attempt.+ if (previous.status === "connecting") {+ session.startedAt = previous.startedAt;+ }session.optimisticItems = previous.optimisticItems;session.messageQueue = previous.messageQueue;// Keep the in-place edit hold with the queue it guards: dropping it here@@ -2422,6 +2432,7 @@ export class SessionService {),);}+ this.flushQueuedMessagesIfIdle(taskId);return true;} else {this.d.log.warn("Reconnect returned null", { taskId, taskRunId });@@ -3313,6 +3324,11 @@ export class SessionService {}for (const timer of this.eventEvictionTimers.values()) clearTimeout(timer);this.eventEvictionTimers.clear();+ for (const { timer } of this.connectingToastTimers.values()) {+ clearTimeout(timer);+ }+ this.connectingToastTimers.clear();+ this.shownConnectingToastSessions.clear();this.evictedRunIds.clear();this.residentBackgroundRunIds.clear();this.connectingTasks.clear();@@ -4230,9 +4246,15 @@ export class SessionService {);}if (session.status === "connecting") {- throw new Error(- "Session is still connecting. Please wait and try again.",- );+ const promptText = extractPromptText(prompt);+ this.d.store.enqueueMessage(taskId, promptText, prompt);+ this.scheduleConnectingToast(session.taskId, session.startedAt);+ this.d.log.info("Message queued", {+ taskId,+ queueLength: session.messageQueue.length + 1,+ reason: "connecting",+ });+ return { stopReason: "queued" };}throw new Error(`Session is not ready (status: ${session.status})`);}@@ -4302,6 +4324,40 @@ export class SessionService {});}+ private scheduleConnectingToast(taskId: string, startedAt: number): void {+ if (this.shownConnectingToastSessions.get(taskId) === startedAt) return;++ const existing = this.connectingToastTimers.get(taskId);+ if (existing?.startedAt === startedAt) return;+ if (existing) clearTimeout(existing.timer);++ const delay = Math.max(0, startedAt + 20_000 - Date.now());+ if (delay === 0) {+ this.showConnectingToast(taskId, startedAt);+ return;+ }++ const timer = setTimeout(() => {+ this.connectingToastTimers.delete(taskId);+ const session = this.d.store.getSessionByTaskId(taskId);+ if (session?.status !== "connecting") return;+ // A resume repaints the session and gives the replacement a fresh+ // `startedAt`, so the session connecting now is rarely the one this timer+ // was armed against. Follow that session and wait out the rest of its own+ // delay, rather than dropping the notice the wait was measured for.+ this.scheduleConnectingToast(taskId, session.startedAt);+ }, delay);+ this.connectingToastTimers.set(taskId, { startedAt, timer });+ }++ private showConnectingToast(taskId: string, startedAt: number): void {+ if (this.shownConnectingToastSessions.get(taskId) === startedAt) return;+ this.shownConnectingToastSessions.set(taskId, startedAt);+ this.d.toast.error("Session is still connecting.", {+ id: `session-connecting-${taskId}-${startedAt}`,+ });+ }+/*** Whether the turn a steer was aimed at is still the one running. `taskId`* outlives any single turn, so it cannot answer this on its own: a turn thatdiff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex ec04a6d29c7c..6ce76d97bb80 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -7084,15 +7084,111 @@ describe("SessionService", () => {);});- it("throws when session is connecting", async () => {+ it("queues message when session is connecting", async () => {+ vi.useFakeTimers();const service = getSessionService();- mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(- createMockSession({ status: "connecting" }),- );+ try {+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(+ createMockSession({ status: "connecting" }),+ );+ const prompt: ContentBlock[] = [{ type: "text", text: "Hello" }];- await expect(service.sendPrompt("task-123", "Hello")).rejects.toThrow(- "Session is still connecting",- );+ const result = await service.sendPrompt("task-123", prompt);++ expect(result.stopReason).toBe("queued");+ expect(mockSessionStoreSetters.enqueueMessage).toHaveBeenCalledWith(+ "task-123",+ "text",+ prompt,+ );+ } finally {+ service.reset();+ vi.useRealTimers();+ }+ });++ it("shows one connecting notice after 20 seconds for each session", async () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date("2026-09-13T00:00:00Z"));+ const service = getSessionService();+ const session = createMockSession({+ status: "connecting",+ startedAt: Date.now(),+ });+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);++ await expect(service.sendPrompt("task-123", "Hello")).resolves.toEqual({+ stopReason: "queued",+ });+ await expect(service.sendPrompt("task-123", "Hello")).resolves.toEqual({+ stopReason: "queued",+ });++ expect(mockToast.error).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(20_000);+ expect(mockToast.error).toHaveBeenCalledOnce();++ session.startedAt = Date.now();+ await expect(service.sendPrompt("task-123", "Hello")).resolves.toEqual({+ stopReason: "queued",+ });+ await vi.advanceTimersByTimeAsync(20_000);+ expect(mockToast.error).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it("keeps a queued prompt without showing a notice when the session connects", async () => {+ vi.useFakeTimers();+ const service = getSessionService();+ try {+ vi.setSystemTime(new Date("2026-09-13T00:00:00Z"));+ const session = createMockSession({+ status: "connecting",+ startedAt: Date.now(),+ });+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);++ await expect(service.sendPrompt("task-123", "Hello")).resolves.toEqual({+ stopReason: "queued",+ });+ session.status = "connected";++ await vi.advanceTimersByTimeAsync(20_000);++ expect(mockToast.error).not.toHaveBeenCalled();+ expect(mockSessionStoreSetters.enqueueMessage).toHaveBeenCalledWith(+ "task-123",+ "Hello",+ "Hello",+ );+ } finally {+ service.reset();+ vi.useRealTimers();+ }+ });++ it("cancels a pending connecting notice when the service resets", async () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date("2026-09-13T00:00:00Z"));+ const service = getSessionService();+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(+ createMockSession({ status: "connecting", startedAt: Date.now() }),+ );++ await expect(service.sendPrompt("task-123", "Hello")).resolves.toEqual({+ stopReason: "queued",+ });+ service.reset();+ await vi.advanceTimersByTimeAsync(20_000);++ expect(mockToast.error).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }});it("queues message when prompt is already pending", async () => {@@ -10365,6 +10461,95 @@ describe("SessionService", () => {expect(stored.editingQueuedId).toBe("q-1");});+ it("keeps a connecting notice timer when reconnect replaces the session", async () => {+ vi.useFakeTimers();+ const service = getSessionService();+ try {+ vi.setSystemTime(new Date("2026-09-13T00:00:00Z"));+ const startedAt = Date.now();+ const originalSession = createMockSession({+ status: "connecting",+ logUrl: "https://logs.example.com/run-123",+ startedAt,+ });+ let currentSession = originalSession;+ mockSessionStoreSetters.getSessionByTaskId.mockImplementation(+ () => currentSession,+ );+ mockSessionStoreSetters.getSessions.mockImplementation(() => ({+ "run-123": currentSession,+ }));+ mockSessionStoreSetters.setSession.mockImplementation(+ (session: AgentSession) => {+ currentSession = session;+ },+ );+ mockSessionStoreSetters.updateSession.mockImplementation(+ (_taskRunId, updates) => {+ currentSession = { ...currentSession, ...updates };+ },+ );+ const queuedMessage = {+ id: "q-1",+ content: "Hello",+ rawPrompt: "Hello",+ queuedAt: 1,+ };+ mockSessionStoreSetters.enqueueMessage.mockImplementation(() => {+ originalSession.messageQueue.push(queuedMessage);+ });+ mockSessionStoreSetters.dequeueMessages.mockReturnValue([+ queuedMessage,+ ]);+ mockTrpcWorkspace.verify.query.mockResolvedValue({ exists: true });+ mockTrpcLogs.readLocalLogs.query.mockResolvedValue("");+ mockTrpcAgent.prompt.mutate.mockResolvedValue({+ stopReason: "end_turn",+ });++ await expect(service.sendPrompt("task-123", "Hello")).resolves.toEqual({+ stopReason: "queued",+ });+ await vi.advanceTimersByTimeAsync(1_000);++ let resolveReconnect: (value: {+ sessionId: string;+ channel: string;+ configOptions: never[];+ }) => void = () => {};+ const reconnectResult = new Promise<{+ sessionId: string;+ channel: string;+ configOptions: never[];+ }>((resolve) => {+ resolveReconnect = resolve;+ });+ mockTrpcAgent.reconnect.mutate.mockReturnValue(reconnectResult);++ const reconnectPromise = service.clearSessionError("task-123", "/repo");+ await vi.advanceTimersByTimeAsync(19_000);++ expect(mockToast.error).toHaveBeenCalledOnce();+ expect(currentSession.startedAt).toBe(startedAt);++ resolveReconnect({+ sessionId: "run-123",+ channel: "agent-event:run-123",+ configOptions: [],+ });+ await reconnectPromise;+ await vi.advanceTimersByTimeAsync(1);++ expect(mockTrpcAgent.prompt.mutate).toHaveBeenCalledWith({+ sessionId: "run-123",+ prompt: [{ type: "text", text: "Hello" }],+ });+ } finally {+ service.reset();+ vi.useRealTimers();+ }+ });+it("creates fresh session when initialPrompt is set (prompt never delivered)", async () => {const service = getSessionService();const mockSession = createMockSession({