: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): handle slow worktree setup without losing prompts (#96874)
Shy Alter0cf8e79cdcf2
diff --git a/products/desktop/apps/code/tests/e2e/tests/smoke.spec.ts b/products/desktop/apps/code/tests/e2e/tests/smoke.spec.tsindex 9ee0e5cf1db4..e960067ef0e8 100644--- a/products/desktop/apps/code/tests/e2e/tests/smoke.spec.ts+++ b/products/desktop/apps/code/tests/e2e/tests/smoke.spec.ts@@ -49,22 +49,21 @@ test.describe("Smoke Tests", () => {expect(isValidBootState).toBe(true);});- test("window has correct minimum dimensions", async ({ window }) => {- // The main process maximizes the window on ready-to-show, which can land- // after domcontentloaded. Poll so the assertion sees the final size, not- // the 600px outer frame the window opens with.- const bounds = () =>- window.evaluate(() => ({- width: window.innerWidth,- height: window.innerHeight,- }));+ test("window has correct minimum dimensions", async ({+ electronApp,+ window,+ }) => {+ const browserWindow = await electronApp.browserWindow(window);+ const { bounds, minimumSize } = await browserWindow.evaluate(+ (nativeWindow) => ({+ bounds: nativeWindow.getBounds(),+ minimumSize: nativeWindow.getMinimumSize(),+ }),+ );- await expect- .poll(async () => (await bounds()).width, { timeout: 10000 })- .toBeGreaterThanOrEqual(900);- await expect- .poll(async () => (await bounds()).height, { timeout: 10000 })- .toBeGreaterThanOrEqual(600);+ expect(minimumSize).toEqual([800, 600]);+ expect(bounds.width).toBeGreaterThanOrEqual(minimumSize[0]);+ expect(bounds.height).toBeGreaterThanOrEqual(minimumSize[1]);});test("app does not crash within 10 seconds of boot", async ({diff --git a/products/desktop/docs/ARCHITECTURE.md b/products/desktop/docs/ARCHITECTURE.mdindex 5c58515d5ab4..72d27146bd99 100644--- a/products/desktop/docs/ARCHITECTURE.md+++ b/products/desktop/docs/ARCHITECTURE.md@@ -46,6 +46,40 @@ The chat displays the submitted prompt with the current startup status untilinitialization ends and the transcript or error state takes over. The waitingmessage and composer use the same outer gutters and column width as the live chat.+Local startup retries retain the original prompt and run configuration after a+failure. A failed replacement keeps its session when available, or restores the+previous session with an error. A later retry can send the original prompt.+A retry without a session reports failure instead of successful recovery.++Claude initialization includes the repository's `SessionStart` hooks. These hooks+can prepare a new worktree and install dependencies before the SDK becomes ready.+An observed setup hook gets a separate, bounded wait of ten minutes. Startup with+no active setup hooks keeps its 30-second timeout. Hook progress does not extend+the hook deadline. Startup phase changes and failures use the desktop log path,+without recording hook commands or output. The renderer subscribes before starting+an agent, so it can show active setup hooks while `session/new` is still pending.+Startup subscriptions end on success or failure. Updates from an older run cannot+change the current run's startup phase. Startup events do not count as conversation+history during recovery.++Worktree creation shows its own preparation screen and setup output. Agent startup+shows one status line beside a spinner: "Starting local agent" or "Running+repository setup". The submitted prompt stays visible. Prompt retention is+normal behavior and needs no extra message. These are observed phases, not+estimated progress percentages.++Desktop does not disable repository hooks, change repository settings, or share+ignored dependency files between worktrees. Each worktree runs its configured+setup in its own directory. A new worktree can need setup that an existing+checkout has already completed. Setup time is not a connection failure while an+observed hook remains within its deadline. The same rule applies to ordinary+checkouts with slow hooks; it does not depend on a repository name or toolchain.++A connected local session only waits for its first prompt when the session still+has a prompt to send. A task description or an existing run does not imply that a+prompt is pending. This lets an empty session open after a failed startup instead+of keeping it in the loading view. Opening it does not resend the description.+New cloud runs seed the full user message before subscribing to setup progress.The chat renders that message immediately, including its space context chip.Reopened transcripts reconcile the plain initial prompt with its context-bearingdiff --git a/products/desktop/packages/agent/e2e/session-startup.e2e.test.ts b/products/desktop/packages/agent/e2e/session-startup.e2e.test.tsnew file mode 100644index 000000000000..384190b7e509--- /dev/null+++ b/products/desktop/packages/agent/e2e/session-startup.e2e.test.ts@@ -0,0 +1,158 @@+import { execFileSync } from "node:child_process";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { ClientSideConnection, ndJsonStream } from "@agentclientprotocol/sdk";+import { expect, it, vi } from "vitest";+import { createAcpConnection } from "../src/adapters/acp-connection";+import { withTimeout } from "../src/utils/common";+import { Logger } from "../src/utils/logger";++it("runs repository setup in a new worktree beyond the connection deadline", async () => {+ const directory = mkdtempSync(join(tmpdir(), "desktop-startup-"));+ const repository = join(directory, "repository");+ const worktree = join(directory, "worktree");+ const source = execFileSync("git", ["rev-parse", "--show-toplevel"], {+ encoding: "utf8",+ }).trim();+ const settings = JSON.stringify({+ hooks: {+ SessionStart: [+ {+ hooks: [+ {+ type: "command",+ command:+ "printf 'started\\n' >> .setup-runs; if [ ! -f .setup-ready ]; then sleep 32; printf ready > .setup-ready; fi",+ timeout: 45,+ },+ ],+ },+ ],+ },+ });++ try {+ execFileSync(+ "git",+ ["clone", "--shared", "--no-checkout", source, repository],+ {+ stdio: "ignore",+ },+ );+ execFileSync(+ "git",+ ["worktree", "add", "--detach", "--no-checkout", worktree, "HEAD"],+ { cwd: repository, stdio: "ignore" },+ );+ for (const cwd of [repository, worktree]) {+ mkdirSync(join(cwd, ".claude"));+ writeFileSync(join(cwd, ".claude", "settings.json"), settings);+ writeFileSync(join(cwd, ".gitignore"), ".setup-ready\n.setup-runs\n");+ }+ writeFileSync(join(repository, ".setup-ready"), "ready");+ expect(statSync(join(repository, ".git")).isDirectory()).toBe(true);+ expect(statSync(join(worktree, ".git")).isFile()).toBe(true);+ expect(existsSync(join(worktree, ".setup-ready"))).toBe(false);++ vi.stubEnv("CLAUDE_CONFIG_DIR", join(directory, "config"));+ vi.stubEnv("ANTHROPIC_API_KEY", "example-not-a-real-key");+ vi.stubEnv("ANTHROPIC_AUTH_TOKEN", "");+ vi.stubEnv("ANTHROPIC_BASE_URL", "http://127.0.0.1:9");+ vi.stubEnv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1");++ for (const { cwd, needsSetup } of [+ { cwd: repository, needsSetup: false },+ { cwd: worktree, needsSetup: true },+ { cwd: worktree, needsSetup: false },+ ]) {+ const onLog = vi.fn();+ const onNotification = vi.fn();+ const transport = createAcpConnection({+ adapter: "claude",+ deviceType: "local",+ logger: new Logger({ onLog }),+ });+ const connection = new ClientSideConnection(+ () => ({+ sessionUpdate: async () => {},+ extNotification: onNotification,+ requestPermission: async () => ({+ outcome: { outcome: "cancelled" },+ }),+ }),+ ndJsonStream(+ transport.clientStreams.writable,+ transport.clientStreams.readable,+ ),+ );++ try {+ await connection.initialize({+ protocolVersion: 1,+ clientCapabilities: {},+ });+ const starting = connection.newSession({+ cwd,+ mcpServers: [],+ _meta: {+ environment: "local",+ claudeCode: {+ options: {+ settingSources: ["project"],+ includeHookEvents: false,+ },+ },+ },+ });+ const atConnectionDeadline = await withTimeout(starting, 30_000);+ if (needsSetup) {+ expect(atConnectionDeadline).toEqual({ result: "timeout" });+ expect(onNotification).toHaveBeenCalledWith(+ "_posthog/status",+ expect.objectContaining({ status: "setup_hooks" }),+ );+ expect(existsSync(join(cwd, ".setup-ready"))).toBe(false);+ } else {+ expect(atConnectionDeadline.result).toBe("success");+ }+ const response = await starting;++ expect(response.sessionId).toBeTruthy();+ expect(existsSync(join(cwd, ".setup-ready"))).toBe(true);+ expect(+ readFileSync(join(cwd, ".claude", "settings.json"), "utf8"),+ ).toBe(settings);+ expect(onNotification).toHaveBeenCalledWith(+ "_posthog/status",+ expect.objectContaining({ status: "sdk_initialization" }),+ );+ expect(onLog).toHaveBeenCalledWith(+ "info",+ "agent:AcpConnection:ClaudeInitialization",+ "Session initialized",+ expect.objectContaining({ initMs: expect.any(Number) }),+ );+ } finally {+ await transport.cleanup();+ }+ }+ expect(readFileSync(join(repository, ".setup-runs"), "utf8")).toBe(+ "started\n",+ );+ expect(readFileSync(join(worktree, ".setup-runs"), "utf8")).toBe(+ "started\nstarted\n",+ );+ } finally {+ vi.unstubAllEnvs();+ rmSync(directory, { recursive: true, force: true });+ }+}, 90_000);diff --git a/products/desktop/packages/agent/src/adapters/acp-connection.ts b/products/desktop/packages/agent/src/adapters/acp-connection.tsindex 92831e794563..9cb19eaa36ee 100644--- a/products/desktop/packages/agent/src/adapters/acp-connection.ts+++ b/products/desktop/packages/agent/src/adapters/acp-connection.ts@@ -161,6 +161,7 @@ function createClaudeConnection(config: AcpConnectionConfig): AcpConnection {const agentConnection = new AgentSideConnection((client) => {agent = new ClaudeAcpAgent(client, {...config.processCallbacks,+ startupLogger: logger.child("ClaudeInitialization"),onStructuredOutput: config.onStructuredOutput,posthogApiConfig: resolveEnricherApiConfig(config),gatewayEnv: config.claudeGatewayEnv,diff --git a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts b/products/desktop/packages/agent/src/adapters/claude/claude-agent.tsindex fe33bfac74ef..bd3b175cc803 100644--- a/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts+++ b/products/desktop/packages/agent/src/adapters/claude/claude-agent.ts@@ -120,6 +120,7 @@ import {} from "./mcp/tool-metadata";import { canUseTool } from "./permissions/permission-handlers";import { getAvailableSlashCommands } from "./session/commands";+import { SessionInitialization } from "./session/initialization";import { getSessionJsonlPath } from "./session/jsonl-hydration";import { parseMcpServers } from "./session/mcp-config";import {@@ -364,6 +365,7 @@ async function fetchContextUsedTokens(}export interface ClaudeAcpAgentOptions {+ startupLogger?: Logger;onProcessSpawned?: (info: ProcessSpawnedInfo) => void;onProcessExited?: (pid: number) => void;onMcpServersReady?: (serverNames: string[]) => void;@@ -2833,6 +2835,23 @@ export class ClaudeAcpAgent extends BaseAcpAgent {const taskState: TaskState = new Map();const traceparentHookNonce = generateTraceparentHookNonce();+ const startupLogger = this.options?.startupLogger ?? this.logger;+ const initialization = new SessionInitialization((initializationPhase) => {+ startupLogger.info("Session initialization phase changed", {+ sessionId,+ taskId,+ taskRunId: meta?.taskRunId,+ initializationPhase,+ });+ void this.client+ .extNotification(POSTHOG_NOTIFICATIONS.STATUS, {+ taskRunId: meta?.taskRunId,+ status: initializationPhase,+ })+ .catch(() => {+ startupLogger.warn("Failed to publish session startup phase");+ });+ });const options = buildSessionOptions({cwd,mcpServers,@@ -2860,6 +2879,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {onPostHogResourceUsed: this.createOnPostHogResourceUsed(),onProcessSpawned: this.options?.onProcessSpawned,onProcessExited: this.options?.onProcessExited,+ onStartupOutput: (stdout) => initialization.observe(stdout),effort,enrichmentDeps: this.enrichment?.deps,enrichedReadCache: this.enrichedReadCache,@@ -2942,14 +2962,11 @@ export class ClaudeAcpAgent extends BaseAcpAgent {// 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 withTimeout(- q.initializationResult(),- SESSION_VALIDATION_TIMEOUT_MS,- );+ const result = await initialization.wait(q.initializationResult());if (result.result === "timeout") {throw new RequestError(-32603,- `Session ${forkSession ? "fork" : "resumption"} timed out after ${SESSION_VALIDATION_TIMEOUT_MS}ms`,+ `Session ${result.phase === "setup_hooks" ? "setup hooks" : forkSession ? "fork" : "resumption"} timed out after ${result.timeoutMs}ms`,{ sessionId, taskId, taskRunId: meta?.taskRunId },);}@@ -2968,7 +2985,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {) {throw RequestError.resourceNotFound(sessionId);}- this.logger.error(+ startupLogger.error(forkSession ? "Session fork failed" : "Session resumption failed",{sessionId,@@ -2985,7 +3002,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {// with the model config fetch below (the gateway REST call is independent).const initStartedAt = Date.now();const initPromise = !isResume- ? withTimeout(q.initializationResult(), SESSION_VALIDATION_TIMEOUT_MS)+ ? initialization.wait(q.initializationResult()): undefined;const requestedModel =meta?.model || settingsManager.getSettings().model || undefined;@@ -3020,12 +3037,16 @@ export class ClaudeAcpAgent extends BaseAcpAgent {: rawModelOptions;if (initPromise) {+ let initializationPhase = initialization.phase;+ let timeoutMs = SESSION_VALIDATION_TIMEOUT_MS;try {const initResult = await initPromise;if (initResult.result === "timeout") {+ initializationPhase = initResult.phase;+ timeoutMs = initResult.timeoutMs;throw new RequestError(-32603,- `Session initialization timed out after ${SESSION_VALIDATION_TIMEOUT_MS}ms`,+ `Session ${initializationPhase === "setup_hooks" ? "setup hooks" : "initialization"} timed out after ${timeoutMs}ms`,{ sessionId, taskId, taskRunId: meta?.taskRunId },);}@@ -3035,7 +3056,7 @@ export class ClaudeAcpAgent extends BaseAcpAgent {session.fastModeEnabled = fastModeStateEnabled(initResult.value.fast_mode_state,);- this.logger.info("Session initialized", {+ startupLogger.info("Session initialized", {sessionId,taskId,taskRunId: meta?.taskRunId,@@ -3046,12 +3067,12 @@ export class ClaudeAcpAgent extends BaseAcpAgent {settingsManager.dispose();this.terminateQuery(q, abortController);const initMs = Date.now() - initStartedAt;- this.logger.error("Session initialization failed", {+ startupLogger.error("Session initialization failed", {sessionId,taskId,taskRunId: meta?.taskRunId,- initializationPhase: "sdk_initialization",- timeoutMs: SESSION_VALIDATION_TIMEOUT_MS,+ initializationPhase,+ timeoutMs,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.tsnew file mode 100644index 000000000000..a8b929c85707--- /dev/null+++ b/products/desktop/packages/agent/src/adapters/claude/session/initialization.test.ts@@ -0,0 +1,109 @@+import { PassThrough } from "node:stream";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SessionInitialization } from "./initialization";++function hookEvent(subtype: string, hookId = "example-hook"): string {+ return `${JSON.stringify({+ type: "system",+ subtype,+ hook_event: "SessionStart",+ hook_id: hookId,+ })}\n`;+}++describe("SessionInitialization", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it("allows setup to finish after the connection deadline without consuming SDK output", async () => {+ const stdout = new PassThrough();+ const received: string[] = [];+ stdout.on("data", (chunk: Buffer) => received.push(chunk.toString()));+ const monitor = new SessionInitialization(vi.fn());+ monitor.observe(stdout);+ let finish!: (value: string) => void;+ const result = monitor.wait(+ new Promise<string>((resolve) => {+ finish = resolve;+ }),+ );+ const settled = vi.fn();+ void result.then(settled);+ const start = hookEvent("hook_started");+ stdout.write(start.slice(0, 20));+ stdout.write(start.slice(20));++ await vi.advanceTimersByTimeAsync(32_000);+ expect(settled).not.toHaveBeenCalled();++ const complete = hookEvent("hook_response");+ stdout.write(complete);+ finish("ready");+ await expect(result).resolves.toEqual({+ result: "success",+ value: "ready",+ });+ expect(received.join("")).toBe(start + complete);+ expect(stdout.listenerCount("data")).toBe(1);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each(["no hooks", "hooks complete", "hooks still running"])(+ "bounds stalled initialization with %s",+ async (scenario) => {+ const stdout = new PassThrough();+ const monitor = new SessionInitialization(vi.fn());+ monitor.observe(stdout);+ const result = monitor.wait(new Promise<never>(() => {}));+ if (scenario !== "no hooks") stdout.write(hookEvent("hook_started"));+ if (scenario === "hooks complete")+ stdout.write(hookEvent("hook_response"));++ const hooksRunning = scenario === "hooks still running";+ const timeoutMs = hooksRunning ? 600_000 : 30_000;+ await vi.advanceTimersByTimeAsync(timeoutMs - 1);+ stdout.write(hookEvent("hook_progress"));+ await vi.advanceTimersByTimeAsync(1);++ await expect(result).resolves.toEqual({+ result: "timeout",+ phase: hooksRunning ? "setup_hooks" : "sdk_initialization",+ timeoutMs,+ });+ expect(stdout.listenerCount("data")).toBe(0);+ },+ );++ it("waits for all concurrent hooks and ignores oversized unrelated output", async () => {+ const stdout = new PassThrough();+ const monitor = new SessionInitialization(vi.fn());+ monitor.observe(stdout);+ const result = monitor.wait(new Promise<never>(() => {}));+ stdout.write("x".repeat(300_000));+ stdout.write(+ `\n${hookEvent("hook_started", "first")}${hookEvent("hook_started", "second")}`,+ );+ stdout.write(hookEvent("hook_response", "first"));+ await vi.advanceTimersByTimeAsync(32_000);+ expect(monitor.phase).toBe("setup_hooks");+ stdout.write(hookEvent("hook_response", "second"));+ await vi.advanceTimersByTimeAsync(30_000);+ await expect(result).resolves.toMatchObject({+ result: "timeout",+ phase: "sdk_initialization",+ });+ });++ it("removes observers and timers when the SDK rejects initialization", async () => {+ const stdout = new PassThrough();+ const monitor = new SessionInitialization(vi.fn());+ monitor.observe(stdout);++ await expect(+ monitor.wait(Promise.reject(new Error("Example startup failure"))),+ ).rejects.toThrow("Example startup failure");++ expect(stdout.listenerCount("data")).toBe(0);+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/products/desktop/packages/agent/src/adapters/claude/session/initialization.ts b/products/desktop/packages/agent/src/adapters/claude/session/initialization.tsnew file mode 100644index 000000000000..0b6cac124a32--- /dev/null+++ b/products/desktop/packages/agent/src/adapters/claude/session/initialization.ts@@ -0,0 +1,128 @@+import type { Readable } from "node:stream";+import { StringDecoder } from "node:string_decoder";++type InitializationPhase = "sdk_initialization" | "setup_hooks";++type InitializationResult<Value> =+ | { result: "success"; value: Value }+ | {+ result: "timeout";+ phase: InitializationPhase;+ timeoutMs: number;+ };++const MAX_OBSERVED_LINE_LENGTH = 256 * 1024;++export class SessionInitialization {+ private activeHooks = new Set<string>();+ private hooksStartedAt: number | undefined;+ private reschedule: (() => void) | undefined;+ private detach: (() => void) | undefined;+ private disposed = false;++ constructor(+ private onPhaseChange: (phase: InitializationPhase) => void,+ private connectionTimeoutMs = 30_000,+ private hooksTimeoutMs = 600_000,+ ) {}++ get phase(): InitializationPhase {+ return this.activeHooks.size > 0 ? "setup_hooks" : "sdk_initialization";+ }++ observe(stdout: Readable): void {+ if (this.disposed) return;+ const decoder = new StringDecoder("utf8");+ let buffer = "";+ let oversized = false;+ const onData = (chunk: Buffer): void => {+ const parts = decoder.write(chunk).split("\n");+ for (let index = 0; index < parts.length; index++) {+ const part = parts[index];+ if (buffer.length + part.length > MAX_OBSERVED_LINE_LENGTH) {+ oversized = true;+ buffer = "";+ }+ if (!oversized) buffer += part;+ if (index < parts.length - 1) {+ if (!oversized) this.observeLine(buffer);+ buffer = "";+ oversized = false;+ }+ }+ };+ stdout.on("data", onData);+ this.detach = () => stdout.off("data", onData);+ }++ private observeLine(line: string): void {+ let message: unknown;+ try {+ message = JSON.parse(line);+ } catch {+ return;+ }+ if (+ !message ||+ typeof message !== "object" ||+ !("type" in message) ||+ message.type !== "system" ||+ !("hook_event" in message) ||+ message.hook_event !== "SessionStart" ||+ !("hook_id" in message) ||+ typeof message.hook_id !== "string" ||+ !("subtype" in message)+ ) {+ return;+ }+ const previousPhase = this.phase;+ if (message.subtype === "hook_started") {+ this.activeHooks.add(message.hook_id);+ this.hooksStartedAt ??= Date.now();+ } else if (message.subtype === "hook_response") {+ this.activeHooks.delete(message.hook_id);+ }+ if (this.phase !== previousPhase) {+ this.onPhaseChange(this.phase);+ this.reschedule?.();+ }+ }++ async wait<Value>(+ initialization: Promise<Value>,+ ): Promise<InitializationResult<Value>> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await new Promise<InitializationResult<Value>>(+ (resolve, reject) => {+ this.reschedule = () => {+ clearTimeout(timer);+ const phase = this.phase;+ const timeoutMs =+ phase === "setup_hooks"+ ? this.hooksTimeoutMs+ : this.connectionTimeoutMs;+ const remainingMs =+ phase === "setup_hooks"+ ? timeoutMs - (Date.now() - (this.hooksStartedAt ?? Date.now()))+ : timeoutMs;+ timer = setTimeout(+ () => resolve({ result: "timeout", phase, timeoutMs }),+ Math.max(0, remainingMs),+ );+ };+ this.reschedule();+ initialization.then(+ (value) => resolve({ result: "success", value }),+ reject,+ );+ },+ );+ } finally {+ clearTimeout(timer);+ this.reschedule = undefined;+ this.disposed = true;+ this.detach?.();+ }+ }+}diff --git a/products/desktop/packages/agent/src/adapters/claude/session/options.ts b/products/desktop/packages/agent/src/adapters/claude/session/options.tsindex c726a9f1b341..fcd7f0e6f731 100644--- a/products/desktop/packages/agent/src/adapters/claude/session/options.ts+++ b/products/desktop/packages/agent/src/adapters/claude/session/options.ts@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";-import type { Writable } from "node:stream";+import type { Readable, Writable } from "node:stream";import type {CanUseTool,McpServerConfig,@@ -105,6 +105,7 @@ export interface BuildOptionsParams {onModeChange?: OnModeChange;onProcessSpawned?: (info: ProcessSpawnedInfo) => void;onProcessExited?: (pid: number) => void;+ onStartupOutput?: (stdout: Readable) => void;effort?: EffortLevel;enrichmentDeps?: FileEnrichmentDeps;enrichedReadCache?: EnrichedReadCache;@@ -486,6 +487,7 @@ function buildSpawnWrapper(onProcessExited?: (pid: number) => void,logger?: Logger,oauthToken?: string,+ onStartupOutput?: (stdout: Readable) => void,): (options: SpawnOptions) => SpawnedProcess {return (spawnOpts: SpawnOptions): SpawnedProcess => {const command = oauthToken ? "/bin/bash" : spawnOpts.command;@@ -510,6 +512,8 @@ function buildSpawnWrapper(: ["pipe", "pipe", "pipe"],});+ if (child.stdout) onStartupOutput?.(child.stdout);+if (oauthToken) {const tokenPipe = child.stdio[3] as Writable;tokenPipe.on("error", () => child.kill("SIGTERM"));@@ -657,8 +661,9 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {},// Surfaces the traceparent hook's output as `hook_response` messages.includeHookEvents:- params.userProvidedOptions?.includeHookEvents ??- traceparentHookSettings !== undefined,+ !!params.onStartupOutput ||+ (params.userProvidedOptions?.includeHookEvents ??+ traceparentHookSettings !== undefined),mcpServers: buildMcpServers(params.userProvidedOptions?.mcpServers,params.mcpServers,@@ -695,13 +700,16 @@ export function buildSessionOptions(params: BuildOptionsParams): Options {abortController: getAbortController(params.userProvidedOptions?.abortController,),- ...((params.onProcessSpawned || params.machineAuth?.oauthToken) && {+ ...((params.onProcessSpawned ||+ params.machineAuth?.oauthToken ||+ params.onStartupOutput) && {spawnClaudeCodeProcess: buildSpawnWrapper(params.sessionId,params.onProcessSpawned,params.onProcessExited,params.logger,params.machineAuth?.oauthToken,+ params.onStartupOutput,),}),};diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 947895e0ddbc..0047e0fe9e04 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -132,6 +132,10 @@ import {import { selectSessionsToEvict } from "./sessionEviction";import { createBaseSession } from "./sessionFactory";import { type ParsedSessionLogs, parseSessionLogContent } from "./sessionLogs";+import {+ readSessionStartupPhase,+ type SessionStartupPhase,+} from "./sessionStartup";const LOCAL_SESSION_RECONNECT_ATTEMPTS = 3;const LOCAL_SESSION_RECONNECT_BACKOFF = {@@ -360,7 +364,12 @@ export interface ISessionStore {setSession(session: AgentSession): void;removeSession(taskRunId: string): void;setTaskStarting?(taskId: string, runId?: string): void;- clearTaskStarting?(taskId: string): void;+ clearTaskStarting?(taskId: string, runId?: string): void;+ setTaskStartupPhase?(+ taskId: string,+ runId: string,+ phase: SessionStartupPhase,+ ): void;updateSession(taskRunId: string, updates: Partial<AgentSession>): void;appendEvents(taskRunId: string,@@ -2673,28 +2682,51 @@ export class SessionService {claude: modelAccess?.claude ?? settingsClaudeModelAccess,};const preferredModel = model ?? this.d.DEFAULT_GATEWAY_MODEL;- const result = await this.d.trpc.agent.start.mutate({- taskId,- taskRunId: taskRun.id,- repoPath,- apiHost: auth.apiHost,- projectId: auth.projectId,- permissionMode: executionMode,- adapter,- codexModelAccess: resolvedModelAccess.codex,- claudeModelAccess: resolvedModelAccess.claude,- customInstructions: startCustomInstructions || undefined,- rtkEnabled: rtkEnabledLocal,- spokenNarration: spokenNarrationEnabled === true,- bedrockGatewayVariant,- effort: effortLevelSchema.safeParse(reasoningLevel).success- ? (reasoningLevel as EffortLevel)- : undefined,- contextWindow,- fastMode,- model: preferredModel,- importedSessionId,- });+ this.d.store.setTaskStarting?.(taskId, taskRun.id);+ const startupSubscription = this.d.trpc.agent.onSessionEvent.subscribe(+ { taskRunId: taskRun.id },+ {+ onData: (event) => {+ const phase = readSessionStartupPhase(event);+ if (phase)+ this.d.store.setTaskStartupPhase?.(taskId, taskRun.id, phase);+ },+ onError: () => {+ this.d.log.warn("Startup progress is unavailable", {+ taskId,+ taskRunId: taskRun.id,+ });+ },+ },+ );+ const result = await this.d.trpc.agent.start+ .mutate({+ taskId,+ taskRunId: taskRun.id,+ repoPath,+ apiHost: auth.apiHost,+ projectId: auth.projectId,+ permissionMode: executionMode,+ adapter,+ codexModelAccess: resolvedModelAccess.codex,+ claudeModelAccess: resolvedModelAccess.claude,+ customInstructions: startCustomInstructions || undefined,+ rtkEnabled: rtkEnabledLocal,+ spokenNarration: spokenNarrationEnabled === true,+ bedrockGatewayVariant,+ effort: effortLevelSchema.safeParse(reasoningLevel).success+ ? (reasoningLevel as EffortLevel)+ : undefined,+ contextWindow,+ fastMode,+ model: preferredModel,+ importedSessionId,+ })+ .catch((error) => {+ this.d.store.clearTaskStarting?.(taskId, taskRun.id);+ throw error;+ })+ .finally(() => startupSubscription.unsubscribe());const session = createBaseSession(taskRun.id, taskId, taskTitle);session.channel = result.channel;@@ -2750,6 +2782,7 @@ export class SessionService {}this.d.store.setSession(session);+ this.d.store.clearTaskStarting?.(taskId, taskRun.id);this.subscribeToChannel(taskRun.id);this.d.track(ANALYTICS_EVENTS.TASK_RUN_STARTED, {@@ -6189,34 +6222,49 @@ export class SessionService {codexModelAccess,claudeModelAccess,} = session;- await this.teardownSession(session.taskRunId);- const authStatus = await this.getAuthCredentialsStatus();- if (authStatus.kind === "restoring") {- throw new Error("Authentication is still restoring. Please wait.");- }- if (authStatus.kind !== "ready") {- throw new Error(- "Unable to reach server. Please check your connection.",+ try {+ const authStatus = await this.getAuthCredentialsStatus();+ if (authStatus.kind === "restoring") {+ throw new Error("Authentication is still restoring. Please wait.");+ }+ if (authStatus.kind !== "ready") {+ throw new Error(+ "Unable to reach server. Please check your connection.",+ );+ }+ await this.teardownSession(session.taskRunId);+ await this.createNewLocalSession(+ taskId,+ taskTitle,+ repoPath,+ authStatus.auth,+ initialPrompt,+ executionMode,+ adapter,+ model,+ reasoningLevel,+ undefined,+ contextWindow,+ fastMode,+ { codex: codexModelAccess, claude: claudeModelAccess },);+ } catch (error) {+ const recoverySession =+ this.d.store.getSessionByTaskId(taskId) ?? session;+ this.d.store.setSession({+ ...recoverySession,+ status: "error",+ errorTitle: "Failed to connect",+ errorMessage: error instanceof Error ? error.message : String(error),+ });+ this.localRepoPaths.set(taskId, repoPath);+ throw error;}- await this.createNewLocalSession(- taskId,- taskTitle,- repoPath,- authStatus.auth,- initialPrompt,- executionMode,- adapter,- model,- reasoningLevel,- undefined,- contextWindow,- fastMode,- { codex: codexModelAccess, claude: claudeModelAccess },- );return;}- await this.reconnectInPlace(taskId, repoPath);+ if (!(await this.reconnectInPlace(taskId, repoPath))) {+ throw new Error("Failed to reconnect to session. Please try again.");+ }}/**@@ -6232,19 +6280,20 @@ export class SessionService {private async runHasConversationHistory(session: AgentSession,): Promise<boolean> {- const isPromptEcho = (event: AcpMessage): boolean =>- isJsonRpcRequest(event.message) &&- event.message.method === "session/prompt";- if (session.events.some((event) => !isPromptEcho(event))) {+ const isConversationEvent = (event: AcpMessage): boolean =>+ !readSessionStartupPhase(event) &&+ !(+ isJsonRpcRequest(event.message) &&+ event.message.method === "session/prompt"+ );+ if (session.events.some(isConversationEvent)) {return true;}const { rawEntries } = await this.fetchSessionLogs(session.logUrl,session.taskRunId,);- return convertStoredEntriesToEvents(rawEntries).some(- (event) => !isPromptEcho(event),- );+ return convertStoredEntriesToEvents(rawEntries).some(isConversationEvent);}/**diff --git a/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.tsindex 026aec4b59b9..fe92dbc31cc9 100644--- a/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionServiceRetryConfig.test.ts@@ -66,28 +66,39 @@ function createHarness(session: AgentSession) {store: {getSessionByTaskId: (taskId: string) =>Object.values(sessions).find((s) => s.taskId === taskId),+ getSessions: () => sessions,+ setSession: (nextSession: AgentSession) => {+ sessions[nextSession.taskRunId] = nextSession;+ },+ removeSession: (taskRunId: string) => {+ delete sessions[taskRunId];+ },},log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },trpc: {agent: {+ cancel: { mutate: vi.fn().mockResolvedValue(undefined) },+ onSessionEvent: { subscribe: () => ({ unsubscribe: vi.fn() }) },onSessionIdleKilled: {subscribe: () => ({ unsubscribe: vi.fn() }),},},},+ adapterStore: { removeAdapter: vi.fn(), setAdapter: vi.fn() },+ removePersistedConfigOptions: vi.fn(),+ settings: {},+ track: vi.fn(),} as unknown as SessionServiceDeps;const service = new SessionService(deps);- vi.spyOn(- service as unknown as { teardownSession: () => Promise<void> },- "teardownSession",- ).mockResolvedValue(undefined);- vi.spyOn(- service as unknown as {- getAuthCredentialsStatus: () => Promise<unknown>;- },- "getAuthCredentialsStatus",- ).mockResolvedValue({ kind: "ready", auth: { client: {} } });+ const getAuthCredentialsStatus = vi+ .spyOn(+ service as unknown as {+ getAuthCredentialsStatus: () => Promise<unknown>;+ },+ "getAuthCredentialsStatus",+ )+ .mockResolvedValue({ kind: "ready", auth: { client: {} } });const createNewLocalSession = vi.spyOn(service as unknown as {@@ -117,10 +128,59 @@ function createHarness(session: AgentSession) {parseFailureCount: 0,});- return { service, createNewLocalSession, reconnectInPlace, fetchSessionLogs };+ return {+ service,+ deps,+ createNewLocalSession,+ reconnectInPlace,+ fetchSessionLogs,+ getAuthCredentialsStatus,+ };}describe("SessionService.clearSessionError retry config", () => {+ it("ends startup when a new session connects without a prompt", async () => {+ const { service, deps, createNewLocalSession, getAuthCredentialsStatus } =+ createHarness(makeSession({ initialPrompt: undefined }));+ createNewLocalSession.mockRestore();+ const clearStartup = vi.fn();+ deps.store.clearTaskStarting = clearStartup;+ deps.trpc.agent.start = {+ mutate: vi.fn().mockResolvedValue({ channel: "empty-run" }),+ } as unknown as SessionServiceDeps["trpc"]["agent"]["start"];+ getAuthCredentialsStatus.mockResolvedValue({+ kind: "ready",+ auth: {+ client: {+ createTaskRun: vi.fn().mockResolvedValue({ id: "empty-run" }),+ },+ },+ });+ vi.spyOn(+ service as unknown as { subscribeToChannel: (runId: string) => void },+ "subscribeToChannel",+ ).mockImplementation(() => {});++ await (+ service as unknown as {+ createNewLocalSession: (+ taskId: string,+ title: string,+ repoPath: string,+ auth: unknown,+ ) => Promise<void>;+ }+ ).createNewLocalSession("task-1", "Test task", "/repo", {+ client: { createTaskRun: async () => ({ id: "empty-run" }) },+ });++ expect(deps.store.getSessions()["empty-run"]).toMatchObject({+ taskRunId: "empty-run",+ status: "connected",+ });+ expect(clearStartup).toHaveBeenCalledWith("task-1", "empty-run");+ });+it("recreates the session with the original run configuration", async () => {const session = makeSession({model: "claude-fable-5",@@ -192,16 +252,154 @@ describe("SessionService.clearSessionError retry config", () => {expect(reconnectInPlace).toHaveBeenCalledWith("task-1", "/repo");});- it("recreates when the transcript holds only the user's prompt echo", async () => {- const session = makeSession({ events: [PROMPT_ECHO_EVENT] });- const { service, createNewLocalSession, reconnectInPlace } =- createHarness(session);+ it.each(["prompt echo", "startup progress", "stored startup progress"])(+ "recreates when the transcript holds only %s",+ async (source) => {+ const startupEvent: AcpMessage = {+ type: "acp_message",+ ts: 2,+ message: {+ jsonrpc: "2.0",+ method: "_posthog/status",+ params: { status: "setup_hooks" },+ },+ };+ const events =+ source === "stored startup progress"+ ? []+ : source === "startup progress"+ ? [PROMPT_ECHO_EVENT, startupEvent]+ : [PROMPT_ECHO_EVENT];+ const {+ service,+ createNewLocalSession,+ reconnectInPlace,+ fetchSessionLogs,+ } = createHarness(makeSession({ events }));+ if (source === "stored startup progress") {+ fetchSessionLogs.mockResolvedValue({+ rawEntries: [+ {+ type: "notification",+ timestamp: "2026-07-06T00:00:00.000Z",+ notification: startupEvent.message,+ },+ ],+ totalLineCount: 1,+ parseFailureCount: 0,+ });+ }+ await service.clearSessionError("task-1", "/repo");+ expect(createNewLocalSession).toHaveBeenCalled();+ expect(reconnectInPlace).not.toHaveBeenCalled();+ },+ );- await service.clearSessionError("task-1", "/repo");+ it.each(["create run", "start agent", "send prompt"])(+ "preserves recovery state after repeated failures to %s",+ async (failureStage) => {+ const session = makeSession({+ model: "claude-fable-5",+ adapter: "claude",+ executionMode: "auto",+ });+ const { service, deps, createNewLocalSession, getAuthCredentialsStatus } =+ createHarness(session);+ createNewLocalSession.mockRestore();+ let nextRun = 0;+ const createTaskRun = vi.fn(async () => ({ id: `retry-${++nextRun}` }));+ let onStartupEvent: ((event: unknown) => void) | undefined;+ const unsubscribeStartup = vi.fn();+ const reportStartupPhase = vi.fn();+ deps.store.setTaskStartupPhase = reportStartupPhase;+ const clearStartup = vi.fn();+ deps.store.clearTaskStarting = clearStartup;+ deps.trpc.agent.onSessionEvent = {+ subscribe: (+ _input: unknown,+ callbacks: { onData?: (event: unknown) => void },+ ) => {+ onStartupEvent = callbacks.onData;+ return { unsubscribe: unsubscribeStartup };+ },+ };+ const startAgent = vi.fn().mockImplementation(async () => {+ onStartupEvent?.({+ message: {+ method: "_posthog/status",+ params: { status: "setup_hooks" },+ },+ });+ return { channel: "retry" };+ });+ deps.trpc.agent.start = {+ mutate: startAgent,+ } as unknown as SessionServiceDeps["trpc"]["agent"]["start"];+ getAuthCredentialsStatus.mockResolvedValue({+ kind: "ready",+ auth: { client: { createTaskRun } },+ });+ vi.spyOn(+ service as unknown as { subscribeToChannel: () => void },+ "subscribeToChannel",+ ).mockImplementation(() => {});+ const sendPrompt = vi+ .spyOn(service, "sendPrompt")+ .mockResolvedValue({ stopReason: "end_turn" });+ const failure = new Error(`Cannot ${failureStage}`);+ const failingOperation =+ failureStage === "create run"+ ? createTaskRun+ : failureStage === "start agent"+ ? startAgent+ : sendPrompt;+ failingOperation+ .mockRejectedValueOnce(failure)+ .mockRejectedValueOnce(failure);- expect(createNewLocalSession).toHaveBeenCalled();- expect(reconnectInPlace).not.toHaveBeenCalled();- });+ for (let attempt = 0; attempt < 2; attempt++) {+ await expect(+ service.clearSessionError("task-1", "/repo"),+ ).rejects.toThrow(failure.message);+ expect(deps.store.getSessionByTaskId("task-1")).toMatchObject({+ status: "error",+ errorMessage: failure.message,+ initialPrompt: session.initialPrompt,+ model: session.model,+ adapter: session.adapter,+ executionMode: session.executionMode,+ ...(failureStage === "send prompt"+ ? { taskRunId: `retry-${attempt + 1}` }+ : {}),+ });+ }++ await service.clearSessionError("task-1", "/repo");++ expect(deps.store.getSessionByTaskId("task-1")).toMatchObject({+ status: "connected",+ initialPrompt: session.initialPrompt,+ model: session.model,+ });+ expect(sendPrompt).toHaveBeenLastCalledWith(+ "task-1",+ session.initialPrompt,+ );+ expect(createTaskRun).toHaveBeenCalledTimes(3);+ expect(reportStartupPhase).toHaveBeenLastCalledWith(+ "task-1",+ deps.store.getSessionByTaskId("task-1")?.taskRunId,+ "setup_hooks",+ );+ expect(unsubscribeStartup).toHaveBeenCalledTimes(+ startAgent.mock.calls.length,+ );+ if (failureStage === "start agent") {+ expect(clearStartup).toHaveBeenNthCalledWith(1, "task-1", "retry-1");+ expect(clearStartup).toHaveBeenNthCalledWith(2, "task-1", "retry-2");+ }+ },+ );});const CONNECT_PARAMS: ConnectParams = {@@ -262,6 +460,7 @@ describe("SessionService.connectToTask start failure", () => {.fn().mockRejectedValue(new Error("session start timeout")),},+ onSessionEvent: { subscribe: () => ({ unsubscribe: vi.fn() }) },onSessionIdleKilled: {subscribe: () => ({ unsubscribe: vi.fn() }),},@@ -307,6 +506,7 @@ describe("SessionService.connectToTask missing auth", () => {getIsOnline: () => true,trpc: {agent: {+ onSessionEvent: { subscribe: () => ({ unsubscribe: vi.fn() }) },onSessionIdleKilled: {subscribe: () => ({ unsubscribe: vi.fn() }),},diff --git a/products/desktop/packages/core/src/sessions/sessionStartup.test.ts b/products/desktop/packages/core/src/sessions/sessionStartup.test.tsnew file mode 100644index 000000000000..507197fd660a--- /dev/null+++ b/products/desktop/packages/core/src/sessions/sessionStartup.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from "vitest";+import { readSessionStartupPhase } from "./sessionStartup";++describe("readSessionStartupPhase", () => {+ it.each(["_posthog/status", "__posthog/status"])(+ "reads startup progress from %s",+ (method) => {+ expect(+ readSessionStartupPhase({+ message: { method, params: { status: "setup_hooks" } },+ }),+ ).toBe("setup_hooks");+ },+ );++ it.each([+ null,+ {+ message: { method: "_posthog/status", params: { status: "compacting" } },+ },+ {+ message: { method: "session/update", params: { status: "setup_hooks" } },+ },+ { message: { method: "_posthog/status", params: null } },+ ])("ignores unrelated or malformed events", (event) => {+ expect(readSessionStartupPhase(event)).toBeUndefined();+ });+});diff --git a/products/desktop/packages/core/src/sessions/sessionStartup.ts b/products/desktop/packages/core/src/sessions/sessionStartup.tsnew file mode 100644index 000000000000..9545c615901c--- /dev/null+++ b/products/desktop/packages/core/src/sessions/sessionStartup.ts@@ -0,0 +1,28 @@+import { z } from "zod";+import { isNotification, POSTHOG_NOTIFICATIONS } from "./acpNotifications";++const startupEventSchema = z.object({+ message: z.object({+ method: z.string(),+ params: z.object({+ status: z.enum(["sdk_initialization", "setup_hooks"]),+ }),+ }),+});++export type SessionStartupPhase = z.infer<+ typeof startupEventSchema+>["message"]["params"]["status"];++export function readSessionStartupPhase(+ event: unknown,+): SessionStartupPhase | undefined {+ const result = startupEventSchema.safeParse(event);+ if (+ result.success &&+ isNotification(result.data.message.method, POSTHOG_NOTIFICATIONS.STATUS)+ ) {+ return result.data.message.params.status;+ }+ return undefined;+}diff --git a/products/desktop/packages/core/src/sessions/sessionStore.ts b/products/desktop/packages/core/src/sessions/sessionStore.tsindex c5954742dd90..5ddb997550f7 100644--- a/products/desktop/packages/core/src/sessions/sessionStore.ts+++ b/products/desktop/packages/core/src/sessions/sessionStore.ts@@ -12,6 +12,7 @@ import { isTerminalStatus } from "@posthog/shared/domain-types";import { setAutoFreeze } from "immer";import { immer } from "zustand/middleware/immer";import { createStore } from "zustand/vanilla";+import type { SessionStartupPhase } from "./sessionStartup";// immer autofreeze deep-walks produced state on every commit. For the// append-only `events` array that re-walks the whole (growing) array on every@@ -26,7 +27,10 @@ export interface SessionState {/** Index mapping taskId -> taskRunId for O(1) lookups */taskIdIndex: Record<string, string>;/** Task ids whose first/resumed agent session is being created. */- startingTaskIds: Record<string, { previousRunId?: string; runId?: string }>;+ startingTaskIds: Record<+ string,+ { previousRunId?: string; runId?: string; phase?: SessionStartupPhase }+ >;}export const sessionStore = createStore<SessionState>()(@@ -155,7 +159,10 @@ export const sessionStoreSetters = {sessionStore.setState((state) => {const marker = state.startingTaskIds[taskId];if (marker) {- if (runId) marker.runId = runId;+ if (runId && marker.runId !== runId) {+ marker.runId = runId;+ marker.phase = undefined;+ }return;}state.startingTaskIds[taskId] = {@@ -165,8 +172,20 @@ export const sessionStoreSetters = {});},- clearTaskStarting: (taskId: string) => {+ setTaskStartupPhase: (+ taskId: string,+ runId: string,+ phase: SessionStartupPhase,+ ) => {+ sessionStore.setState((state) => {+ const marker = state.startingTaskIds[taskId];+ if (marker?.runId === runId) marker.phase = phase;+ });+ },++ clearTaskStarting: (taskId: string, runId?: string) => {sessionStore.setState((state) => {+ if (runId && state.startingTaskIds[taskId]?.runId !== runId) return;delete state.startingTaskIds[taskId];});},diff --git a/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts b/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.tsindex 41d488581c52..89801d03d082 100644--- a/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts@@ -180,3 +180,39 @@ describe("evictEvents / restoreEvents", () => {expect(sessionStore.getState().sessions[RUN].events).toHaveLength(0);});});++describe("startup phase ownership", () => {+ afterEach(() => sessionStoreSetters.clearAll());++ it("ignores stale progress and clears the phase for a replacement run", () => {+ sessionStoreSetters.setTaskStarting(TASK, RUN);+ sessionStoreSetters.setTaskStartupPhase(TASK, RUN, "setup_hooks");+ expect(sessionStore.getState().startingTaskIds[TASK]?.phase).toBe(+ "setup_hooks",+ );+ sessionStoreSetters.setTaskStarting(TASK, "replacement-run");+ sessionStoreSetters.setTaskStartupPhase(TASK, RUN, "setup_hooks");+ expect(+ sessionStore.getState().startingTaskIds[TASK]?.phase,+ ).toBeUndefined();+ sessionStoreSetters.setTaskStartupPhase(+ TASK,+ "replacement-run",+ "setup_hooks",+ );+ expect(sessionStore.getState().startingTaskIds[TASK]?.phase).toBe(+ "setup_hooks",+ );+ sessionStoreSetters.clearTaskStarting(TASK, RUN);+ expect(sessionStore.getState().startingTaskIds[TASK]?.phase).toBe(+ "setup_hooks",+ );+ sessionStoreSetters.clearTaskStarting(TASK, "replacement-run");+ sessionStoreSetters.setTaskStartupPhase(+ TASK,+ "replacement-run",+ "setup_hooks",+ );+ expect(sessionStore.getState().startingTaskIds[TASK]).toBeUndefined();+ });+});diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts b/products/desktop/packages/core/src/sessions/sessionViewState.test.tsindex bbec248e6af0..4eef8142547b 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.test.ts@@ -218,12 +218,33 @@ describe("deriveSessionViewState", () => {).toBe(true);session.status = "connected";+ session.initialPrompt = [+ { type: "text", text: "Inspect the example task" },+ ];+ expect(+ deriveSessionViewState(session, task, null, false).isInitializing,+ ).toBe(true);+session.firstPromptForRunId = session.taskRunId;expect(deriveSessionViewState(session, task, null, false).isInitializing,).toBe(false);});+ it("opens a connected local task when no initial prompt remains to send", () => {+ const task = makeTask("in_progress");+ task.description = "Inspect the example task";+ if (task.latest_run) task.latest_run.environment = "local";+ const session = makeSession("in_progress");+ session.isCloud = false;++ const state = deriveSessionViewState(session, task, null, false);++ expect(state.isInitializing).toBe(false);+ expect(state.isRunning).toBe(true);+ expect(state.hasError).toBe(false);+ });+it("treats not_started as a non-terminal cloud state", () => {const state = deriveSessionViewState(undefined,diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.ts b/products/desktop/packages/core/src/sessions/sessionViewState.tsindex 4e6f4723f4b8..244ad162baa1 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.ts@@ -58,8 +58,7 @@ export function deriveSessionLifecycleState(const hasStarted =sessionMatchesActiveRun && session.firstPromptForRunId === activeTaskRunId;const expectsInitialPrompt =- !!session &&- (!!task.description || !!task.latest_run?.id || session.isPromptPending);+ !!session && (!!session.initialPrompt?.length || session.isPromptPending);let isInitializing = isTaskStarting;if (!isTaskStarting && !hasError && !isCloudRunTerminal && !hasStarted) {diff --git a/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx b/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsxindex 59093023f4f5..e508f543190b 100644--- a/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx+++ b/products/desktop/packages/ui/src/features/permissions/PlanContent.test.tsx@@ -40,6 +40,7 @@ vi.mock("../sessions/sessionStore", () => ({useModelConfigOptionForTask: () => undefined,usePendingPermissionsForTask: () => new Map(),useSessionSelector: () => false,+ useSessionStore: () => undefined,useThoughtLevelConfigOptionForTask: () => undefined,}));vi.mock("../sessions/sessionViewStore", () => ({diff --git a/products/desktop/packages/ui/src/features/provisioning/ProvisioningView.tsx b/products/desktop/packages/ui/src/features/provisioning/ProvisioningView.tsxindex ccd2d69abe7c..5f69f4d0c048 100644--- a/products/desktop/packages/ui/src/features/provisioning/ProvisioningView.tsx+++ b/products/desktop/packages/ui/src/features/provisioning/ProvisioningView.tsx@@ -24,8 +24,12 @@ export function ProvisioningView({ taskId }: ProvisioningViewProps) {<div className="flex h-full flex-col gap-2 p-3"><div className="flex items-center gap-2"><Spinner size="sm" />- <span className="font-medium text-[13px]">Loading</span>+ <span className="font-medium text-[13px]">Preparing worktree</span></div>+ <p className="m-0 text-gray-11 text-sm">+ Creating a separate checkout for this task. Setup output appears+ below.+ </p><div className="min-h-0 flex-1 rounded-(--radius-2) border border-(--gray-a5) bg-(--color-surface)"><preref={scrollRef}diff --git a/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.test.tsxindex eb91be8d2b9a..d600cc73efca 100644--- a/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.test.tsx@@ -1,4 +1,3 @@-import { Theme } from "@radix-ui/themes";import { fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -37,12 +36,11 @@ function renderPending(} = {},) {render(- <Theme>- <PendingChatView- content={props.content ?? "Ship the login fix"}- attachments={props.attachments}- />- </Theme>,+ <PendingChatView+ executionTarget="local"+ content={props.content ?? "Ship the login fix"}+ attachments={props.attachments}+ />,);}@@ -59,7 +57,10 @@ describe("PendingChatView", () => {it("renders the prompt with a loading state", () => {renderPending();expect(screen.getByText("Ship the login fix")).toBeInTheDocument();- expect(screen.getByText("Loading")).toBeInTheDocument();+ expect(screen.getByText("Starting local agent")).toBeInTheDocument();+ expect(+ screen.queryByText(/Your prompt is saved with this task/),+ ).not.toBeInTheDocument();});it("renders file mentions as chips so the bubble matches the live transcript", () => {diff --git a/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsx b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsxindex 1b2c28b26703..3170918132de 100644--- a/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsx@@ -13,9 +13,12 @@ import {CHAT_CONTENT_PADDING_INLINE,} from "@posthog/ui/features/sessions/constants";import type { UserMessageAttachment } from "@posthog/ui/features/sessions/userMessageTypes";-import { Spinner } from "@posthog/ui/primitives/Spinner";+import {+ SessionStartupStatus,+ type SessionStartupStatusProps,+} from "./SessionStartupStatus";-interface PendingChatViewProps {+interface PendingChatViewProps extends SessionStartupStatusProps {/*** The prompt as the live transcript will render it (serialized content with* chips), so the bubble looks the same when the transcript replaces it.@@ -27,6 +30,8 @@ interface PendingChatViewProps {export function PendingChatView({content,attachments,+ executionTarget,+ phase,}: PendingChatViewProps) {return (<div className="absolute inset-0 flex flex-col bg-background">@@ -54,11 +59,13 @@ export function PendingChatView({</ChatMessage></div><div- className="mx-auto flex w-full items-center gap-2 px-2.5"+ className="mx-auto w-full px-2.5"style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}>- <Spinner size="sm" className="text-accent-11" />- <span className="text-[13px] text-accent-11">Loading</span>+ <SessionStartupStatus+ executionTarget={executionTarget}+ phase={phase}+ /></div></div></div>diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.test.tsxindex 50c22be8f183..7a4bda47fbe2 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.test.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.test.tsx@@ -1,4 +1,3 @@-import { Theme } from "@radix-ui/themes";import { act, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { SessionInitializingView } from "./SessionInitializingView";@@ -11,31 +10,57 @@ describe("SessionInitializingView", () => {it.each([{executionTarget: "local" as const,- subtitle: "Connecting to Pi on this device.",+ title: "Starting local agent",},{executionTarget: "cloud" as const,- subtitle: "Connecting to your cloud runner.",+ title: "Starting cloud agent",},])(- "shows Loading through $executionTarget startup",- ({ executionTarget, subtitle }) => {+ "shows the current step through $executionTarget startup",+ ({ executionTarget, title }) => {vi.useFakeTimers();- render(- <Theme>- <SessionInitializingView executionTarget={executionTarget} />- </Theme>,- );+ render(<SessionInitializingView executionTarget={executionTarget} />);- expect(screen.getByText("Loading")).toBeInTheDocument();+ expect(screen.getByRole("status").textContent).toBe(title);act(() => {vi.advanceTimersByTime(2000);});- expect(screen.getByText("Loading")).toBeInTheDocument();- expect(screen.getByText(subtitle)).toBeInTheDocument();+ expect(screen.getByRole("status").textContent).toBe(title);},);++ it("updates the visible phase when hooks start and finish", () => {+ vi.useFakeTimers();+ const { rerender } = render(+ <SessionInitializingView executionTarget="local" />,+ );+ rerender(+ <SessionInitializingView executionTarget="local" phase="setup_hooks" />,+ );+ expect(screen.getByRole("status")).toHaveTextContent(+ "Running repository setup",+ );+ act(() => {+ vi.advanceTimersByTime(2000);+ });+ expect(screen.getByRole("status").textContent).toBe(+ "Running repository setup",+ );+ rerender(+ <SessionInitializingView+ executionTarget="local"+ phase="sdk_initialization"+ />,+ );+ expect(screen.getByRole("status")).toHaveTextContent(+ "Starting local agent",+ );+ expect(+ screen.queryByText("Running repository setup"),+ ).not.toBeInTheDocument();+ });});diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsxindex 851a642183cc..e8d82be83b2a 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsx@@ -1,20 +1,16 @@-import { Spinner } from "@posthog/ui/primitives/Spinner";import { useEffect, useState } from "react";import zenHedgehog from "../../../assets/images/zen.png";--interface SessionInitializingViewProps {- executionTarget: "cloud" | "local";-}+import {+ SessionStartupStatus,+ type SessionStartupStatusProps,+} from "./SessionStartupStatus";const REVEAL_DELAY_MS = 2000;export function SessionInitializingView({executionTarget,-}: SessionInitializingViewProps) {- const subtitle =- executionTarget === "local"- ? "Connecting to Pi on this device."- : "Connecting to your cloud runner.";+ phase,+}: SessionStartupStatusProps) {const [revealed, setRevealed] = useState(false);useEffect(() => {@@ -25,8 +21,7 @@ export function SessionInitializingView({if (!revealed) {return (<div className="absolute inset-0 flex items-center justify-center gap-2 bg-background">- <Spinner size="md" className="text-gray-9" />- <span className="font-medium text-base">Loading</span>+ <SessionStartupStatus executionTarget={executionTarget} phase={phase} /></div>);}@@ -36,13 +31,7 @@ export function SessionInitializingView({<div className="zen-float"><img src={zenHedgehog} alt="" className="block w-[160px]" /></div>- <div className="flex flex-col items-center gap-2">- <div className="flex items-center gap-2">- <Spinner size="md" className="text-gray-9" />- <span className="font-medium text-base">Loading</span>- </div>- <span className="text-gray-11 text-sm">{subtitle}</span>- </div>+ <SessionStartupStatus executionTarget={executionTarget} phase={phase} /></div>);}diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionStartupStatus.stories.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionStartupStatus.stories.tsxnew file mode 100644index 000000000000..f434ecd92066--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionStartupStatus.stories.tsx@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PendingChatView } from "./PendingChatView";+import { SessionStartupStatus } from "./SessionStartupStatus";++const meta = {+ title: "Sessions/Startup status",+ component: SessionStartupStatus,+ parameters: { layout: "centered" },+ args: { executionTarget: "local" },+} satisfies Meta<typeof SessionStartupStatus>;++export default meta;+type Story = StoryObj<typeof meta>;++export const StartingAgent: Story = {};+export const RunningSetup: Story = { args: { phase: "setup_hooks" } };+export const Cloud: Story = { args: { executionTarget: "cloud" } };++export const PendingWorktree: Story = {+ args: { phase: "setup_hooks" },+ parameters: { layout: "fullscreen" },+ render: (args) => (+ <div className="relative h-screen min-h-[420px] w-full bg-background">+ <PendingChatView+ content="Add keyboard navigation to the project list."+ executionTarget={args.executionTarget}+ phase={args.phase}+ />+ </div>+ ),+};diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionStartupStatus.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionStartupStatus.tsxnew file mode 100644index 000000000000..7baadb6458a3--- /dev/null+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionStartupStatus.tsx@@ -0,0 +1,25 @@+import type { SessionStartupPhase } from "@posthog/core/sessions/sessionStartup";+import { Spinner } from "@posthog/ui/primitives/Spinner";++export interface SessionStartupStatusProps {+ executionTarget: "cloud" | "local";+ phase?: SessionStartupPhase;+}++export function SessionStartupStatus({+ executionTarget,+ phase,+}: SessionStartupStatusProps) {+ const isSetup = executionTarget === "local" && phase === "setup_hooks";+ const title = isSetup+ ? "Running repository setup"+ : executionTarget === "local"+ ? "Starting local agent"+ : "Starting cloud agent";+ return (+ <output className="flex items-center gap-2 text-gray-11 text-sm">+ <Spinner aria-hidden size="sm" className="shrink-0 text-accent-11" />+ <span>{title}</span>+ </output>+ );+}diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsxindex 325c0e706fa8..781b4cdcb63c 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx@@ -72,6 +72,7 @@ import {useModelConfigOptionForTask,usePendingPermissionsForTask,useSessionSelector,+ useSessionStore,useThoughtLevelConfigOptionForTask,} from "@posthog/ui/features/sessions/sessionStore";import {@@ -200,6 +201,9 @@ export function SessionView({const olderHistoryCursor = useSessionSelector(taskId, (session) =>isCloud ? (session?.transcriptWindowStart ?? 0) : 0,);+ const startupPhase = useSessionStore((state) =>+ taskId ? state.startingTaskIds[taskId]?.phase : undefined,+ );const isLoadingOlderHistory = useSessionSelector(taskId,(session) => session?.isLoadingOlderTranscript ?? false,@@ -680,6 +684,8 @@ export function SessionView({) : isInitializing ? (pendingTaskPrompt?.promptText ? (<PendingChatView+ executionTarget={isCloud ? "cloud" : "local"}+ phase={startupPhase}content={pendingTaskPrompt.contentXml ?? pendingTaskPrompt.promptText}@@ -687,6 +693,7 @@ export function SessionView({/>) : (<SessionInitializingView+ phase={startupPhase}executionTarget={isCloud ? "cloud" : "local"}/>)diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex dc47f780a2da..aeeb0040bd97 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -9998,6 +9998,7 @@ describe("SessionService", () => {it("does not restore persisted options unsupported by the resumed session", async () => {const service = getSessionService();+ mockTrpcAgent.setConfigOption.mutate.mockResolvedValue(undefined);const modelOption: SessionConfigOption = {id: "model",name: "Model",@@ -10246,13 +10247,13 @@ describe("SessionService", () => {expect(mockTrpcAgent.start.mutate).toHaveBeenCalled();});- it("handles missing session gracefully", async () => {+ it("rejects a retry when no session remains", async () => {const service = getSessionService();mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(undefined);await expect(service.clearSessionError("task-123", "/repo"),- ).resolves.not.toThrow();+ ).rejects.toThrow("Failed to reconnect to session");});});