: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): show what the claude cli did before a startup timeout (#107463)
Charles Vienae7a3d2387c6
diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.resume-model.test.tsindex 7c2af131b8dd..0aa1fb4f9e58 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.resume-model.test.ts@@ -539,13 +539,23 @@ describe("ClaudeAcpAgent session creation", () => {});await vi.advanceTimersByTimeAsync(30_001);+ const silentCli = {+ lines: 0,+ hasPartialLine: false,+ msSinceLastLine: null,+ lastMessageType: null,+ };await expect(promise).rejects.toBeInstanceOf(RequestError);+ await expect(promise).rejects.toMatchObject({+ data: expect.objectContaining({ cliOutput: silentCli }),+ });expect(createdQueries[0]?.close).toHaveBeenCalledTimes(1);expect(errorSpy).toHaveBeenCalledWith(log,expect.objectContaining({initializationPhase: "sdk_initialization",timeoutMs: 30_000,+ cliOutput: silentCli,initMs: expect.any(Number),requestedModel: "claude-opus-5",gatewayConfigured: false,diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.tsindex 631ea0f714ea..e5c3431b571b 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts@@ -127,7 +127,10 @@ import {RunBudgetGuard,} from "./session/budget-guard";import { getAvailableSlashCommands } from "./session/commands";-import { SessionInitialization } from "./session/initialization";+import {+ type CliOutputSummary,+ SessionInitialization,+} from "./session/initialization";import { getSessionJsonlPath } from "./session/jsonl-hydration";import { parseMcpServers } from "./session/mcp-config";import {@@ -3270,15 +3273,17 @@ export class ClaudeAcpAgent extends BaseAcpAgent {if (isResume) {const resumeStartedAt = Date.now();+ let cliOutput: CliOutputSummary | undefined;// Resume must block on initialization to validate the session is still alive.// For stale sessions this throws (e.g. "No conversation found").try {const result = await initialization.wait(q.initializationResult());if (result.result === "timeout") {+ cliOutput = result.cliOutput;throw new RequestError(-32603,`Session ${result.phase === "setup_hooks" ? "setup hooks" : forkSession ? "fork" : "resumption"} timed out after ${result.timeoutMs}ms`,- { sessionId, taskId, taskRunId: meta?.taskRunId },+ { sessionId, taskId, taskRunId: meta?.taskRunId, cliOutput },);}session.knownSlashCommands = collectKnownSlashCommands(@@ -3310,6 +3315,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {taskRunId: meta?.taskRunId,initializationPhase: initialization.phase,timeoutMs: initialization.timeoutMs,+ cliOutput: cliOutput ?? null,initMs: Date.now() - resumeStartedAt,transcriptBytes,requestedModel: requestedModel ?? null,@@ -3362,15 +3368,17 @@ export class ClaudeAcpAgent extends BaseAcpAgent {if (initPromise) {let initializationPhase = initialization.phase;let timeoutMs = SESSION_VALIDATION_TIMEOUT_MS;+ let cliOutput: CliOutputSummary | undefined;try {const initResult = await initPromise;if (initResult.result === "timeout") {initializationPhase = initResult.phase;timeoutMs = initResult.timeoutMs;+ cliOutput = initResult.cliOutput;throw new RequestError(-32603,`Session ${initializationPhase === "setup_hooks" ? "setup hooks" : "initialization"} timed out after ${timeoutMs}ms`,- { sessionId, taskId, taskRunId: meta?.taskRunId },+ { sessionId, taskId, taskRunId: meta?.taskRunId, cliOutput },);}session.knownSlashCommands = collectKnownSlashCommands(@@ -3396,6 +3404,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {taskRunId: meta?.taskRunId,initializationPhase,timeoutMs,+ cliOutput: cliOutput ?? null,modelConfigMs,initMs,requestedModel: requestedModel ?? null,diff --git a/products/desktop/packages/agent/src/adapters/claude/session/initialization.test.ts b/products/desktop/packages/agent/src/adapters/claude/session/initialization.test.tsindex a8b929c85707..d5b6049734c3 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/initialization.test.ts+++ b/products/desktop/packages/agent/src/adapters/claude/session/initialization.test.ts@@ -48,7 +48,7 @@ describe("SessionInitialization", () => {expect(vi.getTimerCount()).toBe(0);});- it.each(["no hooks", "hooks complete", "hooks still running"])(+ it.each(["no hooks", "hooks complete", "hooks still running"] as const)("bounds stalled initialization with %s",async (scenario) => {const stdout = new PassThrough();@@ -69,11 +69,41 @@ describe("SessionInitialization", () => {result: "timeout",phase: hooksRunning ? "setup_hooks" : "sdk_initialization",timeoutMs,+ cliOutput: {+ lines: {+ "no hooks": 1,+ "hooks complete": 3,+ "hooks still running": 2,+ }[scenario],+ hasPartialLine: false,+ msSinceLastLine: 1,+ lastMessageType: "system/hook_progress",+ },});expect(stdout.listenerCount("data")).toBe(0);},);+ it("reports partial output and bounds message type labels", async () => {+ const stdout = new PassThrough();+ const monitor = new SessionInitialization(vi.fn());+ monitor.observe(stdout);+ const result = monitor.wait(new Promise<never>(() => {}));+ stdout.write(`${JSON.stringify({ type: "x".repeat(150) })}\npartial`);++ await vi.advanceTimersByTimeAsync(30_000);++ await expect(result).resolves.toMatchObject({+ result: "timeout",+ cliOutput: {+ lines: 1,+ hasPartialLine: true,+ msSinceLastLine: 30_000,+ lastMessageType: "x".repeat(100),+ },+ });+ });+it("waits for all concurrent hooks and ignores oversized unrelated output", async () => {const stdout = new PassThrough();const monitor = new SessionInitialization(vi.fn());diff --git a/products/desktop/packages/agent/src/adapters/claude/session/initialization.ts b/products/desktop/packages/agent/src/adapters/claude/session/initialization.tsindex 78fdbf8d3d59..e63875df0005 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/initialization.ts+++ b/products/desktop/packages/agent/src/adapters/claude/session/initialization.ts@@ -3,19 +3,32 @@ import { StringDecoder } from "node:string_decoder";type InitializationPhase = "sdk_initialization" | "setup_hooks";+export interface CliOutputSummary {+ lines: number;+ hasPartialLine: boolean;+ msSinceLastLine: number | null;+ lastMessageType: string | null;+}+type InitializationResult<Value> =| { result: "success"; value: Value }| {result: "timeout";phase: InitializationPhase;timeoutMs: number;+ cliOutput: CliOutputSummary;};const MAX_OBSERVED_LINE_LENGTH = 256 * 1024;+const MAX_MESSAGE_TYPE_LENGTH = 100;export class SessionInitialization {private activeHooks = new Set<string>();private hooksStartedAt: number | undefined;+ private outputLines = 0;+ private hasPartialLine = false;+ private lastLineAt: number | undefined;+ private lastMessageType: string | null = null;private reschedule: (() => void) | undefined;private detach: (() => void) | undefined;private disposed = false;@@ -51,11 +64,14 @@ export class SessionInitialization {}if (!oversized) buffer += part;if (index < parts.length - 1) {+ this.outputLines++;+ this.lastLineAt = Date.now();if (!oversized) this.observeLine(buffer);buffer = "";oversized = false;}}+ this.hasPartialLine = oversized || buffer.length > 0;};stdout.on("data", onData);this.detach = () => stdout.off("data", onData);@@ -68,6 +84,18 @@ export class SessionInitialization {} catch {return;}+ if (+ message &&+ typeof message === "object" &&+ "type" in message &&+ typeof message.type === "string"+ ) {+ const messageType =+ "subtype" in message && typeof message.subtype === "string"+ ? `${message.type}/${message.subtype}`+ : message.type;+ this.lastMessageType = messageType.slice(0, MAX_MESSAGE_TYPE_LENGTH);+ }if (!message ||typeof message !== "object" ||@@ -94,6 +122,16 @@ export class SessionInitialization {}}+ private cliOutput(): CliOutputSummary {+ return {+ lines: this.outputLines,+ hasPartialLine: this.hasPartialLine,+ msSinceLastLine:+ this.lastLineAt === undefined ? null : Date.now() - this.lastLineAt,+ lastMessageType: this.lastMessageType,+ };+ }+async wait<Value>(initialization: Promise<Value>,): Promise<InitializationResult<Value>> {@@ -110,7 +148,13 @@ export class SessionInitialization {? timeoutMs - (Date.now() - (this.hooksStartedAt ?? Date.now())): timeoutMs;timer = setTimeout(- () => resolve({ result: "timeout", phase, timeoutMs }),+ () =>+ resolve({+ result: "timeout",+ phase,+ timeoutMs,+ cliOutput: this.cliOutput(),+ }),Math.max(0, remainingMs),);};