Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): isolate status views from streamed session updates (#98934)

Charles Vien63a063d15b17
diff --git a/products/desktop/docs/SESSION_SUBSCRIPTIONS.md b/products/desktop/docs/SESSION_SUBSCRIPTIONS.md
new file mode 100644
index 000000000000..4e4a3126c524
--- /dev/null
+++ b/products/desktop/docs/SESSION_SUBSCRIPTIONS.md
@@ -0,0 +1,19 @@
+# Session subscriptions
+
+Command-center tiles select status fields for their own tasks through the task-to-run index.
+Their view models do not keep transcript arrays alive.
+PR badges and the chat footer select the output or timing fields they display.
+
+Command-center tiles fold the latest stop reason incrementally, so a streaming background run costs one pass over the appended batch rather than a reverse scan of the transcript.
+
+Cloud file summaries share an incremental tool-call tracker.
+Text-only appends keep the same summary identity, and tool changes produce a new snapshot without mutating a previous result.
+The tracker rebuilds when a transcript is replaced, including a same-length log reconcile that swaps a hydrated middle in while keeping the prefix and live tail.
+The cache uses weak event keys so evicting a transcript can release its derived data.
+Inactive review panes ignore session updates and skip tool-summary work.
+
+Verification:
+
+- Append text to a displayed task and another task; status-only views must not render again.
+- Change permissions, completion, or run identity; the displayed status must update.
+- Mount two file-summary consumers and verify that they share results, including after tool updates, history replacement, a same-length reconcile, and eviction.
diff --git a/products/desktop/packages/core/src/command-center/cells.ts b/products/desktop/packages/core/src/command-center/cells.ts
index a22129cca7bd..98b81e4505e9 100644
--- a/products/desktop/packages/core/src/command-center/cells.ts
+++ b/products/desktop/packages/core/src/command-center/cells.ts
@@ -14,13 +14,47 @@ import {
deriveStatus,
deriveTaskCellStatus,
getRepoName,
+ trackLatestStopReason,
} from "./status";
+export type CommandCenterSession = Pick<
+ AgentSession,
+ | "taskRunId"
+ | "status"
+ | "cloudStatus"
+ | "isPromptPending"
+ | "pendingPermissions"
+ | "agentIdleForRunId"
+> & { lastStopReason?: string };
+
+const projectedSessions = new WeakMap<AgentSession, CommandCenterSession>();
+
+export function selectCommandCenterSession(
+ session: AgentSession | undefined,
+): CommandCenterSession | undefined {
+ if (!session) return undefined;
+ const cached = projectedSessions.get(session);
+ if (cached) return cached;
+ const projected: CommandCenterSession = {
+ taskRunId: session.taskRunId,
+ status: session.status,
+ cloudStatus: session.cloudStatus,
+ isPromptPending: session.isPromptPending,
+ pendingPermissions: session.pendingPermissions,
+ agentIdleForRunId: session.agentIdleForRunId,
+ lastStopReason: session.isPromptPending
+ ? undefined
+ : trackLatestStopReason(session.events),
+ };
+ projectedSessions.set(session, projected);
+ return projected;
+}
+
export interface CommandCenterCellData {
cellIndex: number;
taskId: string | null;
task: Task | undefined;
- session: AgentSession | undefined;
+ session: CommandCenterSession | undefined;
status: CellStatus;
repoName: string | null;
workspaceMode: WorkspaceMode | null;
@@ -35,7 +69,7 @@ export interface CommandCenterCellData {
export interface BuildCellsInput {
taskById: Map<string, Task>;
- sessionByTaskId: Map<string, AgentSession>;
+ sessionByTaskId: Map<string, CommandCenterSession>;
workspaces: Record<string, { mode: WorkspaceMode } | undefined> | undefined;
}
diff --git a/products/desktop/packages/core/src/command-center/status.test.ts b/products/desktop/packages/core/src/command-center/status.test.ts
index 8816b81391f0..99a4bc046dad 100644
--- a/products/desktop/packages/core/src/command-center/status.test.ts
+++ b/products/desktop/packages/core/src/command-center/status.test.ts
@@ -7,7 +7,9 @@ import {
deriveStatus,
deriveTaskCellStatus,
hasUnseenCompletion,
+ latestStopReason,
type SessionStatusInput,
+ trackLatestStopReason,
} from "./status";
function makeSession(
@@ -174,3 +176,63 @@ describe("buildStatusSummary", () => {
expect(summary.total).toBe(0);
});
});
+
+describe("trackLatestStopReason", () => {
+ function chunk(ts: number): AcpMessage {
+ return {
+ type: "acp_message",
+ ts,
+ message: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: { update: { sessionUpdate: "agent_message_chunk" } },
+ },
+ };
+ }
+
+ it.each([
+ {
+ name: "append",
+ next: (events: AcpMessage[]) => [...events, completedTurn("refusal", 9)],
+ },
+ {
+ name: "hydrated replacement",
+ next: (events: AcpMessage[]) => [
+ events[0],
+ completedTurn("refusal", 9),
+ events[2],
+ ],
+ },
+ { name: "truncation", next: (events: AcpMessage[]) => events.slice(0, 1) },
+ { name: "eviction", next: () => [] },
+ ])("agrees with a full scan after $name", ({ next }) => {
+ const events = [chunk(1), completedTurn("cancelled", 2), chunk(3)];
+ expect(trackLatestStopReason(events)).toBe("cancelled");
+ const changed = next(events);
+ expect(trackLatestStopReason(changed)).toBe(latestStopReason(changed));
+ });
+
+ it("visits only appended events while a transcript streams", () => {
+ let reads = 0;
+ const counted = (ts: number): AcpMessage => {
+ const { message } = chunk(ts);
+ return {
+ type: "acp_message",
+ ts,
+ get message() {
+ reads++;
+ return message;
+ },
+ };
+ };
+ const events = [completedTurn("end_turn", 1)];
+ for (let ts = 2; ts <= 200; ts++) events.push(counted(ts));
+ trackLatestStopReason(events);
+ reads = 0;
+ for (let batch = 0; batch < 5; batch++) {
+ events.push(counted(1000 + batch));
+ expect(trackLatestStopReason([...events])).toBe("end_turn");
+ }
+ expect(reads).toBe(5);
+ });
+});
diff --git a/products/desktop/packages/core/src/command-center/status.ts b/products/desktop/packages/core/src/command-center/status.ts
index f52f4ac3ad25..1098fe4d73ad 100644
--- a/products/desktop/packages/core/src/command-center/status.ts
+++ b/products/desktop/packages/core/src/command-center/status.ts
@@ -4,6 +4,7 @@ import {
parseRepository,
} from "@posthog/shared";
import type { Task, TaskRunStatus } from "@posthog/shared/domain-types";
+import { createAppendOnlyTracker } from "../sessions/appendOnlyTracker";
import {
deriveTaskRunState,
isTaskUnread,
@@ -19,26 +20,73 @@ export interface SessionStatusInput {
cloudStatus?: TaskRunStatus;
pendingPermissions: { size: number };
isPromptPending: boolean;
- events: readonly AcpMessage[];
+ events?: readonly AcpMessage[];
+ lastStopReason?: string;
}
-function latestStopReason(events: readonly AcpMessage[]): string | undefined {
+function readStopReason(event: AcpMessage): string | undefined {
+ const message = event.message;
+ if (!("result" in message)) return undefined;
+ const result = message.result;
+ if (
+ typeof result === "object" &&
+ result !== null &&
+ "stopReason" in result &&
+ typeof result.stopReason === "string"
+ ) {
+ return result.stopReason;
+ }
+ return undefined;
+}
+
+export function latestStopReason(
+ events: readonly AcpMessage[],
+): string | undefined {
for (let index = events.length - 1; index >= 0; index--) {
- const message = events[index].message;
- if (!("result" in message)) continue;
- const result = message.result;
- if (
- typeof result === "object" &&
- result !== null &&
- "stopReason" in result &&
- typeof result.stopReason === "string"
- ) {
- return result.stopReason;
- }
+ const stopReason = readStopReason(events[index]);
+ if (stopReason !== undefined) return stopReason;
}
return undefined;
}
+function createStopReasonTracker() {
+ return createAppendOnlyTracker<
+ { stopReason: string | undefined },
+ string | undefined
+ >({
+ init: () => ({ stopReason: undefined }),
+ processEvent: (state, event) => {
+ const stopReason = readStopReason(event);
+ if (stopReason !== undefined) state.stopReason = stopReason;
+ },
+ getResult: (state) => state.stopReason,
+ });
+}
+
+// Weak keys let eviction release a transcript and its derived stop reason together.
+const stopReasonTrackers = new WeakMap<
+ AcpMessage,
+ ReturnType<typeof createStopReasonTracker>
+>();
+
+/**
+ * Same answer as {@link latestStopReason}, folded incrementally so a streaming
+ * transcript costs O(appended) per batch rather than a reverse scan that walks
+ * every event back to the previous turn boundary.
+ */
+export function trackLatestStopReason(
+ events: AcpMessage[] | undefined,
+): string | undefined {
+ const first = events?.[0];
+ if (!first || !events) return undefined;
+ let tracker = stopReasonTrackers.get(first);
+ if (!tracker) {
+ tracker = createStopReasonTracker();
+ stopReasonTrackers.set(first, tracker);
+ }
+ return tracker.update(events);
+}
+
export function deriveStatus(
session: SessionStatusInput | undefined,
): CellStatus {
@@ -54,7 +102,11 @@ export function deriveStatus(
if (session.status === "connected" && session.isPromptPending)
return "running";
- if (latestStopReason(session.events) === "cancelled") return "error";
+ if (
+ (session.lastStopReason ?? latestStopReason(session.events ?? [])) ===
+ "cancelled"
+ )
+ return "error";
return "idle";
}
diff --git a/products/desktop/packages/core/src/sessions/appendOnlyTracker.ts b/products/desktop/packages/core/src/sessions/appendOnlyTracker.ts
index 0355d290ffb1..c19fe825497b 100644
--- a/products/desktop/packages/core/src/sessions/appendOnlyTracker.ts
+++ b/products/desktop/packages/core/src/sessions/appendOnlyTracker.ts
@@ -4,11 +4,12 @@ import type { AcpMessage } from "@posthog/shared";
* Folds a growing session event log into running state, visiting only the tail
* appended since the last call so streaming stays O(appended), not O(history).
*
- * An append is detected by reference identity: same-or-greater length with the
- * first and previous-boundary elements unchanged; otherwise the state is rebuilt.
- * This assumes an append-only log — a mid-array edit that keeps both ends reads
- * as an append and is missed, which is safe because the session event log only
- * ever grows.
+ * An append is detected by reference identity: the same array again, or a longer
+ * one whose first and previous-boundary elements are unchanged. Otherwise the
+ * state is rebuilt. A same-length array counts as a replacement even when both
+ * ends survive, because the cloud log reconcile swaps a middle segment for
+ * hydrated entries while retaining the leading prefix and the live tail, and
+ * folding only the tail there would drop the replaced entries for good.
*
* `processEvent` mutates `state`; `getResult` projects it, allocating a fresh
* value so a retained result never sees `state` mutate underneath it.
@@ -20,14 +21,17 @@ export function createAppendOnlyTracker<State, Result>(config: {
}) {
let state = config.init();
let processedCount = 0;
+ let eventsRef: AcpMessage[] | null = null;
let firstEventRef: AcpMessage | null = null;
let boundaryEventRef: AcpMessage | null = null;
const update = (events: AcpMessage[]): Result => {
const isAppend =
- events.length >= processedCount &&
- (processedCount === 0 || events[0] === firstEventRef) &&
- (processedCount === 0 || events[processedCount - 1] === boundaryEventRef);
+ processedCount === 0 ||
+ (events === eventsRef && events.length === processedCount) ||
+ (events.length > processedCount &&
+ events[0] === firstEventRef &&
+ events[processedCount - 1] === boundaryEventRef);
if (!isAppend) {
state = config.init();
@@ -39,6 +43,7 @@ export function createAppendOnlyTracker<State, Result>(config: {
}
processedCount = events.length;
+ eventsRef = events;
firstEventRef = events[0] ?? null;
boundaryEventRef = events[processedCount - 1] ?? null;
diff --git a/products/desktop/packages/core/src/task-detail/cloudEventSummary.test.ts b/products/desktop/packages/core/src/task-detail/cloudEventSummary.test.ts
new file mode 100644
index 000000000000..62a52f01377b
--- /dev/null
+++ b/products/desktop/packages/core/src/task-detail/cloudEventSummary.test.ts
@@ -0,0 +1,91 @@
+import type { AcpMessage } from "@posthog/shared";
+import { describe, expect, it } from "vitest";
+import {
+ buildCloudEventSummary,
+ getCloudEventSummary,
+} from "./cloudToolChanges";
+
+function update(ts: number, value: Record<string, unknown>): AcpMessage {
+ return {
+ type: "acp_message",
+ ts,
+ message: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: { update: value },
+ },
+ };
+}
+const text = (ts: number) =>
+ update(ts, {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "More text" },
+ });
+const tool = (ts: number, id: string) =>
+ update(ts, {
+ sessionUpdate: "tool_call",
+ toolCallId: id,
+ kind: "read",
+ status: "in_progress",
+ title: "Read example.ts",
+ });
+
+describe("getCloudEventSummary", () => {
+ it("shares results and preserves previous snapshots while applying only tool updates", () => {
+ const events = [text(1), tool(2, "read-1")];
+ const first = getCloudEventSummary(events);
+ expect(getCloudEventSummary(events)).toBe(first);
+ const withText = [...events, text(3)];
+ expect(getCloudEventSummary(withText)).toBe(first);
+ const updated = [
+ ...withText,
+ update(4, {
+ sessionUpdate: "tool_call_update",
+ toolCallId: "read-1",
+ status: "completed",
+ }),
+ ];
+ const second = getCloudEventSummary(updated);
+ expect(second.toolCalls.get("read-1")).toMatchObject({
+ kind: "read",
+ status: "completed",
+ title: "Read example.ts",
+ });
+ expect(first.toolCalls.get("read-1")?.status).toBe("in_progress");
+ expect(getCloudEventSummary(updated)).toBe(second);
+ });
+
+ it("keeps concurrent forked histories stable when they share the first event", () => {
+ const first = text(1);
+ const branchA = [first, tool(2, "branch-a")];
+ const branchB = [first, tool(2, "branch-b")];
+ const summaryA = getCloudEventSummary(branchA);
+ const summaryB = getCloudEventSummary(branchB);
+ expect(getCloudEventSummary(branchA)).toBe(summaryA);
+ expect(getCloudEventSummary(branchB)).toBe(summaryB);
+ expect(summaryA.toolCalls.has("branch-b")).toBe(false);
+ });
+
+ it.each(["truncate", "replace", "boundary", "reconcile", "evict"])(
+ "rebuilds after %s",
+ (change) => {
+ const events = [text(1), tool(2, "read-1"), tool(3, "read-2")];
+ getCloudEventSummary(events);
+ const changed =
+ change === "truncate"
+ ? events.slice(0, 2)
+ : change === "replace"
+ ? [text(1), tool(2, "new")]
+ : change === "boundary"
+ ? [...events.slice(0, 2), tool(3, "replacement")]
+ : // A log reconcile swaps a hydrated middle in while keeping the
+ // leading prefix and the live tail, holding the length equal.
+ change === "reconcile"
+ ? [events[0], tool(2, "hydrated"), events[2]]
+ : [];
+ expect(getCloudEventSummary(changed)).toEqual(
+ buildCloudEventSummary(changed),
+ );
+ },
+ );
+});
diff --git a/products/desktop/packages/core/src/task-detail/cloudToolChanges.ts b/products/desktop/packages/core/src/task-detail/cloudToolChanges.ts
index 479d0035b48a..c06ee5405b8c 100644
--- a/products/desktop/packages/core/src/task-detail/cloudToolChanges.ts
+++ b/products/desktop/packages/core/src/task-detail/cloudToolChanges.ts
@@ -8,6 +8,7 @@ import {
isJsonRpcNotification,
} from "@posthog/shared";
import type { ChangedFile } from "@posthog/shared/domain-types";
+import { createAppendOnlyTracker } from "../sessions/appendOnlyTracker";
function getContentText(
content: ToolCallContent[] | undefined,
@@ -189,48 +190,99 @@ export function buildCloudEventSummary(
const toolCalls = new Map<string, ParsedToolCall>();
for (const event of events) {
- const message = event.message;
- if (!isJsonRpcNotification(message)) continue;
+ const patch = readToolCallPatch(event);
+ if (patch)
+ toolCalls.set(
+ patch.toolCallId,
+ mergeToolCall(toolCalls.get(patch.toolCallId), patch),
+ );
+ }
+ return { toolCalls };
+}
- if (message.method === "session/update") {
- const params = message.params as
- | { update?: Record<string, unknown> }
- | undefined;
- const update = params?.update;
- if (!update || typeof update !== "object") continue;
+function readToolCallPatch(event: AcpMessage): ParsedToolCall | undefined {
+ const message = event.message;
+ if (!isJsonRpcNotification(message) || message.method !== "session/update")
+ return undefined;
+ const params = message.params as
+ | { update?: Record<string, unknown> }
+ | undefined;
+ const update = params?.update;
+ if (
+ !update ||
+ typeof update !== "object" ||
+ (update.sessionUpdate !== "tool_call" &&
+ update.sessionUpdate !== "tool_call_update") ||
+ typeof update.toolCallId !== "string" ||
+ !update.toolCallId
+ )
+ return undefined;
+ return {
+ toolCallId: update.toolCallId,
+ kind: typeof update.kind === "string" ? update.kind : null,
+ title: typeof update.title === "string" ? update.title : undefined,
+ status: typeof update.status === "string" ? update.status : null,
+ locations: Array.isArray(update.locations)
+ ? (update.locations as ToolCallLocation[])
+ : undefined,
+ content: Array.isArray(update.content)
+ ? (update.content as ToolCallContent[])
+ : undefined,
+ rawOutput: update.rawOutput,
+ };
+}
- const sessionUpdate = update.sessionUpdate;
- if (
- sessionUpdate !== "tool_call" &&
- sessionUpdate !== "tool_call_update"
- ) {
- continue;
+const EMPTY_SUMMARY: CloudEventSummary = { toolCalls: new Map() };
+
+function createSummaryTracker() {
+ return createAppendOnlyTracker({
+ init: () => ({
+ toolCalls: new Map<string, ParsedToolCall>(),
+ result: EMPTY_SUMMARY,
+ dirty: false,
+ }),
+ processEvent: (state, event) => {
+ const patch = readToolCallPatch(event);
+ if (!patch) return;
+ state.toolCalls.set(
+ patch.toolCallId,
+ mergeToolCall(state.toolCalls.get(patch.toolCallId), patch),
+ );
+ state.dirty = true;
+ },
+ getResult: (state) => {
+ if (state.dirty) {
+ state.result = { toolCalls: new Map(state.toolCalls) };
+ state.dirty = false;
}
+ return state.result;
+ },
+ });
+}
- const toolCallId =
- typeof update.toolCallId === "string" ? update.toolCallId : undefined;
- if (!toolCallId) continue;
-
- const patch: Partial<ParsedToolCall> = {
- toolCallId,
- kind: typeof update.kind === "string" ? update.kind : null,
- title: typeof update.title === "string" ? update.title : undefined,
- status: typeof update.status === "string" ? update.status : null,
- locations: Array.isArray(update.locations)
- ? (update.locations as ToolCallLocation[])
- : undefined,
- content: Array.isArray(update.content)
- ? (update.content as ToolCallContent[])
- : undefined,
- rawOutput: update.rawOutput,
- };
+// Weak keys let eviction release a transcript and its derived tools together.
+const summaryTrackers = new WeakMap<
+ AcpMessage,
+ ReturnType<typeof createSummaryTracker>
+>();
- const merged = mergeToolCall(toolCalls.get(toolCallId), patch);
- toolCalls.set(toolCallId, merged);
- }
- }
+const summarySnapshots = new WeakMap<AcpMessage[], CloudEventSummary>();
- return { toolCalls };
+export function getCloudEventSummary(
+ events: AcpMessage[] | undefined,
+): CloudEventSummary {
+ const first = events?.[0];
+ if (!first || !events) return EMPTY_SUMMARY;
+ const cached = summarySnapshots.get(events);
+ if (cached) return cached;
+ let tracker = summaryTrackers.get(first);
+ if (!tracker) {
+ tracker = createSummaryTracker();
+ summaryTrackers.set(first, tracker);
+ }
+ const result = tracker.update(events);
+ summarySnapshots.set(events, result);
+ return result;
}
export function extractCloudFileDiff(
diff --git a/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterData.ts b/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterData.ts
index b4ebc774cd69..c7917053b021 100644
--- a/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterData.ts
+++ b/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterData.ts
@@ -11,12 +11,11 @@ import {
import { taskActivityAt } from "@posthog/core/tasks/taskActivity";
import type { Task } from "@posthog/shared/domain-types";
import { useMemo } from "react";
-import type { AgentSession } from "../../sessions/sessionStore";
-import { useSessions } from "../../sessions/useSession";
import { useTaskViewed } from "../../sidebar/useTaskViewed";
import { useTasks } from "../../tasks/useTasks";
import { useWorkspaces } from "../../workspace/useWorkspace";
import { useCommandCenterStore } from "../commandCenterStore";
+import { useCommandCenterSessions } from "./useCommandCenterSessions";
export type CommandCenterCellData = BaseCommandCenterCellData & {
hasUnseenCompletion: boolean;
@@ -30,7 +29,7 @@ export function useCommandCenterData(): {
} {
const storeCells = useCommandCenterStore((s) => s.cells);
const { data: tasks = [] } = useTasks();
- const sessions = useSessions();
+ const sessionByTaskId = useCommandCenterSessions(storeCells);
const { data: workspaces } = useWorkspaces();
const { timestamps } = useTaskViewed();
@@ -42,16 +41,6 @@ export function useCommandCenterData(): {
return map;
}, [tasks]);
- const sessionByTaskId = useMemo(() => {
- const map = new Map<string, AgentSession>();
- for (const session of Object.values(sessions)) {
- if (session.taskId) {
- map.set(session.taskId, session);
- }
- }
- return map;
- }, [sessions]);
-
const cells = useMemo(() => {
const baseCells = buildCommandCenterCells(storeCells, {
taskById,
diff --git a/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterSessions.test.tsx b/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterSessions.test.tsx
new file mode 100644
index 000000000000..c286c385241e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterSessions.test.tsx
@@ -0,0 +1,102 @@
+import { sessionStoreSetters } from "@posthog/core/sessions/sessionStore";
+import type { AcpMessage, AgentSession } from "@posthog/shared";
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { useCommandCenterSessions } from "./useCommandCenterSessions";
+
+const TASKS = ["task-1"];
+const text: AcpMessage = {
+ type: "acp_message",
+ ts: 1,
+ message: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "Hello" },
+ },
+ },
+ },
+};
+function seed(runId: string, taskId: string): void {
+ sessionStoreSetters.setSession({
+ taskRunId: runId,
+ taskId,
+ status: "connected",
+ isPromptPending: true,
+ events: [],
+ messageQueue: [],
+ pendingPermissions: new Map(),
+ } as unknown as AgentSession);
+}
+
+afterEach(() => {
+ cleanup();
+ for (const id of ["run-1", "run-2", "run-3"])
+ sessionStoreSetters.removeSession(id);
+});
+
+describe("useCommandCenterSessions", () => {
+ it("ignores transcript appends and unrelated tasks without retaining transcript arrays", () => {
+ seed("run-1", "task-1");
+ seed("run-2", "task-2");
+ let renders = 0;
+ const { result } = renderHook(() => {
+ renders++;
+ return useCommandCenterSessions(TASKS);
+ });
+ const before = result.current;
+ const baseline = renders;
+ act(() => {
+ sessionStoreSetters.appendEvents("run-1", [text]);
+ sessionStoreSetters.appendEvents("run-2", [text]);
+ });
+ expect(renders).toBe(baseline);
+ expect(result.current).toBe(before);
+ expect(result.current.get("task-1")).not.toHaveProperty("events");
+ });
+
+ it("updates completion, cancellation, and replacement run status", () => {
+ seed("run-1", "task-1");
+ const { result } = renderHook(() => useCommandCenterSessions(TASKS));
+ act(() =>
+ sessionStoreSetters.updateSession("run-1", {
+ pendingPermissions: new Map([
+ [
+ "request-1",
+ {
+ taskRunId: "run-1",
+ receivedAt: 1,
+ toolCall: { toolCallId: "tool-1" },
+ options: [],
+ },
+ ],
+ ]),
+ }),
+ );
+ expect(result.current.get("task-1")?.pendingPermissions.size).toBe(1);
+
+ act(() =>
+ sessionStoreSetters.updateSession("run-1", { isPromptPending: false }),
+ );
+ expect(result.current.get("task-1")?.isPromptPending).toBe(false);
+ act(() =>
+ sessionStoreSetters.appendEvents("run-1", [
+ {
+ type: "acp_message",
+ ts: 2,
+ message: {
+ jsonrpc: "2.0",
+ id: 1,
+ result: { stopReason: "cancelled" },
+ },
+ },
+ ]),
+ );
+ expect(result.current.get("task-1")?.lastStopReason).toBe("cancelled");
+ act(() => seed("run-3", "task-1"));
+ expect(result.current.get("task-1")?.taskRunId).toBe("run-3");
+ expect(result.current.get("task-1")?.isPromptPending).toBe(true);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterSessions.ts b/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterSessions.ts
new file mode 100644
index 000000000000..10c8cb82a708
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/command-center/hooks/useCommandCenterSessions.ts
@@ -0,0 +1,33 @@
+import {
+ type CommandCenterSession,
+ selectCommandCenterSession,
+} from "@posthog/core/command-center/cells";
+import { useMemo } from "react";
+import { shallow } from "zustand/shallow";
+import { useSessionStore } from "../../sessions/sessionStore";
+
+export function useCommandCenterSessions(
+ taskIds: (string | null)[],
+): Map<string, CommandCenterSession> {
+ const sessions = useSessionStore(
+ (state) =>
+ taskIds.map((taskId) => {
+ const runId = taskId ? state.taskIdIndex[taskId] : undefined;
+ return selectCommandCenterSession(
+ runId ? state.sessions[runId] : undefined,
+ );
+ }),
+ (previous, next) =>
+ previous.length === next.length &&
+ previous.every((session, index) => shallow(session, next[index])),
+ );
+ return useMemo(() => {
+ const byTaskId = new Map<string, CommandCenterSession>();
+ for (let index = 0; index < taskIds.length; index++) {
+ const taskId = taskIds[index];
+ const session = sessions[index];
+ if (taskId && session) byTaskId.set(taskId, session);
+ }
+ return byTaskId;
+ }, [taskIds, sessions]);
+}
diff --git a/products/desktop/packages/ui/src/features/git-interaction/cloudPrUrl.ts b/products/desktop/packages/ui/src/features/git-interaction/cloudPrUrl.ts
index a6a942e6d109..98ad87ad1b68 100644
--- a/products/desktop/packages/ui/src/features/git-interaction/cloudPrUrl.ts
+++ b/products/desktop/packages/ui/src/features/git-interaction/cloudPrUrl.ts
@@ -4,7 +4,7 @@ import type { AgentSession } from "@posthog/ui/features/sessions/sessionStore";
export function resolveCloudPrUrls(
task: Task | undefined,
- session: AgentSession | undefined,
+ session: Pick<AgentSession, "cloudOutput"> | undefined,
): string[] {
return mergePrUrls(
readPrUrls(task?.latest_run?.output),
@@ -14,7 +14,7 @@ export function resolveCloudPrUrls(
export function resolveCloudPrSummaries(
task: Task | undefined,
- session: AgentSession | undefined,
+ session: Pick<AgentSession, "cloudOutput"> | undefined,
): Record<string, string> {
return {
...readPrSummaries(session?.cloudOutput),
@@ -24,7 +24,7 @@ export function resolveCloudPrSummaries(
export function resolveCloudPrUrl(
task: Task | undefined,
- session: AgentSession | undefined,
+ session: Pick<AgentSession, "cloudOutput"> | undefined,
): string | null {
return resolveCloudPrUrls(task, session)[0] ?? null;
}
diff --git a/products/desktop/packages/ui/src/features/git-interaction/useCloudPrUrl.ts b/products/desktop/packages/ui/src/features/git-interaction/useCloudPrUrl.ts
index 76782db0f234..3e39ce306384 100644
--- a/products/desktop/packages/ui/src/features/git-interaction/useCloudPrUrl.ts
+++ b/products/desktop/packages/ui/src/features/git-interaction/useCloudPrUrl.ts
@@ -1,4 +1,4 @@
-import { useSessionForTask } from "../sessions/useSession";
+import { useSessionSelector } from "../sessions/useSession";
import { useTasks } from "../tasks/useTasks";
import { resolveCloudPrSummaries, resolveCloudPrUrls } from "./cloudPrUrl";
@@ -10,13 +10,19 @@ export function useCloudPrUrl(taskId: string): string | null {
export function useCloudPrUrls(taskId: string): string[] {
const { data: tasks = [] } = useTasks();
const task = tasks.find((t) => t.id === taskId);
- const session = useSessionForTask(taskId);
- return resolveCloudPrUrls(task, session);
+ const cloudOutput = useSessionSelector(
+ taskId,
+ (session) => session?.cloudOutput,
+ );
+ return resolveCloudPrUrls(task, { cloudOutput });
}
export function useCloudPrSummaries(taskId: string): Record<string, string> {
const { data: tasks = [] } = useTasks();
const task = tasks.find((t) => t.id === taskId);
- const session = useSessionForTask(taskId);
- return resolveCloudPrSummaries(task, session);
+ const cloudOutput = useSessionSelector(
+ taskId,
+ (session) => session?.cloudOutput,
+ );
+ return resolveCloudPrSummaries(task, { cloudOutput });
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
index b05bfdf19036..763b706470b0 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
@@ -5,7 +5,7 @@ import { SessionStartupRow } from "@posthog/ui/features/sessions/components/Sess
import {
usePendingPermissionsForTask,
useQueuedMessagesForTask,
- useSessionForTask,
+ useSessionSelector,
} from "@posthog/ui/features/sessions/sessionStore";
import { resolvePendingPermissionVisibility } from "./pendingPermissionVisibility";
@@ -47,8 +47,10 @@ export function ChatThreadFooter({
pendingPermissions.size,
);
const queuedCount = useQueuedMessagesForTask(taskId).length;
- const session = useSessionForTask(taskId);
- const pausedDurationMs = session?.pausedDurationMs ?? 0;
+ const pausedDurationMs = useSessionSelector(
+ taskId,
+ (session) => session?.pausedDurationMs ?? 0,
+ );
return (
<div className="pt-1">
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudChangedFiles.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudChangedFiles.ts
index 9ffd6d608ddc..32a67c56f3bf 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudChangedFiles.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudChangedFiles.ts
@@ -14,7 +14,7 @@ export function useCloudChangedFiles(
isActive = true,
prUrlOverride?: string,
) {
- const cloudRunState = useCloudRunState(taskId, task);
+ const cloudRunState = useCloudRunState(taskId, task, isActive);
const prUrl = prUrlOverride ?? cloudRunState.prUrl;
const { effectiveBranch, repo, isRunActive } = cloudRunState;
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudEventSummary.test.tsx b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudEventSummary.test.tsx
new file mode 100644
index 000000000000..faae576aa815
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudEventSummary.test.tsx
@@ -0,0 +1,94 @@
+import { sessionStoreSetters } from "@posthog/core/sessions/sessionStore";
+import type { AcpMessage, AgentSession } from "@posthog/shared";
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { useCloudEventSummary } from "./useCloudEventSummary";
+
+function update(ts: number, value: Record<string, unknown>): AcpMessage {
+ return {
+ type: "acp_message",
+ ts,
+ message: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: { update: value },
+ },
+ };
+}
+afterEach(() => {
+ cleanup();
+ sessionStoreSetters.removeSession("run-1");
+});
+
+describe("useCloudEventSummary", () => {
+ it("shares snapshots across consumers, ignores text, and releases tools on eviction", () => {
+ sessionStoreSetters.setSession({
+ taskRunId: "run-1",
+ taskId: "task-1",
+ events: [],
+ messageQueue: [],
+ pendingPermissions: new Map(),
+ } as unknown as AgentSession);
+ let renders = 0;
+ const first = renderHook(() => {
+ renders++;
+ return useCloudEventSummary("task-1");
+ });
+ const second = renderHook(() => useCloudEventSummary("task-1"));
+ const baseline = renders;
+ act(() =>
+ sessionStoreSetters.appendEvents("run-1", [
+ update(1, {
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "Hello" },
+ }),
+ ]),
+ );
+ expect(renders).toBe(baseline);
+ act(() =>
+ sessionStoreSetters.appendEvents("run-1", [
+ update(2, {
+ sessionUpdate: "tool_call",
+ toolCallId: "read-1",
+ kind: "read",
+ status: "in_progress",
+ }),
+ ]),
+ );
+ expect(first.result.current.toolCalls.size).toBe(1);
+ expect(first.result.current).toBe(second.result.current);
+ act(() => sessionStoreSetters.evictEvents("run-1"));
+ expect(first.result.current.toolCalls.size).toBe(0);
+ expect(first.result.current).toBe(second.result.current);
+ });
+
+ it("skips a hidden pane and catches up when enabled", () => {
+ sessionStoreSetters.setSession({
+ taskRunId: "run-1",
+ taskId: "task-1",
+ events: [],
+ messageQueue: [],
+ pendingPermissions: new Map(),
+ } as unknown as AgentSession);
+ let enabled = false;
+ let renders = 0;
+ const { result, rerender } = renderHook(() => {
+ renders++;
+ return useCloudEventSummary("task-1", enabled);
+ });
+ const baseline = renders;
+ act(() =>
+ sessionStoreSetters.appendEvents("run-1", [
+ update(1, {
+ sessionUpdate: "tool_call",
+ toolCallId: "read-1",
+ status: "completed",
+ }),
+ ]),
+ );
+ expect(renders).toBe(baseline);
+ enabled = true;
+ rerender();
+ expect(result.current.toolCalls.size).toBe(1);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudEventSummary.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudEventSummary.ts
index 4a1d1effa779..a561752257c1 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudEventSummary.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudEventSummary.ts
@@ -1,22 +1,14 @@
import {
- buildCloudEventSummary,
type CloudEventSummary,
+ getCloudEventSummary,
} from "@posthog/core/task-detail/cloudToolChanges";
-import { useMemo } from "react";
-import { useSessionForTask } from "../../sessions/useSession";
-
-const EMPTY_SUMMARY: CloudEventSummary = {
- toolCalls: new Map(),
-};
+import { useSessionSelector } from "../../sessions/useSession";
export function useCloudEventSummary(
taskId: string,
enabled = true,
): CloudEventSummary {
- const session = useSessionForTask(enabled ? taskId : undefined);
- const events = session?.events;
- return useMemo(
- () => (events ? buildCloudEventSummary(events) : EMPTY_SUMMARY),
- [events],
+ return useSessionSelector(enabled ? taskId : undefined, (session) =>
+ getCloudEventSummary(session?.events),
);
}
diff --git a/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudRunState.ts b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudRunState.ts
index cff2f5cec040..85f706ef6eaf 100644
--- a/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudRunState.ts
+++ b/products/desktop/packages/ui/src/features/task-detail/hooks/useCloudRunState.ts
@@ -2,13 +2,14 @@ import { deriveCloudRunState } from "@posthog/core/task-detail/cloudRunState";
import { extractCloudToolChangedFiles } from "@posthog/core/task-detail/cloudToolChanges";
import type { Task } from "@posthog/shared/domain-types";
import { useMemo } from "react";
+import { shallow } from "zustand/shallow";
import { resolveCloudPrUrl } from "../../git-interaction/cloudPrUrl";
-import { useSessionForTask } from "../../sessions/useSession";
+import { useSessionSelector } from "../../sessions/useSession";
import { pickFreshestTask } from "../../tasks/taskFreshness";
import { useTasks } from "../../tasks/useTasks";
import { useCloudEventSummary } from "./useCloudEventSummary";
-export function useCloudRunState(taskId: string, task: Task) {
+export function useCloudRunState(taskId: string, task: Task, enabled = true) {
const { data: tasks = [] } = useTasks();
const freshTask = useMemo(
() =>
@@ -19,13 +20,25 @@ export function useCloudRunState(taskId: string, task: Task) {
[task, taskId, tasks],
);
- const session = useSessionForTask(taskId);
+ const session = useSessionSelector(
+ enabled ? taskId : undefined,
+ (session) =>
+ session
+ ? {
+ taskRunId: session.taskRunId,
+ cloudStatus: session.cloudStatus,
+ cloudBranch: session.cloudBranch,
+ cloudOutput: session.cloudOutput,
+ }
+ : undefined,
+ shallow,
+ );
const prUrl = resolveCloudPrUrl(freshTask, session);
const { effectiveBranch, repo, cloudStatus, isRunActive } =
deriveCloudRunState(freshTask, session, prUrl);
- const summary = useCloudEventSummary(taskId);
+ const summary = useCloudEventSummary(taskId, enabled);
const fallbackFiles = useMemo(
() => extractCloudToolChangedFiles(summary.toolCalls),
[summary],