: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): keep task startup in loading state (#95870)
Adam Leithbf7cf4582184
diff --git a/products/desktop/packages/core/src/canvas/threadTimeline.test.ts b/products/desktop/packages/core/src/canvas/threadTimeline.test.tsindex a3b75dfbc6b7..f14538e9208c 100644--- a/products/desktop/packages/core/src/canvas/threadTimeline.test.ts+++ b/products/desktop/packages/core/src/canvas/threadTimeline.test.ts@@ -204,6 +204,16 @@ describe("deriveThreadAgentStatus", () => {input: { hasActivity: true, hasError: true, errorTitle: "Run failed" },expected: { phase: "error", label: "Run failed" },},+ {+ name: "shows a new run loading over a stale failure",+ input: {+ hasActivity: true,+ hasError: true,+ isInitializing: true,+ errorTitle: "Run failed",+ },+ expected: { phase: "active", label: "Loading" },+ },{name: "prioritizes pending permissions over active work",input: {@@ -213,6 +223,20 @@ describe("deriveThreadAgentStatus", () => {},expected: { phase: "needs_input", label: "Needs input" },},+ {+ name: "reports startup loading before other activity",+ input: { isInitializing: true },+ expected: { phase: "active", label: "Loading" },+ },+ {+ name: "keeps startup loading ahead of prompt work",+ input: {+ hasActivity: true,+ isInitializing: true,+ isPromptPending: true,+ },+ expected: { phase: "active", label: "Loading" },+ },{name: "reports active work",input: { hasActivity: true, isPromptPending: true },diff --git a/products/desktop/packages/core/src/canvas/threadTimeline.ts b/products/desktop/packages/core/src/canvas/threadTimeline.tsindex 9ef7bfd7cdd9..0ac762f6495e 100644--- a/products/desktop/packages/core/src/canvas/threadTimeline.ts+++ b/products/desktop/packages/core/src/canvas/threadTimeline.ts@@ -106,14 +106,17 @@ export function deriveThreadAgentStatus({isPromptPending?: boolean;isInitializing?: boolean;}): ThreadAgentStatus | null {- if (!hasActivity) return null;+ if (!hasActivity && !isInitializing) return null;+ if (isInitializing) {+ return { phase: "active", label: "Loading" };+ }if (hasError || cloudStatus === "failed") {return { phase: "error", label: errorTitle ?? "Failed" };}if (pendingPermissionCount > 0) {return { phase: "needs_input", label: "Needs input" };}- if (isPromptPending || isInitializing) {+ if (isPromptPending) {return { phase: "active", label: "Working…" };}return null;diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 702368e23591..297c6b869701 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -356,7 +356,7 @@ export interface SessionTrpc {export interface ISessionStore {setSession(session: AgentSession): void;removeSession(taskRunId: string): void;- setTaskStarting?(taskId: string): void;+ setTaskStarting?(taskId: string, runId?: string): void;clearTaskStarting?(taskId: string): void;updateSession(taskRunId: string, updates: Partial<AgentSession>): void;appendEvents(@@ -1917,7 +1917,7 @@ export class SessionService {return;}if (task.latest_run?.environment !== "cloud") {- this.d.store.setTaskStarting?.(taskId);+ this.d.store.setTaskStarting?.(taskId, task.latest_run?.id);}if (existingSession?.status === "connecting") {this.d.log.info("Session already in connecting state", { taskId });@@ -2204,6 +2204,9 @@ export class SessionService {// previous in-memory events when the log read produced nothing.session.events =events.length === 0 && previous?.events.length ? previous.events : events;+ if (hasSessionPromptEvent(session.events)) {+ session.firstPromptForRunId = taskRunId;+ }if (logUrl) {session.logUrl = logUrl;}@@ -3424,11 +3427,19 @@ export class SessionService {} else if (kind === "output") turnTally.agentOutputEvents += 1;}if (isJsonRpcRequest(msg) && msg.method === "session/prompt") {+ const promptSession = this.d.store.getSessions()[taskRunId];+ const promptPosition = getStoredLogEventPosition(acpMsg);+ const promptBelongsToRun = promptSession?.isCloud+ ? promptPosition?.taskRunId === taskRunId+ : true;this.d.store.updateSession(taskRunId, {isPromptPending: true,promptStartedAt: acpMsg.ts,pausedDurationMs: 0,currentPromptId: msg.id,+ ...(promptBelongsToRun+ ? { firstPromptForRunId: taskRunId }+ : undefined),});this.liveTurnContent.set(taskRunId, {startedAtTs: acpMsg.ts,@@ -3436,7 +3447,6 @@ export class SessionService {agentOutputEvents: 0,agentText: "",});- const promptSession = this.d.store.getSessions()[taskRunId];if (promptSession?.isCloud) {this.cloudRunIdleTracker.markBusy(promptSession);if (promptSession.agentIdleForRunId) {@@ -5339,6 +5349,7 @@ export class SessionService {throw new Error("Failed to create resume run");}+ this.d.store.setTaskStarting?.(session.taskId, newRun.id);this.supersededRunIds.add(session.taskRunId);while (this.supersededRunIds.size > MAX_SUPERSEDED_RUN_IDS) {const oldest = this.supersededRunIds.values().next().value;@@ -5354,6 +5365,10 @@ export class SessionService {);newSession.status = "disconnected";newSession.isCloud = true;+ newSession.resumeAncestorRunIds = [+ ...(session.resumeAncestorRunIds ?? []),+ session.taskRunId,+ ];newSession.isPromptPending = true;newSession.promptStartedAt = Date.now();newSession.events = [...session.events];@@ -6454,6 +6469,13 @@ export class SessionService {isTaskAuthor = true,): () => void {const taskRunId = runId;+ const watchedSession = this.d.store.getSessionByTaskId(taskId);+ if (+ !isTerminalStatus(runStatus) &&+ watchedSession?.firstPromptForRunId !== taskRunId+ ) {+ this.d.store.setTaskStarting?.(taskId, taskRunId);+ }const persistedConfigOptions = this.d.getPersistedConfigOptions(taskRunId);const persistedAdapter = this.d.adapterStore.getAdapter(taskRunId);const buildInitialConfigOptions = (@@ -6646,6 +6668,10 @@ export class SessionService {session.status = "disconnected";session.isCloud = true;session.isTaskAuthor = isTaskAuthor;+ session.resumeAncestorRunIds =+ typeof runState?.resume_from_run_id === "string"+ ? [runState.resume_from_run_id]+ : undefined;session.adapter = adapter;session.configOptions = buildInitialConfigOptions(initialMode,@@ -7013,6 +7039,37 @@ export class SessionService {}}+ private async runPromptExistsBefore(+ client: SessionLogsClient,+ taskId: string,+ taskRunId: string,+ endOffset: number,+ ): Promise<boolean> {+ try {+ let offset = 0;+ const scanEnd = Math.min(endOffset, CLOUD_HYDRATION_MAX_ENTRIES);+ while (offset < scanEnd) {+ const page = await client.getTaskRunSessionLogsPage(taskId, taskRunId, {+ limit: Math.min(SESSION_LOGS_MAX_PAGE_SIZE, scanEnd - offset),+ offset,+ });+ if (page.entries.length === 0) return false;+ if (hasSessionPromptEvent(convertStoredEntriesToEvents(page.entries))) {+ return true;+ }+ offset += page.entries.length;+ }+ } catch (error) {+ this.d.log.warn("Cloud prompt history check failed", {+ taskId,+ taskRunId,+ endOffset,+ error,+ });+ }+ return false;+ }+/*** A one-entry probe learns the chain total without downloading a page an* oversized log would throw away, then only the newest@@ -7175,6 +7232,7 @@ export class SessionService {let liveStreamLineCount: number;let resumeLeafEntryStartIndex: number | undefined;let transcriptWindow: ChainTranscriptWindow | null = null;+ let hasPromptBeforeWindow = false;// How many entries a capped fetch dropped off the front of rawEntries on// paths that produce no window. The stream cursors count from the start of// the chain, and the engine's own totals still include those entries, so@@ -7323,14 +7381,15 @@ export class SessionService {liveStreamLineCount = local.totalLineCount;} else {const authStatus = await this.getAuthCredentialsStatus();- const window =- authStatus.kind === "ready"- ? await this.fetchChainTranscriptWindow(- authStatus.auth.client,- taskId,- taskRunId,- )- : null;+ const sessionLogsClient =+ authStatus.kind === "ready" ? authStatus.auth.client : null;+ const window = sessionLogsClient+ ? await this.fetchChainTranscriptWindow(+ sessionLogsClient,+ taskId,+ taskRunId,+ )+ : null;// An empty persisted chain can trail an S3 log that already has// entries (persistence lag), so only a non-empty window short-circuits// the full read.@@ -7338,6 +7397,14 @@ export class SessionService {transcriptWindow = window;rawEntries = window.entries;liveStreamLineCount = window.chainTotal;+ if (sessionLogsClient && window.windowStart > 0) {+ hasPromptBeforeWindow = await this.runPromptExistsBefore(+ sessionLogsClient,+ taskId,+ taskRunId,+ window.windowStart,+ );+ }} else {const parsed = await this.fetchSessionLogs(logUrl, taskRunId);rawEntries = parsed.rawEntries;@@ -7388,9 +7455,21 @@ export class SessionService {);}}+ const hasCurrentRunOutput = events.some((event) => {+ const position = getStoredLogEventPosition(event);+ return (+ (!isResumeRun || position?.taskRunId === taskRunId) &&+ classifyTurnEventKind(event.message) !== "other"+ );+ });const hasCurrentRunUserPrompt = isResumeRun? hasSessionPromptEventForTaskRun(events, taskRunId)- : hasSessionPromptEvent(events);+ : hasPromptBeforeWindow || hasSessionPromptEvent(events);+ if (hasCurrentRunUserPrompt || hasCurrentRunOutput) {+ this.d.store.updateSession(taskRunId, {+ firstPromptForRunId: taskRunId,+ });+ }// A reload loses the in-memory placeholder; restore it from the resume// state or initial task description until the active run records its prompt.@@ -8024,6 +8103,10 @@ export class SessionService {this.d.store.setTaskStarting?.(taskId);}+ public clearVisibleTaskStarting(taskId: string): void {+ this.d.store.clearTaskStarting?.(taskId);+ }+private clearTaskCreationInFlight(taskId: string): void {this.taskCreationMarks.delete(taskId);this.d.store.clearTaskStarting?.(taskId);@@ -8035,7 +8118,7 @@ export class SessionService {const expired =Date.now() - markedAt > SessionService.TASK_CREATION_IN_FLIGHT_TTL_MS;if (expired) {- this.clearTaskCreationInFlight(taskId);+ this.taskCreationMarks.delete(taskId);return false;}return true;diff --git a/products/desktop/packages/core/src/sessions/sessionServiceRecovery.test.ts b/products/desktop/packages/core/src/sessions/sessionServiceRecovery.test.tsindex 9c0d86226b2b..3f006650922c 100644--- a/products/desktop/packages/core/src/sessions/sessionServiceRecovery.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionServiceRecovery.test.ts@@ -177,7 +177,7 @@ describe("SessionService run-less local task recovery", () => {await service.connectToTask({ task, repoPath: "/repo" });- expect(store.setTaskStarting).toHaveBeenCalledWith(task.id);+ expect(store.setTaskStarting).toHaveBeenCalledWith(task.id, undefined);expect(store.clearTaskStarting).not.toHaveBeenCalled();const connectToTask = vidiff --git a/products/desktop/packages/core/src/sessions/sessionStore.ts b/products/desktop/packages/core/src/sessions/sessionStore.tsindex 0338810b1298..c5954742dd90 100644--- a/products/desktop/packages/core/src/sessions/sessionStore.ts+++ b/products/desktop/packages/core/src/sessions/sessionStore.ts@@ -26,7 +26,7 @@ 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, true>;+ startingTaskIds: Record<string, { previousRunId?: string; runId?: string }>;}export const sessionStore = createStore<SessionState>()(@@ -37,6 +37,15 @@ export const sessionStore = createStore<SessionState>()(})),);+function clearMatchingStartingTask(+ state: SessionState,+ session: AgentSession,+): void {+ if (state.startingTaskIds[session.taskId]?.runId === session.taskRunId) {+ delete state.startingTaskIds[session.taskId];+ }+}+/*** How many messages to drain off the head of a queue, honoring both options:* `stopAtEdited` caps at the in-place edit boundary (nothing from the message@@ -95,9 +104,39 @@ export const sessionStoreSetters = {delete state.sessions[existingTaskRunId];}- state.sessions[session.taskRunId] = session;+ const existingSession =+ existingTaskRunId === session.taskRunId+ ? state.sessions[session.taskRunId]+ : undefined;+ state.sessions[session.taskRunId] = {+ ...session,+ ...(existingSession?.firstPromptForRunId === session.taskRunId+ ? { firstPromptForRunId: session.taskRunId }+ : {}),+ ...(existingSession?.resumeAncestorRunIds &&+ !session.resumeAncestorRunIds+ ? { resumeAncestorRunIds: existingSession.resumeAncestorRunIds }+ : {}),+ };state.taskIdIndex[session.taskId] = session.taskRunId;- delete state.startingTaskIds[session.taskId];+ const startingTask = state.startingTaskIds[session.taskId];+ if (+ startingTask &&+ !startingTask.runId &&+ startingTask.previousRunId !== session.taskRunId+ ) {+ startingTask.runId = session.taskRunId;+ }+ const storedSession = state.sessions[session.taskRunId];+ if (+ storedSession.firstPromptForRunId === session.taskRunId ||+ storedSession.status === "error" ||+ (storedSession.status === "disconnected" &&+ !!storedSession.errorMessage) ||+ isTerminalStatus(storedSession.cloudStatus)+ ) {+ clearMatchingStartingTask(state, storedSession);+ }});},@@ -112,9 +151,17 @@ export const sessionStoreSetters = {});},- setTaskStarting: (taskId: string) => {+ setTaskStarting: (taskId: string, runId?: string) => {sessionStore.setState((state) => {- state.startingTaskIds[taskId] = true;+ const marker = state.startingTaskIds[taskId];+ if (marker) {+ if (runId) marker.runId = runId;+ return;+ }+ state.startingTaskIds[taskId] = {+ previousRunId: state.taskIdIndex[taskId],+ runId,+ };});},@@ -126,8 +173,15 @@ export const sessionStoreSetters = {updateSession: (taskRunId: string, updates: Partial<AgentSession>) => {sessionStore.setState((state) => {- if (state.sessions[taskRunId]) {- Object.assign(state.sessions[taskRunId], updates);+ const session = state.sessions[taskRunId];+ if (!session) return;+ Object.assign(session, updates);+ if (+ updates.firstPromptForRunId === taskRunId ||+ updates.status === "error" ||+ (updates.status === "disconnected" && !!updates.errorMessage)+ ) {+ clearMatchingStartingTask(state, session);}});},@@ -219,6 +273,9 @@ export const sessionStoreSetters = {if (fields.errorMessage !== undefined)session.cloudErrorMessage = fields.errorMessage;if (fields.branch !== undefined) session.cloudBranch = fields.branch;+ if (fields.status !== undefined && isTerminalStatus(fields.status)) {+ clearMatchingStartingTask(state, session);+ }});},diff --git a/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts b/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.tsindex 4e37a235d63f..41d488581c52 100644--- a/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionStoreEviction.test.ts@@ -13,6 +13,7 @@ function seedWithEvents() {messageQueue: [],pendingPermissions: new Map(),status: "disconnected",+ firstPromptForRunId: RUN,} as unknown as AgentSession);sessionStoreSetters.appendEvents(RUN,@@ -24,7 +25,7 @@ function seedWithEvents() {afterEach(() => sessionStoreSetters.removeSession(RUN));describe("evictEvents / restoreEvents", () => {- it("clears a starting marker when the session arrives", () => {+ it("keeps the starting marker until the first prompt arrives", () => {sessionStoreSetters.setTaskStarting(TASK);sessionStoreSetters.setSession({@@ -36,6 +37,51 @@ describe("evictEvents / restoreEvents", () => {status: "connected",} as unknown as AgentSession);+ expect(sessionStore.getState().startingTaskIds[TASK]).toBeDefined();++ sessionStoreSetters.updateSession(RUN, { firstPromptForRunId: RUN });+ expect(sessionStore.getState().startingTaskIds[TASK]).toBeUndefined();+ });++ it("does not let an old run clear a successor startup marker", () => {+ seedWithEvents();+ sessionStoreSetters.setTaskStarting(TASK);++ sessionStoreSetters.updateCloudStatus(RUN, { status: "failed" });++ expect(sessionStore.getState().startingTaskIds[TASK]).toBeDefined();+ });++ it.each([+ [+ "a session error",+ () => sessionStoreSetters.updateSession(RUN, { status: "error" }),+ ],+ [+ "an offline disconnect",+ () =>+ sessionStoreSetters.updateSession(RUN, {+ status: "disconnected",+ errorMessage: "Offline",+ }),+ ],+ [+ "a terminal cloud status",+ () => sessionStoreSetters.updateCloudStatus(RUN, { status: "failed" }),+ ],+ ])("clears the starting marker after %s", (_name, finishStartup) => {+ sessionStoreSetters.setTaskStarting(TASK, RUN);+ sessionStoreSetters.setSession({+ taskRunId: RUN,+ taskId: TASK,+ events: [],+ messageQueue: [],+ pendingPermissions: new Map(),+ status: "connected",+ } as unknown as AgentSession);++ finishStartup();+expect(sessionStore.getState().startingTaskIds[TASK]).toBeUndefined();});@@ -48,6 +94,7 @@ describe("evictEvents / restoreEvents", () => {const s = sessionStore.getState().sessions[RUN];expect(s.events).toHaveLength(0);expect(s.processedLineCount).toBe(0);+ expect(s.firstPromptForRunId).toBe(RUN);});it("restoreEvents refills the transcript and freezes each event", () => {@@ -63,9 +110,30 @@ describe("evictEvents / restoreEvents", () => {const s = sessionStore.getState().sessions[RUN];expect(s.events).toHaveLength(1);expect(s.processedLineCount).toBe(7);+ expect(s.firstPromptForRunId).toBe(RUN);expect(Object.isFrozen(s.events[0])).toBe(true);});+ it("preserves run lifecycle facts when the same session is replaced", () => {+ seedWithEvents();+ sessionStoreSetters.updateSession(RUN, {+ resumeAncestorRunIds: ["ancestor-run"],+ });++ sessionStoreSetters.setSession({+ taskRunId: RUN,+ taskId: TASK,+ events: [],+ messageQueue: [],+ pendingPermissions: new Map(),+ status: "connected",+ } as unknown as AgentSession);++ const session = sessionStore.getState().sessions[RUN];+ expect(session.firstPromptForRunId).toBe(RUN);+ expect(session.resumeAncestorRunIds).toEqual(["ancestor-run"]);+ });+it.each([["evictEvents", () => sessionStoreSetters.evictEvents(RUN)],[diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts b/products/desktop/packages/core/src/sessions/sessionViewState.test.tsindex 626679b47afe..bbec248e6af0 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.test.ts@@ -46,8 +46,8 @@ function makeSession(}describe("deriveSessionViewState", () => {- it("opens the live cloud chat as soon as the initial prompt is seeded", () => {- const session = makeSession("queued");+ it("keeps the loading view through optimistic prompts and setup events", () => {+ const session = makeSession("in_progress");session.optimisticItems = [{id: "initial-prompt",@@ -57,9 +57,30 @@ describe("deriveSessionViewState", () => {pinToTop: true,},];+ session.events = [+ {+ type: "acp_message",+ ts: 2,+ message: {+ jsonrpc: "2.0",+ method: "_posthog/progress",+ params: {},+ },+ },+ ];expect(- deriveSessionViewState(session, makeTask("queued"), null, true)+ deriveSessionViewState(session, makeTask("in_progress"), null, true)+ .isInitializing,+ ).toBe(true);+ });++ it("opens the live cloud chat after the active run sends its prompt", () => {+ const session = makeSession("in_progress");+ session.firstPromptForRunId = session.taskRunId;++ expect(+ deriveSessionViewState(session, makeTask("in_progress"), null, true).isInitializing,).toBe(false);});@@ -93,36 +114,115 @@ describe("deriveSessionViewState", () => {});it("uses the task status when the session belongs to an older run", () => {+ const oldSession = makeSession("completed", "old-run");+ oldSession.status = "error";+ oldSession.firstPromptForRunId = "old-run";+const state = deriveSessionViewState(- makeSession("completed", "old-run"),+ oldSession,makeTask("in_progress", "new-run"),null,true,+ true,);expect(state.cloudStatus).toBe("in_progress");expect(state.isCloudRunNotTerminal).toBe(true);+ expect(state.hasError).toBe(false);+ expect(state.isInitializing).toBe(true);+ });++ it("uses a started session while task metadata still names the old run", () => {+ const session = makeSession("in_progress", "new-run");+ session.firstPromptForRunId = "new-run";+ session.resumeAncestorRunIds = ["older-run", "old-run"];++ const state = deriveSessionViewState(+ session,+ makeTask("failed", "old-run"),+ null,+ true,+ );++ expect(state.cloudStatus).toBe("in_progress");+ expect(state.isCloudRunTerminal).toBe(false);+ expect(state.isInitializing).toBe(false);+ });++ it("uses newer task metadata over an unrelated old session", () => {+ const session = makeSession("completed", "old-run");+ session.firstPromptForRunId = "old-run";++ const state = deriveSessionViewState(+ session,+ makeTask("in_progress", "new-run"),+ null,+ true,+ );++ expect(state.cloudStatus).toBe("in_progress");+ expect(state.isInitializing).toBe(true);});- it.each([- { isHydratingTranscript: true, expected: true },- { isHydratingTranscript: undefined, expected: false },- ])(- "shows an empty terminal thread as initializing only while its transcript hydrates (hydrating: $isHydratingTranscript)",- ({ isHydratingTranscript, expected }) => {- const session = makeSession("completed");- session.isHydratingTranscript = isHydratingTranscript;-- const state = deriveSessionViewState(- session,- makeTask("completed"),- null,- true,- );-- expect(state.isInitializing).toBe(expected);- },- );+ it("shows loading immediately when a new run starts from a terminal task", () => {+ const session = makeSession("failed");+ session.status = "error";++ const state = deriveSessionViewState(+ session,+ makeTask("failed"),+ null,+ true,+ true,+ );++ expect(state.isInitializing).toBe(true);+ });++ it("does not restore startup loading while a terminal transcript hydrates", () => {+ const session = makeSession("completed");+ session.isHydratingTranscript = true;++ const state = deriveSessionViewState(+ session,+ makeTask("completed"),+ null,+ true,+ );++ expect(state.isInitializing).toBe(false);+ });++ it("shows loading while a local session reconnects after reload", () => {+ const task = makeTask("in_progress");+ if (task.latest_run) {+ task.latest_run.environment = "local";+ }++ expect(+ deriveSessionViewState(undefined, task, null, false).isInitializing,+ ).toBe(true);+ });++ it("keeps a local session loading until its first prompt", () => {+ const task = makeTask("in_progress");+ if (task.latest_run) {+ task.latest_run.environment = "local";+ }+ const session = makeSession("in_progress");+ session.isCloud = false;+ session.status = "connecting";++ expect(+ deriveSessionViewState(session, task, null, false).isInitializing,+ ).toBe(true);++ session.status = "connected";+ session.firstPromptForRunId = session.taskRunId;+ expect(+ deriveSessionViewState(session, task, null, false).isInitializing,+ ).toBe(false);+ });it("treats not_started as a non-terminal cloud state", () => {const state = deriveSessionViewState(diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.ts b/products/desktop/packages/core/src/sessions/sessionViewState.tsindex b68a51122f46..4e6f4723f4b8 100644--- a/products/desktop/packages/core/src/sessions/sessionViewState.ts+++ b/products/desktop/packages/core/src/sessions/sessionViewState.ts@@ -23,20 +23,89 @@ export interface SessionViewState {errorRetryable: boolean | undefined;}+export interface SessionLifecycleState {+ isCloud: boolean;+ isCloudRunNotTerminal: boolean;+ isCloudRunTerminal: boolean;+ cloudStatus: TaskRunStatus | null;+ hasError: boolean;+ isInitializing: boolean;+}++export function deriveSessionLifecycleState(+ session: AgentSession | undefined,+ task: Task,+ isCloud: boolean,+ isTaskStarting = false,+): SessionLifecycleState {+ const effectiveIsCloud = isCloud || session?.isCloud === true;+ const taskRunId = task.latest_run?.id;+ const preferSessionRun =+ !!taskRunId && session?.resumeAncestorRunIds?.includes(taskRunId) === true;+ const activeTaskRunId = preferSessionRun+ ? session.taskRunId+ : (taskRunId ?? session?.taskRunId);+ const sessionMatchesActiveRun =+ !!session && !!activeTaskRunId && session.taskRunId === activeTaskRunId;+ const cloudStatus = preferSessionRun+ ? (session.cloudStatus ?? null)+ : resolveEffectiveCloudStatus(task, session);+ const isCloudRunTerminal = effectiveIsCloud && isTerminalStatus(cloudStatus);+ const hasError =+ sessionMatchesActiveRun &&+ session.status === "error" &&+ !session.idleKilled;+ const hasStarted =+ sessionMatchesActiveRun && session.firstPromptForRunId === activeTaskRunId;+ const expectsInitialPrompt =+ !!session &&+ (!!task.description || !!task.latest_run?.id || session.isPromptPending);++ let isInitializing = isTaskStarting;+ if (!isTaskStarting && !hasError && !isCloudRunTerminal && !hasStarted) {+ isInitializing = effectiveIsCloud;+ if (!effectiveIsCloud) {+ isInitializing =+ !session ||+ (sessionMatchesActiveRun &&+ (session.status === "connecting" ||+ (session.status === "connected" && expectsInitialPrompt)));+ }+ }++ return {+ isCloud: effectiveIsCloud,+ isCloudRunNotTerminal: effectiveIsCloud && !isCloudRunTerminal,+ isCloudRunTerminal,+ cloudStatus,+ hasError,+ isInitializing,+ };+}+export function deriveSessionViewState(session: AgentSession | undefined,task: Task,workspace: Workspace | null,isCloud: boolean,+ isTaskStarting = false,): SessionViewState {// The live session knows it is cloud before the workspace query or `latest_run`// metadata lands, so trust either source.- const effectiveIsCloud = isCloud || session?.isCloud === true;- const cloudStatus = resolveEffectiveCloudStatus(task, session);- const isCloudRunTerminal = effectiveIsCloud && isTerminalStatus(cloudStatus);- const isCloudRunNotTerminal = effectiveIsCloud && !isCloudRunTerminal;-- const hasError = session?.status === "error" && !session?.idleKilled;+ const lifecycle = deriveSessionLifecycleState(+ session,+ task,+ isCloud,+ isTaskStarting,+ );+ const {+ isCloud: effectiveIsCloud,+ isCloudRunNotTerminal,+ isCloudRunTerminal,+ cloudStatus,+ hasError,+ isInitializing,+ } = lifecycle;const isRunning = effectiveIsCloud? !hasError: session?.status === "connected";@@ -45,31 +114,6 @@ export function deriveSessionViewState(const isPromptPending = session?.isPromptPending ?? false;const promptStartedAt = session?.promptStartedAt;- const isNewSessionWithInitialPrompt =- !task.latest_run?.id && !!task.description;- const isResumingExistingSession = !!task.latest_run?.id;- const hasOptimisticPrompt = session?.optimisticItems.some(- (item) => item.type === "user_message",- );- const isHydratingEmptyTranscript =- effectiveIsCloud &&- events.length === 0 &&- (session?.isHydratingTranscript ?? false);- const isInitializing = effectiveIsCloud- ? isHydratingEmptyTranscript ||- (!hasError &&- (!session ||- (events.length === 0 &&- !hasOptimisticPrompt &&- isCloudRunNotTerminal)))- : !session ||- (session.status === "connecting" && events.length === 0) ||- (session.status === "connected" &&- events.length === 0 &&- (isPromptPending ||- isNewSessionWithInitialPrompt ||- isResumingExistingSession));-const cloudBranch = effectiveIsCloud? (workspace?.baseBranch ?? task.latest_run?.branch ?? null): null;diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.tsindex 58b9eb60071c..bd20a90f43c6 100644--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.test.ts@@ -55,6 +55,7 @@ const sessionService = {watchCreatedCloudTask: vi.fn(),rememberInitialCloudPrompt: vi.fn(),markTaskCreationInFlight: vi.fn(),+ clearVisibleTaskStarting: vi.fn(),} as unknown as SessionService;const createTask = (overrides: Partial<Task> = {}): Task => ({@@ -1391,6 +1392,9 @@ describe("TaskCreationSaga", () => {expect(deleteTaskMock).not.toHaveBeenCalled();// Spinner is dismissed and no agent session starts without a worktree.expect(mockHost.clearProvisioning).toHaveBeenCalledWith("task-123");+ expect(sessionService.clearVisibleTaskStarting).toHaveBeenCalledWith(+ "task-123",+ );expect(sessionService.connectToTask).not.toHaveBeenCalled();// The early onTaskReady already navigated onto the task.expect(onTaskReady).toHaveBeenCalledTimes(1);@@ -1422,6 +1426,9 @@ describe("TaskCreationSaga", () => {expect(result.success).toBe(false);// Only workspace_creation is protected; an agent_session failure rolls back.expect(deleteTaskMock).toHaveBeenCalledWith("task-123");+ expect(sessionService.clearVisibleTaskStarting).toHaveBeenCalledWith(+ "task-123",+ );expect(mockHost.deleteWorkspace).toHaveBeenCalled();});diff --git a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts b/products/desktop/packages/core/src/task-detail/taskCreationSaga.tsindex 55c841800082..f6917a56015c 100644--- a/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts+++ b/products/desktop/packages/core/src/task-detail/taskCreationSaga.ts@@ -123,7 +123,16 @@ export class TaskCreationSaga extends Saga<: await this.createTask(input, warmPayload);if (!isPiRuntime) {- this.deps.sessionService.markTaskCreationInFlight(task.id);+ await this.step({+ name: "mark_task_starting",+ execute: async () => {+ this.deps.sessionService.markTaskCreationInFlight(task.id);+ return task.id;+ },+ rollback: async (markedTaskId) => {+ this.deps.sessionService.clearVisibleTaskStarting(markedTaskId);+ },+ });}if (importedClaude && input.repoPath) {@@ -221,11 +230,12 @@ export class TaskCreationSaga extends Saga<error,});this.deps.host.clearProvisioning(task.id);+ this.deps.sessionService.clearVisibleTaskStarting(task.id);if (shouldDeferLocalPiTaskReady) {this.notifyTaskReady({ task, workspace: null });}- // The in-flight mark is left to TTL-expire on purpose: this state has- // its own retry-prompt UX, and auto-recovery would race the retry.+ // Keep the recovery guard until its TTL expires so automatic recovery+ // cannot race the worktree retry.return { task, workspace: null, provisioningError };}} else if (workspaceMode === "cloud") {diff --git a/products/desktop/packages/shared/src/sessions.ts b/products/desktop/packages/shared/src/sessions.tsindex d82df90340aa..93d15397b26e 100644--- a/products/desktop/packages/shared/src/sessions.ts+++ b/products/desktop/packages/shared/src/sessions.ts@@ -71,7 +71,7 @@ export interface AgentSession {/** Absolute chain index of the first hydrated entry; >0 while older history is not loaded. */transcriptWindowStart?: number;isLoadingOlderTranscript?: boolean;- /** True while the terminal transcript is being fetched, so an empty thread shows as loading. */+ /** True while the terminal transcript is being fetched. */isHydratingTranscript?: boolean;/** Leaf-run cursor used to reconcile live cloud log updates. */processedLineCount?: number;@@ -130,6 +130,9 @@ export interface AgentSession {conversationSummary?: string;idleKilled?: boolean;agentVersion?: string;+ /** Monotonic for one session: the run that emitted its first non-steer prompt. */+ firstPromptForRunId?: string;+ resumeAncestorRunIds?: string[];agentIdleForRunId?: string;}diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsxindex 7dd009561fd3..6d49df4d8508 100644--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.test.tsx@@ -146,18 +146,29 @@ beforeEach(() => {});describe("ChannelItemRow", () => {- // The dot vocabulary in one table: what the row's leading mark says for each- // state a task can be in. Only the states a reader can act on get a voice —- // run mechanics (queued, failed) resolve to a dot that describes the work- // rather than the status: starting, live but stalled, or something to read.+ // This table keeps task state labels consistent across all task rows.it.each([["a permission prompt", { needsPermission: true }, "Needs your input"],+ [+ "a new run starting with a stale permission prompt",+ { needsPermission: true, isAgentSessionStarting: true },+ "Loading",+ ],["an agent session being created",{ isAgentSessionStarting: true },- "Starting",+ "Loading",],["a streaming agent", { isGenerating: true }, "Working"],+ [+ "a streaming agent with stale queued status",+ {+ isGenerating: true,+ taskRunStatus: "queued" as const,+ workspaceMode: "cloud" as const,+ },+ "Working",+ ],[// Persisted run status can outlive the work. Without a live stream it// must not look like unread attention that opening the session can clear.@@ -182,7 +193,7 @@ describe("ChannelItemRow", () => {// on its own, so the motion is honest."a queued cloud run",{ taskRunStatus: "queued" as const, workspaceMode: "cloud" as const },- "Starting",+ "Loading",],[// A background run's status is never advanced once it parks, so queued@@ -211,12 +222,26 @@ describe("ChannelItemRow", () => {workspaceMode: "cloud" as const,prState: "open" as const,},- "Starting",+ "Loading",+ ],+ [+ "a new run starting after a failed run",+ {+ taskRunStatus: "failed" as const,+ isAgentSessionStarting: true,+ isUnread: true,+ },+ "Loading",+ ],+ [+ "a working run with stale failed metadata",+ { taskRunStatus: "failed" as const, isGenerating: true },+ "Working",],["a broken run with unseen output",{ taskRunStatus: "failed" as const, isUnread: true },- "Unread — something to read",+ "Failed",],["a suspended task", { isSuspended: true }, "Suspended — parked"],[diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.tsindex 78475f73bb3e..55f35cd676c1 100644--- a/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useChannelTaskStatus.ts@@ -1,7 +1,11 @@import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";+import { deriveSessionLifecycleState } from "@posthog/core/sessions/sessionViewState";import type { Task } from "@posthog/shared/domain-types";import { useChannelTaskData } from "@posthog/ui/features/canvas/hooks/useChannelTaskData";-import { useTaskSessionStarting } from "@posthog/ui/features/sessions/useSession";+import {+ useSessionForTask,+ useSessionStore,+} from "@posthog/ui/features/sessions/sessionStore";import type { TaskStatusInput } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";import { useTaskPrStatus } from "@posthog/ui/features/sidebar/useTaskPrStatus";import { useWorkspace } from "@posthog/ui/features/workspace/useWorkspace";@@ -33,7 +37,16 @@ export function useTaskStatusInput(): TaskStatusInput | null {const taskData = useChannelTaskData(task);const workspace = useWorkspace(task?.id);- const isAgentSessionStarting = useTaskSessionStarting(task?.id);+ const session = useSessionForTask(task?.id);+ const isTaskStarting = useSessionStore((state) =>+ task ? state.startingTaskIds[task.id] !== undefined : false,+ );+ const isCloud =+ workspace?.mode === "cloud" || task?.latest_run?.environment === "cloud";+ const isAgentSessionStarting = task+ ? deriveSessionLifecycleState(session, task, isCloud, isTaskStarting)+ .isInitializing+ : false;const { prState, hasDiff, prUrl } = useTaskPrStatus({// An empty id is the hook's own "nothing to look up", so this asks for no// query rather than one it throws away.diff --git a/products/desktop/packages/ui/src/features/provisioning/ProvisioningView.tsx b/products/desktop/packages/ui/src/features/provisioning/ProvisioningView.tsxindex 32b48e47a1fe..3953e30d80f1 100644--- a/products/desktop/packages/ui/src/features/provisioning/ProvisioningView.tsx+++ b/products/desktop/packages/ui/src/features/provisioning/ProvisioningView.tsx@@ -1,4 +1,4 @@-import { Box, Flex, Spinner, Text } from "@radix-ui/themes";+import { Spinner } from "@posthog/ui/primitives/Spinner";import { useEffect, useRef } from "react";import { useProvisioningStore } from "./store";@@ -20,23 +20,21 @@ export function ProvisioningView({ taskId }: ProvisioningViewProps) {}, []);return (- <Box height="100%">- <Flex direction="column" height="100%" p="3" gap="2">- <Flex align="center" gap="2">- <Spinner size="1" />- <Text className="font-medium text-[13px]">- Setting up worktree...- </Text>- </Flex>- <Box className="min-h-0 flex-1 rounded-(--radius-2) border border-(--gray-a5) bg-(--color-surface)">+ <div className="h-full">+ <div className="flex h-full flex-col gap-2 p-3">+ <div className="flex items-center gap-2">+ <Spinner size={14} />+ <span className="font-medium text-[13px]">Loading</span>+ </div>+ <div className="min-h-0 flex-1 rounded-(--radius-2) border border-(--gray-a5) bg-(--color-surface)"><preref={scrollRef}className="m-0 h-full overflow-auto whitespace-pre-wrap break-all p-2 font-[var(--code-font-family)] text-(--gray-12) text-[13px]">{text}</pre>- </Box>- </Flex>- </Box>+ </div>+ </div>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/sessions/components/EmbeddedSessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/EmbeddedSessionView.tsxindex 41e137852d0a..c600e1dfadec 100644--- a/products/desktop/packages/ui/src/features/sessions/components/EmbeddedSessionView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/EmbeddedSessionView.tsx@@ -38,7 +38,6 @@ export function EmbeddedSessionView({promptStartedAt,isInitializing,cloudBranch,- cloudStatus,errorTitle,errorMessage,errorRetryable,@@ -80,7 +79,6 @@ export function EmbeddedSessionView({onNewSession={isCloud ? undefined : handleNewSession}isInitializing={isInitializing}isCloud={isCloud}- cloudStatus={cloudStatus}compactisActiveSession={isActiveSession}threadActions={threadActions?.({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 3c781b74af97..eb91be8d2b9a 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@@ -34,7 +34,6 @@ function renderPending(props: {content?: string;attachments?: { id: string; label: string }[];- statusText?: string;} = {},) {render(@@ -42,7 +41,6 @@ function renderPending(<PendingChatViewcontent={props.content ?? "Ship the login fix"}attachments={props.attachments}- statusText={props.statusText}/></Theme>,);@@ -58,16 +56,10 @@ describe("PendingChatView", () => {vi.unstubAllGlobals();});- it("renders the prompt as a chat message with the default status", () => {+ it("renders the prompt with a loading state", () => {renderPending();expect(screen.getByText("Ship the login fix")).toBeInTheDocument();- expect(screen.getByText("Starting task...")).toBeInTheDocument();- });-- it("shows the live run status in place of the default line", () => {- renderPending({ statusText: "Starting the sandbox…" });- expect(screen.getByText("Starting the sandbox…")).toBeInTheDocument();- expect(screen.queryByText("Starting task...")).not.toBeInTheDocument();+ expect(screen.getByText("Loading")).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 df3612c2674f..31343fbf8a72 100644--- a/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/PendingChatView.tsx@@ -1,4 +1,3 @@-import { Brain } from "@phosphor-icons/react";import {ChatBubble,ChatBubbleContent,@@ -14,6 +13,7 @@ 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";interface PendingChatViewProps {/**@@ -22,13 +22,11 @@ interface PendingChatViewProps {*/content: string;attachments?: UserMessageAttachment[];- statusText?: string;}export function PendingChatView({content,attachments,- statusText,}: PendingChatViewProps) {return (<div className="absolute inset-0 flex flex-col bg-background">@@ -59,10 +57,8 @@ export function PendingChatView({className="mx-auto flex w-full items-center gap-2 px-2.5"style={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}>- <Brain size={12} className="ph-pulse text-accent-11" />- <span className="text-[13px] text-accent-11">- {statusText ?? "Starting task..."}- </span>+ <Spinner size={12} className="text-accent-11" />+ <span className="text-[13px] text-accent-11">Loading</span></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 211a7b542584..50c22be8f183 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@@ -11,39 +11,30 @@ describe("SessionInitializingView", () => {it.each([{executionTarget: "local" as const,- heading: "Starting Pi…",subtitle: "Connecting to Pi on this device.",},{executionTarget: "cloud" as const,- heading: "Getting things ready…",- subtitle: "Connecting to your cloud runner.",- },- {- executionTarget: "cloud" as const,- cloudStatus: "in_progress" as const,- heading: "Starting the sandbox…",subtitle: "Connecting to your cloud runner.",},])(- "shows $executionTarget connection copy",- ({ executionTarget, cloudStatus, heading, subtitle }) => {+ "shows Loading through $executionTarget startup",+ ({ executionTarget, subtitle }) => {vi.useFakeTimers();render(<Theme>- <SessionInitializingView- executionTarget={executionTarget}- cloudStatus={cloudStatus}- />+ <SessionInitializingView executionTarget={executionTarget} /></Theme>,);+ expect(screen.getByText("Loading")).toBeInTheDocument();+act(() => {vi.advanceTimersByTime(2000);});- expect(screen.getByText(heading)).toBeInTheDocument();+ expect(screen.getByText("Loading")).toBeInTheDocument();expect(screen.getByText(subtitle)).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 e2323a886421..ac848960bb84 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionInitializingView.tsx@@ -1,59 +1,22 @@-import type { TaskRunStatus } from "@posthog/shared/domain-types";import { Spinner } from "@posthog/ui/primitives/Spinner";-import { Flex, Text } from "@radix-ui/themes";import { useEffect, useState } from "react";import zenHedgehog from "../../../assets/images/zen.png";interface SessionInitializingViewProps {executionTarget: "cloud" | "local";- cloudStatus?: TaskRunStatus | null;- heading?: string;- subtitle?: string;}const REVEAL_DELAY_MS = 2000;-export function sessionInitializingCopy(- executionTarget: "cloud" | "local",- cloudStatus: TaskRunStatus | null | undefined,-): { heading: string; subtitle: string } {- if (executionTarget === "local") {- return {- heading: "Starting Pi…",- subtitle: "Connecting to Pi on this device.",- };- }-- switch (cloudStatus) {- case "queued":- return {- heading: "Waiting in the queue…",- subtitle: "Reserving a cloud sandbox — this can take a few seconds.",- };- case "in_progress":- return {- heading: "Starting the sandbox…",- subtitle: "Connecting to your cloud runner.",- };- default:- return {- heading: "Getting things ready…",- subtitle: "Connecting to your cloud runner.",- };- }-}-export function SessionInitializingView({executionTarget,- cloudStatus,- heading,- subtitle,}: SessionInitializingViewProps) {- const copy = sessionInitializingCopy(executionTarget, cloudStatus);- const visibleHeading = heading ?? copy.heading;- const visibleSubtitle = subtitle ?? copy.subtitle;-+ const subtitle =+ executionTarget === "local"+ ? "Connecting to Pi on this device."+ : "Connecting to your cloud runner.";const [revealed, setRevealed] = useState(false);+useEffect(() => {const timer = setTimeout(() => setRevealed(true), REVEAL_DELAY_MS);return () => clearTimeout(timer);@@ -61,36 +24,25 @@ export function SessionInitializingView({if (!revealed) {return (- <Flex- align="center"- justify="center"- className="absolute inset-0 bg-background"- >- <Spinner size={32} className="text-gray-9" />- </Flex>+ <div className="absolute inset-0 flex items-center justify-center gap-2 bg-background">+ <Spinner size={16} className="text-gray-9" />+ <span className="font-medium text-base">Loading</span>+ </div>);}return (- <Flex- align="center"- justify="center"- direction="column"- gap="5"- className="absolute inset-0 bg-background"- >+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-5 bg-background"><div className="zen-float"><img src={zenHedgehog} alt="" className="block w-[160px]" /></div>- <Flex direction="column" align="center" gap="2">- <Flex align="center" gap="2">+ <div className="flex flex-col items-center gap-2">+ <div className="flex items-center gap-2"><Spinner size={16} className="text-gray-9" />- <Text className="font-medium text-base">{visibleHeading}</Text>- </Flex>- <Text color="gray" className="text-sm">- {visibleSubtitle}- </Text>- </Flex>- </Flex>+ <span className="font-medium text-base">Loading</span>+ </div>+ <span className="text-gray-11 text-sm">{subtitle}</span>+ </div>+ </div>);}diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsxindex 8160e7c54edf..5ba1a0b7ac41 100644--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx@@ -12,7 +12,7 @@ import {} from "@posthog/core/task-detail/previewConfig";import { useService } from "@posthog/di/react";import { type AcpMessage, FAST_MODE_FLAG } from "@posthog/shared";-import type { Task, TaskRunStatus } from "@posthog/shared/domain-types";+import type { Task } from "@posthog/shared/domain-types";import {spendStopMessage,useSpendStop,@@ -48,10 +48,7 @@ import { PlanStatusBar } from "@posthog/ui/features/sessions/components/PlanStatimport { QueuedMessagesDock } from "@posthog/ui/features/sessions/components/QueuedMessagesDock";import { ReasoningLevelSelector } from "@posthog/ui/features/sessions/components/ReasoningLevelSelector";import { RawLogsView } from "@posthog/ui/features/sessions/components/raw-logs/RawLogsView";-import {- SessionInitializingView,- sessionInitializingCopy,-} from "@posthog/ui/features/sessions/components/SessionInitializingView";+import { SessionInitializingView } from "@posthog/ui/features/sessions/components/SessionInitializingView";import { SessionSummaryPanel } from "@posthog/ui/features/sessions/components/SessionSummaryPanel";import { SideQuestionCard } from "@posthog/ui/features/sessions/components/SideQuestionCard";import { SteerQueueToggle } from "@posthog/ui/features/sessions/components/SteerQueueToggle";@@ -132,7 +129,6 @@ interface SessionViewProps {onNewSession?: () => void;isInitializing?: boolean;isCloud?: boolean;- cloudStatus?: TaskRunStatus | null;slackThreadUrl?: string;compact?: boolean;isActiveSession?: boolean;@@ -169,7 +165,6 @@ export function SessionView({onNewSession,isInitializing = false,isCloud = false,- cloudStatus = null,slackThreadUrl,compact = false,isActiveSession = true,@@ -689,25 +684,11 @@ export function SessionView({pendingTaskPrompt.contentXml ?? pendingTaskPrompt.promptText}attachments={pendingTaskPrompt.attachments}- statusText={- isCloud- ? sessionInitializingCopy("cloud", cloudStatus).heading- : undefined- }/>- ) : isCloud ? (+ ) : (<SessionInitializingView- executionTarget="cloud"- cloudStatus={cloudStatus}+ executionTarget={isCloud ? "cloud" : "local"}/>- ) : (- <Flex- align="center"- justify="center"- className="absolute inset-0 bg-background"- >- <Spinner size={32} className="text-gray-9" />- </Flex>)) : (<>diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useSessionViewState.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useSessionViewState.tsindex 120809a2ea75..04b14303f18e 100644--- a/products/desktop/packages/ui/src/features/sessions/hooks/useSessionViewState.ts+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useSessionViewState.ts@@ -1,6 +1,9 @@import { deriveSessionViewState } from "@posthog/core/sessions/sessionViewState";import type { Task } from "@posthog/shared/domain-types";-import { useSessionForTask } from "@posthog/ui/features/sessions/sessionStore";+import {+ useSessionForTask,+ useSessionStore,+} from "@posthog/ui/features/sessions/sessionStore";import { useCwd } from "@posthog/ui/features/sidebar/useCwd";import { useIsCloudTask } from "@posthog/ui/features/workspace/useIsCloudTask";import { useWorkspace } from "@posthog/ui/features/workspace/useWorkspace";@@ -10,8 +13,17 @@ export function useSessionViewState(taskId: string, task: Task) {const repoPath = useCwd(taskId) ?? null;const workspace = useWorkspace(taskId);const taskIsCloud = useIsCloudTask(taskId, task);+ const isTaskStarting = useSessionStore(+ (state) => state.startingTaskIds[taskId] !== undefined,+ );- const derived = deriveSessionViewState(session, task, workspace, taskIsCloud);+ const derived = deriveSessionViewState(+ session,+ task,+ workspace,+ taskIsCloud,+ isTaskStarting,+ );return {session,diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex 46dadbf37c60..f10ff2f7c306 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -2024,7 +2024,12 @@ describe("SessionService", () => {mockTrpcLogs.readLocalLogs.query.mockResolvedValue("");const chainEntries = Array.from({ length: 12000 }, (_, i) => ({timestamp: `2024-01-01T00:00:${String(i % 60).padStart(2, "0")}Z`,- notification: { method: `entry-${i}` },+ notification: {+ jsonrpc: "2.0",+ ...(i === 2+ ? { id: 1, method: "session/prompt", params: {} }+ : { method: `entry-${i}` }),+ },}));mockAuthenticatedClient.getTaskRunSessionLogsPage.mockImplementation(async (@@ -2041,6 +2046,14 @@ describe("SessionService", () => {};},);+ mockConvertStoredEntriesToEvents.mockImplementation(+ (entries: unknown[]) =>+ entries.map((entry, index) => ({+ type: "acp_message" as const,+ ts: index,+ message: (entry as (typeof chainEntries)[number]).notification,+ })),+ );service.watchCloudTask("task-123",@@ -2067,6 +2080,10 @@ describe("SessionService", () => {}),);});+ expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(+ "run-123",+ { firstPromptForRunId: "run-123" },+ );expect(mockTrpcLogs.fetchS3Logs.query).not.toHaveBeenCalled();// The run's prompt sits behind the window, not missing; a pinned// placeholder would double it once older pages load.@@ -2947,6 +2964,7 @@ describe("SessionService", () => {},};mockConvertStoredEntriesToEvents.mockReturnValueOnce([inFlightPrompt]);+ mockHasSessionPromptEventForTaskRun.mockReturnValueOnce(true);service.watchCloudTask("task-123",@@ -2964,6 +2982,7 @@ describe("SessionService", () => {isPromptPending: true,promptStartedAt: inFlightPrompt.ts,currentPromptId: 42,+ firstPromptForRunId: "run-123",}),);});diff --git a/products/desktop/packages/ui/src/features/sessions/useSession.ts b/products/desktop/packages/ui/src/features/sessions/useSession.tsindex b67bc332cd8a..9b60affc71e2 100644--- a/products/desktop/packages/ui/src/features/sessions/useSession.ts+++ b/products/desktop/packages/ui/src/features/sessions/useSession.ts@@ -161,10 +161,3 @@ export const useSessionIsCloud = (taskId: string | undefined): boolean => {return s.sessions[taskRunId]?.isCloud ?? false;});};--export const useTaskSessionStarting = (taskId: string | undefined): boolean => {- return useSessionStore((s) => {- if (!taskId) return false;- return s.startingTaskIds[taskId] === true;- });-};diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.test.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.test.tsxindex 7a4d428491d9..b0d2304de42f 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.test.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.test.tsx@@ -8,7 +8,7 @@ const working: TaskDot = {style: "solid",pulse: false,spinner: true,- label: "Working",+ label: "Loading",};const idle: TaskDot = {@@ -19,16 +19,7 @@ const idle: TaskDot = {};describe("TaskStatusDot", () => {- // The two halves of the same constraint, and the pair is the point: the ring- // has to outgrow the column to read as a ring at all, and the column has to- // stay the plain dot's or every working row's label steps right of its- // neighbours'. Measured against a rendered plain dot rather than a hardcoded- // 8px, so retuning the vocabulary's sizes moves both marks together.- //- // jsdom lays nothing out, so this reaches the sizes the component sets and- // stops there. Whether the ring is legible at that size, and whether it is- // clipped by anything upstream, is not a claim this test makes.- it("draws the working ring larger than the column it sits in", () => {+ it("uses a standard spinner without changing the status column width", () => {render(<><TaskStatusDot dot={working} />@@ -38,12 +29,10 @@ describe("TaskStatusDot", () => {const column = screen.getByRole("img", { name: "All caught up" }).style.width;- const mark = screen.getByRole("img", { name: "Working" });- const ring = mark.firstElementChild as HTMLElement;+ const mark = screen.getByRole("img", { name: "Loading" });expect(mark.style.width).toBe(column);- expect(Number.parseFloat(ring.style.width)).toBeGreaterThan(- Number.parseFloat(column),- );+ expect(mark.firstElementChild).toHaveClass("animate-spin");+ expect(mark.querySelector("svg")).toBeInTheDocument();});});diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.tsx b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.tsxindex a27e7da40bd6..caed92a73032 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.tsx+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/TaskStatusDot.tsx@@ -16,18 +16,12 @@ import {TONE_ICON_VAR,taskBadges,} from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";-import { DotRingSpinner } from "@posthog/ui/primitives/DotRingSpinner";+import { Spinner } from "@posthog/ui/primitives/Spinner";import type { ReactElement, ReactNode } from "react";const DOT_SIZE = 8;-// Drawn at the row-icon size the rest of the app spins at, not at the dot's own-// 8px: eight dots inside an 8px box are 1.6px across, and that reads as a smudge-// rather than as something turning, which leaves the one row that is working the-// faintest mark in the list.const SPINNER_SIZE = 12;-// The box the ring is centered in and measured by. It stays the plain dot's, so-// the icon column holds one width and a working row's label lines up with its-// neighbours' — the ring's extra width spills evenly into the row's padding.+// Keep the status column stable when a dot changes to a larger spinner.const SPINNER_BOX = DOT_SIZE;// Enough to still find the dot if you look for it, not enough to count as one of// the list's live rows.@@ -81,17 +75,14 @@ function dotMark(dot: TaskDot, decorative = false): ReactElement {<span{...naming}className="relative flex shrink-0 items-center justify-center"- // The spinner draws its dots in `currentColor`, so the tone is set- // here rather than passed down.style={{color: TONE_ICON_VAR[dot.tone],width: SPINNER_BOX,height: SPINNER_BOX,}}>- <DotRingSpinner+ <Spinnersize={SPINNER_SIZE}- // Out of flow, so the box measures the dot rather than the ring.className="-translate-x-1/2 -translate-y-1/2 absolute top-1/2 left-1/2"/></span>diff --git a/products/desktop/packages/ui/src/features/sidebar/components/items/taskStatusVocabulary.ts b/products/desktop/packages/ui/src/features/sidebar/components/items/taskStatusVocabulary.tsindex 1aff5fa7d715..3897f41e3f89 100644--- a/products/desktop/packages/ui/src/features/sidebar/components/items/taskStatusVocabulary.ts+++ b/products/desktop/packages/ui/src/features/sidebar/components/items/taskStatusVocabulary.ts@@ -82,11 +82,7 @@ export interface TaskDot {style: "solid" | "hollow";/** Flashing = happening now, or wanting you now. */pulse: boolean;- /**- * Draw as the braille dots spinner instead of one dot — still dot-shaped, so- * it stays in the dot column's vocabulary, but the motion is a *cycle* rather- * than a blink, which is the honest shape for "output is arriving".- */+ /** Draw a standard spinner instead of a status dot. */spinner?: boolean;/*** Draw the dot barely there. For states that are deliberately inert — the task@@ -101,23 +97,34 @@ export interface TaskDot {* State → dot. Three things only: blue wants a decision from you, the brand* yellow is working or unread, grey is quiet.*- * Run mechanics are deliberately absent. A cloud run is magic from the outside —- * queued, claiming a sandbox, retrying, and erroring out are our problems, not- * the reader's, and a list that reports them turns every infrastructure hiccup- * into a red mark on the reader's work. So a failed run is not a state here: what- * the reader actually gets is output they haven't seen, which is `isUnread`, and- * the run's real story lives in the task detail where there's room to tell it.+ * Recoverable run mechanics stay behind one loading state. A failed run uses a+ * red mark because the loading spinner must end with a clear result.*- * A cloud run's queued is folded into working for the same reason. "Waiting on a- * sandbox" and "a sandbox is writing code" are one fact to the reader, that it's- * under way, so they share the spinner. A local run at `queued`, or any run at- * `in_progress` with nothing streaming, is not a live signal by itself: those- * persisted states can outlive the work, so neither earns an attention dot.+ * A cloud run's queued state shows the same loading spinner as other startup+ * states. A local run at `queued`, or any run at `in_progress` with nothing+ * streaming, is not a live signal by itself because those states can outlive+ * the work.** A run that has already opened a PR follows the same rule. The PR badge carries- * that story; only a visibly starting or streaming run lights the dot.+ * that story; only a visibly loading or streaming run lights the dot.*/export function taskDot(props: TaskStatusInput): TaskDot {+ // Cloud `queued` is a sandbox being claimed, and the backend leaves that+ // state by itself. A local run can remain `queued` after the agent finishes.+ const isLoadingCloudRun =+ props.taskRunStatus === "queued" &&+ props.workspaceMode === "cloud" &&+ !props.isGenerating;+ const isLoading = props.isAgentSessionStarting || isLoadingCloudRun;+ if (isLoading) {+ return {+ tone: "yellow",+ style: "solid",+ pulse: false,+ spinner: true,+ label: "Loading",+ };+ }if (props.needsPermission) {// Not flashing. Blue already reads as the one thing in the list that is// yours to answer, and a blink on top of that argues with every quiet row@@ -133,21 +140,21 @@ export function taskDot(props: TaskStatusInput): TaskDot {label: "Needs your input",};}- // Spinning means something is moving on its own: a prompt in flight, or a- // cloud run still coming up. Cloud `queued` is a sandbox being claimed, and- // the backend leaves that state by itself, so the motion is bounded. A local- // run at `queued` is not a launch: nothing advances a local run's persisted- // status, so it can sit there for hours after the agent is done with it.- const isStartingCloudRun =- props.taskRunStatus === "queued" && props.workspaceMode === "cloud";- const isStarting = props.isAgentSessionStarting || isStartingCloudRun;- if (props.isGenerating || isStarting) {+ if (props.taskRunStatus === "failed" && !props.isGenerating) {+ return {+ tone: "red",+ style: "solid",+ pulse: false,+ label: "Failed",+ };+ }+ if (props.isGenerating) {return {tone: "yellow",style: "solid",pulse: false,spinner: true,- label: props.isGenerating && !isStarting ? "Working" : "Starting",+ label: "Working",};}if (props.isUnread) {diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskLogsPanel.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskLogsPanel.tsxindex 1cc72833562d..259ed44b763c 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskLogsPanel.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskLogsPanel.tsx@@ -64,7 +64,6 @@ export function TaskLogsPanel({ taskId, task, hideInput }: TaskLogsPanelProps) {promptStartedAt,isInitializing,cloudBranch,- cloudStatus,errorTitle,errorMessage,errorRetryable,@@ -190,7 +189,6 @@ export function TaskLogsPanel({ taskId, task, hideInput }: TaskLogsPanelProps) {onNewSession={isCloud ? undefined : handleNewSession}isInitializing={isInitializing}isCloud={isCloud}- cloudStatus={cloudStatus}slackThreadUrl={slackThreadUrl}/></ErrorBoundary>