: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): release idle pi transcripts on navigation (#98931)
Charles Vienae1d7799bba2
diff --git a/products/desktop/docs/PI_TRANSCRIPT_RESIDENCY.md b/products/desktop/docs/PI_TRANSCRIPT_RESIDENCY.mdnew file mode 100644index 000000000000..4940a813821a--- /dev/null+++ b/products/desktop/docs/PI_TRANSCRIPT_RESIDENCY.md@@ -0,0 +1,17 @@+# Pi transcript residency++Pi releases transcript events and model catalogs when a view leaves an idle session.+The next visit reloads history through the session provider, as it does for an initial visit.+Usage stats and recovery errors remain available without retaining the transcript.+Session status is released too, so the next visit shows the loading skeleton instead of an empty conversation.++Background sessions stay subscribed while a submission, turn, compaction, shell command, authentication restoration, queue, or permission request needs them.+A submission holds the session from the moment the user sends it, before the runtime reports the turn.+A cloud run stays subscribed until its status is terminal.+A queue or a permission request left behind by a finished cloud run does not hold the session, because that run can no longer act on it.+Once the remaining work finishes, the controller releases the inactive transcript.+Disconnecting all sessions also releases all stored transcripts.++The controller lifecycle tests cover reopening evicted history and keeping unfinished background work alive.+For a memory check, repeatedly open and leave completed Pi tasks and collect renderer garbage after the run.+Idle transcript retention should stay flat as the number of visited tasks grows.diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.tsindex e79343e826d4..fd58c6547685 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts@@ -87,6 +87,8 @@ function createSession(): PiSession {describe("PiSessionController", () => {it("queues concurrent MCP permission requests", async () => {const session = createSession();+ const unsubscribe = vi.fn();+ vi.mocked(session.onConversationEvent).mockReturnValue(unsubscribe);let onRequest: ((request: McpToolPermissionRequest) => void) | undefined;session.onMcpToolPermissionRequest = vi.fn((callback) => {onRequest = callback;@@ -116,6 +118,7 @@ describe("PiSessionController", () => {onRequest?.(first);onRequest?.(first);onRequest?.(second);+ controller.release("task-1");expect(controller.store.getState().sessions["task-1"]?.mcpToolPermissionRequests@@ -129,11 +132,14 @@ describe("PiSessionController", () => {taskTitle: "Fix notifications",});await controller.respondMcpToolPermission("task-1", first, "reject");+ expect(unsubscribe).not.toHaveBeenCalled();expect(controller.store.getState().sessions["task-1"]?.mcpToolPermissionRequests.has("call-2"),).toBe(true);+ await controller.respondMcpToolPermission("task-1", second, "reject");+ expect(unsubscribe).toHaveBeenCalledOnce();});it.each([@@ -317,6 +323,7 @@ describe("PiSessionController", () => {>);expect(unsubscribe).toHaveBeenCalledOnce();+ expect(controller.store.getState().sessions["task-1"].events).toEqual([]);});it("cancels auth-held submissions on disconnect and preserves the prompt", async () => {@@ -709,13 +716,22 @@ describe("PiSessionController", () => {await controller.connect("task-1");await controller.submit("task-1", "continue", false, "steer");+ onEvent({+ type: "assistant_message_chunk",+ timestamp: 1,+ content: { type: "text", text: "Working" },+ });controller.release("task-1");expect(unsubscribe).not.toHaveBeenCalled();+ expect(controller.store.getState().sessions["task-1"].events).not.toEqual(+ [],+ );onEvent({ type: "turn_completed", timestamp: Date.now() });expect(unsubscribe).toHaveBeenCalledOnce();+ expect(controller.store.getState().sessions["task-1"].events).toEqual([]);});it("releases a session that finishes connecting after its view unmounts", async () => {@@ -740,6 +756,261 @@ describe("PiSessionController", () => {expect(unsubscribe).toHaveBeenCalledOnce();});+ it("keeps a background cloud session until the run ends", async () => {+ const session: PiSession = {+ ...createSession(),+ cloudStatus: "in_progress",+ };+ const unsubscribe = vi.fn();+ let onCloudStatus: Parameters<PiSession["onConversationEvent"]>[2];+ vi.mocked(session.onConversationEvent).mockImplementation(+ (_event, _error, onStatus) => {+ onCloudStatus = onStatus;+ return unsubscribe;+ },+ );+ const controller = createController(session);++ await controller.connect("task-1");+ controller.release("task-1");+ expect(unsubscribe).not.toHaveBeenCalled();++ onCloudStatus?.("completed");+ await Promise.resolve();+ expect(unsubscribe).toHaveBeenCalledOnce();+ expect(controller.store.getState().sessions["task-1"].events).toEqual([]);+ });++ it("notifies a background cloud completion before releasing the session", async () => {+ const session: PiSession = {+ ...createSession(),+ cloudStatus: "in_progress",+ };+ const unsubscribe = vi.fn();+ let onEvent: (+ event: AgentConversationEvent,+ context?: PiConversationEventContext,+ ) => void = () => {};+ let onCloudStatus: Parameters<PiSession["onConversationEvent"]>[2];+ vi.mocked(session.onConversationEvent).mockImplementation(+ (handler, _error, onStatus) => {+ onEvent = handler;+ onCloudStatus = onStatus;+ return unsubscribe;+ },+ );+ const notifier = { notify: vi.fn() } as unknown as AgentSessionNotifier;+ const controller = createController(+ session,+ undefined,+ undefined,+ notifier,+ );+ controller.setNotificationContext("task-1", {+ taskTitle: "Fix notifications",+ isTaskAuthor: true,+ });++ await controller.connect("task-1");+ controller.release("task-1");++ // The cloud client reports the terminal status first, then emits the turn event.+ onCloudStatus?.("completed");+ onEvent(+ { type: "turn_completed", timestamp: 5, stopReason: "stop" },+ { isLive: true },+ );+ await Promise.resolve();++ expect(notifier.notify).toHaveBeenCalledOnce();+ expect(unsubscribe).toHaveBeenCalledOnce();+ });++ it("releases a finished cloud run holding an unanswered permission request", async () => {+ const session: PiSession = {+ ...createSession(),+ cloudStatus: "in_progress",+ };+ const unsubscribe = vi.fn();+ let onCloudStatus: Parameters<PiSession["onConversationEvent"]>[2];+ vi.mocked(session.onConversationEvent).mockImplementation(+ (_event, _error, onStatus) => {+ onCloudStatus = onStatus;+ return unsubscribe;+ },+ );+ let onRequest: ((request: McpToolPermissionRequest) => void) | undefined;+ session.onMcpToolPermissionRequest = vi.fn((callback) => {+ onRequest = callback;+ return () => {};+ });+ const controller = createController(session);++ await controller.connect("task-1");+ onRequest?.({+ requestId: "call-1",+ serverName: "Cloudflare",+ toolName: "search",+ installationId: "installation-1",+ arguments: {},+ });+ controller.release("task-1");+ expect(unsubscribe).not.toHaveBeenCalled();++ onCloudStatus?.("cancelled");+ await Promise.resolve();++ expect(unsubscribe).toHaveBeenCalledOnce();+ expect(+ controller.store.getState().sessions["task-1"].mcpToolPermissionRequests+ .size,+ ).toBe(0);+ });++ it("keeps an inactive session until requested compaction reaches the runtime", async () => {+ const session = createSession();+ const unsubscribe = vi.fn();+ vi.mocked(session.onConversationEvent).mockReturnValue(unsubscribe);+ let finish: () => void = () => {};+ const pending = new Promise<void>((resolve) => {+ finish = resolve;+ });+ session.client.compact = (async () => {+ await pending;+ return undefined;+ }) as unknown as PiRemoteRpcClient["compact"];+ const controller = createController(session);++ await controller.connect("task-1");+ const compaction = controller.submit("task-1", "/compact", false, "steer");+ controller.release("task-1");+ expect(unsubscribe).not.toHaveBeenCalled();++ finish();+ await compaction;+ expect(unsubscribe).toHaveBeenCalledOnce();+ });++ it("releases an inactive session after a failed prompt", async () => {+ const session = createSession();+ const unsubscribe = vi.fn();+ vi.mocked(session.onConversationEvent).mockReturnValue(unsubscribe);+ let fail: (error: Error) => void = () => {};+ const pending = new Promise<void>((_resolve, reject) => {+ fail = reject;+ });+ vi.mocked(session.client.prompt).mockImplementation(async () => {+ await pending;+ });+ const controller = createController(session);++ await controller.connect("task-1");+ const submission = controller.submit("task-1", "Go", false, "steer");+ controller.release("task-1");+ expect(unsubscribe).not.toHaveBeenCalled();++ fail(new Error("Pi is unavailable"));+ await expect(submission).rejects.toThrow(PiOperationError);+ expect(unsubscribe).toHaveBeenCalledOnce();+ });++ it("releases an inactive session after a failed turn ends it", async () => {+ const session = createSession();+ const unsubscribe = vi.fn();+ let onEvent: (event: AgentConversationEvent) => void = () => {};+ vi.mocked(session.onConversationEvent).mockImplementation((handler) => {+ onEvent = handler;+ return unsubscribe;+ });+ const controller = createController(session);++ await controller.connect("task-1");+ onEvent({+ type: "runtime_error",+ timestamp: 1,+ errorType: "agent_server_crash",+ message: "Agent crashed",+ });+ controller.release("task-1");++ expect(unsubscribe).toHaveBeenCalledOnce();+ });++ it("does not reclaim view ownership when a retry outlives its view", async () => {+ const session = createSession();+ let liveSubscriptions = 0;+ vi.mocked(session.onConversationEvent).mockImplementation(() => {+ liveSubscriptions += 1;+ return () => {+ liveSubscriptions -= 1;+ };+ });+ vi.mocked(session.getConversation).mockResolvedValue([+ { type: "turn_completed", timestamp: 1 },+ ]);+ let finish: () => void = () => {};+ const pending = new Promise<void>((resolve) => {+ finish = resolve;+ });+ session.retry = vi.fn(async () => {+ await pending;+ });+ const controller = createController(session);++ await controller.connect("task-1");+ const retrying = controller.retry("task-1");+ controller.release("task-1");+ expect(liveSubscriptions).toBe(1);++ finish();+ await retrying;++ expect(liveSubscriptions).toBe(0);+ expect(controller.store.getState().sessions["task-1"].events).toEqual([]);+ });++ it("keeps an inactive session until its queue is cleared", async () => {+ const session = createSession();+ const unsubscribe = vi.fn();+ vi.mocked(session.onConversationEvent).mockReturnValue(unsubscribe);+ vi.mocked(session.getQueue).mockResolvedValue({+ steering: [],+ followUp: ["Continue after this turn"],+ });+ const controller = createController(session);++ await controller.connect("task-1");+ controller.release("task-1");+ expect(unsubscribe).not.toHaveBeenCalled();++ await controller.clearQueue("task-1");+ expect(unsubscribe).toHaveBeenCalledOnce();+ });++ it("keeps an inactive shell command until it finishes", async () => {+ const session = createSession();+ const unsubscribe = vi.fn();+ vi.mocked(session.onConversationEvent).mockReturnValue(unsubscribe);+ let finish: () => void = () => {};+ const pending = new Promise<void>((resolve) => {+ finish = resolve;+ });+ vi.mocked(session.client.bash).mockImplementation(async () => {+ await pending;+ return { output: "", exitCode: 0, cancelled: false, truncated: false };+ });+ const controller = createController(session);++ await controller.connect("task-1");+ const execution = controller.bash("task-1", "printf example");+ controller.release("task-1");+ expect(unsubscribe).not.toHaveBeenCalled();++ finish();+ await execution;+ expect(unsubscribe).toHaveBeenCalledOnce();+ });+it("restores a native queue after retry replaces the runtime", async () => {let onEvent: (event: AgentConversationEvent) => void = () => {};const session = createSession();@@ -1179,23 +1450,47 @@ describe("PiSessionController", () => {});});- it("owns and releases the bound session lifetime", async () => {- const session = createSession();- const provider: PiSessionProvider = {- get: vi.fn(async () => session),- };- const controller = new PiSessionController(provider, {} as TaskService);+ it.each(["release", "disconnect"] as const)(+ "%s releases history and reloads it on the next visit",+ async (release) => {+ const session = createSession();+ const history: AgentConversationEvent[] = [+ {+ type: "assistant_message_chunk",+ timestamp: 1,+ content: { type: "text", text: "Finished" },+ },+ { type: "turn_completed", timestamp: 2 },+ ];+ vi.mocked(session.getConversation).mockResolvedValue(history);+ const provider: PiSessionProvider = {+ get: vi.fn(async () => session),+ };+ const controller = new PiSessionController(provider, {} as TaskService);- await controller.ensureConnected("task-1");- await controller.setThinkingLevel("task-1", "high");+ await controller.ensureConnected("task-1");+ await controller.setThinkingLevel("task-1", "high");- expect(provider.get).toHaveBeenCalledOnce();+ expect(provider.get).toHaveBeenCalledOnce();+ expect(controller.store.getState().sessions["task-1"].events).toEqual(+ history,+ );- controller.disconnect("task-1");- await controller.ensureConnected("task-1");+ controller[release]("task-1");+ expect(controller.store.getState().sessions["task-1"].events).toEqual([]);+ // The view keys its loading skeleton off status, so a released session+ // must not look like a loaded one with an empty transcript.+ expect(controller.store.getState().sessions["task-1"].status).toBe(+ undefined,+ );+ await controller.ensureConnected("task-1");- expect(provider.get).toHaveBeenCalledTimes(2);- });+ expect(provider.get).toHaveBeenCalledTimes(2);+ expect(controller.store.getState().sessions["task-1"].events).toEqual(+ history,+ );+ },+ );it("opens cold tasks before connecting", async () => {const client = createSession();diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.tsindex 6565a2ce80b7..3bab0b0de13b 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts@@ -120,6 +120,28 @@ type PiTurnState =| { phase: "active"; startedAt?: number; stopReason?: string }| { phase: "completed" };+function isTerminalCloudStatus(status: TaskRunStatus | undefined): boolean {+ return (+ status === "completed" || status === "failed" || status === "cancelled"+ );+}++// Reopening reloads history, so keeping it after transport disposal only retains memory.+function disposedSessionState(): Partial<PiControllerSessionState> {+ return {+ connectionState: "disconnected",+ events: [],+ models: [],+ modelsLoaded: false,+ thinkingLevels: [],+ thinkingLevelsLoaded: false,+ commands: [],+ queue: { steering: [], followUp: [] },+ status: undefined,+ mcpToolPermissionRequests: new Map(),+ };+}+type PiOperation =| "prompt"| "compact"@@ -183,6 +205,7 @@ export class PiSessionController {PiSessionNotificationContext>();private readonly turnStates = new Map<string, PiTurnState>();+ private readonly submissionsInFlight = new Map<string, number>();constructor(@inject(PI_SESSION_PROVIDER) private readonly provider: PiSessionProvider,@@ -210,6 +233,12 @@ export class PiSessionController {ensureConnected(taskId: string, taskRunId?: string): Promise<void> {this.activeTaskIds.add(taskId);+ return this.reconnect(taskId, taskRunId);+ }++ // Reconnects without claiming view ownership, so a reconnect that outlives its+ // view cannot pin the session against eviction.+ private reconnect(taskId: string, taskRunId?: string): Promise<void> {this.bindTaskRun(taskId, taskRunId);this.ensureSubscription(taskId);@@ -284,14 +313,27 @@ export class PiSessionController {disconnectAll(): void {const taskIds = new Set([+ ...Object.keys(this.store.getState().sessions),...this.activeTaskIds,...this.sessions.keys(),...this.subscriptions.keys(),...this.notificationContexts.keys(),]);for (const taskId of taskIds) {- this.disconnect(taskId);- }+ this.activeTaskIds.delete(taskId);+ this.disposeTaskResources(taskId);+ }+ // One store write, because a write per task copies the whole record each time.+ this.store.setState((state) => {+ const sessions = { ...state.sessions };+ for (const taskId of taskIds) {+ const session = sessions[taskId];+ if (session) {+ sessions[taskId] = { ...session, ...disposedSessionState() };+ }+ }+ return { sessions };+ });}async retry(taskId: string): Promise<void> {@@ -308,7 +350,7 @@ export class PiSessionController {const session = await this.getPiSession(taskId);await session.retry?.();this.resetTransport(taskId);- await this.ensureConnected(taskId, taskRunId);+ await this.reconnect(taskId, taskRunId);} catch (error) {throw this.recordOperationFailure(taskId, "retry", error);}@@ -327,6 +369,7 @@ export class PiSessionController {const requests = new Map(this.getSession(taskId).mcpToolPermissionRequests);requests.delete(request.requestId);this.updateSession(taskId, { mcpToolPermissionRequests: requests });+ this.disposeInactiveSessionIfIdle(taskId);}async clearQueue(taskId: string): Promise<PiQueueSnapshot> {@@ -362,7 +405,7 @@ export class PiSessionController {taskRunId,);this.resetTransport(taskId);- await this.ensureConnected(taskId, resumedRun.id);+ await this.reconnect(taskId, resumedRun.id);} catch (error) {throw this.recordOperationFailure(taskId, "restart", error);}@@ -401,12 +444,48 @@ export class PiSessionController {return messagingMode === "steer" ? "steer" : "followUp";}+ // A submission only marks its turn pending after its first await, so hold the+ // session from the moment it is requested.async submit(taskId: string,text: string,isStreaming: boolean,messagingMode: PiMessagingMode,deferredConfig?: PiDeferredConfig,+ ): Promise<PiSubmitResult> {+ this.submissionsInFlight.set(+ taskId,+ (this.submissionsInFlight.get(taskId) ?? 0) + 1,+ );+ try {+ return await this.runSubmission(+ taskId,+ text,+ isStreaming,+ messagingMode,+ deferredConfig,+ );+ } finally {+ this.endSubmission(taskId);+ this.disposeInactiveSessionIfIdle(taskId);+ }+ }++ private endSubmission(taskId: string): void {+ const remaining = (this.submissionsInFlight.get(taskId) ?? 1) - 1;+ if (remaining > 0) {+ this.submissionsInFlight.set(taskId, remaining);+ return;+ }+ this.submissionsInFlight.delete(taskId);+ }++ private async runSubmission(+ taskId: string,+ text: string,+ isStreaming: boolean,+ messagingMode: PiMessagingMode,+ deferredConfig?: PiDeferredConfig,): Promise<PiSubmitResult> {const message = text.trim();const action = this.getSubmitAction(message, isStreaming, messagingMode);@@ -481,6 +560,7 @@ export class PiSessionController {followUp: action === "followUp" ? [message] : [],});}+ const previousTurnState = this.turnStates.get(taskId);this.markTurnPending(taskId);if (currentSession.resumeRequired) {this.updateSession(taskId, { connectionState: "connecting" });@@ -525,6 +605,7 @@ export class PiSessionController {this.applyQueue(taskId, controllerSession.queue);}this.setTurnStreaming(taskId, wasStreaming);+ this.restoreTurnState(taskId, previousTurnState);const operation = queuesMessage ? "queue" : "prompt";throw this.recordOperationFailure(taskId,@@ -580,6 +661,7 @@ export class PiSessionController {throw this.recordOperationFailure(taskId, "bash", error);} finally {this.updateSession(taskId, { isBashRunning: false });+ this.disposeInactiveSessionIfIdle(taskId);}}@@ -602,6 +684,7 @@ export class PiSessionController {const session = await this.getPiSession(taskId);await session.client.abortBash();this.updateSession(taskId, { isBashRunning: false });+ this.disposeInactiveSessionIfIdle(taskId);} catch (error) {throw this.recordOperationFailure(taskId, "cancel", error);}@@ -780,6 +863,7 @@ export class PiSessionController {this.setSession(taskId, {connectionState: "connected",events: reconciledEvents,+ cloudStatus: currentSession.cloudStatus ?? session.cloudStatus,status: resolvedStatus,stats,models: currentSession.models,@@ -945,8 +1029,8 @@ export class PiSessionController {if (event.type === "turn_completed") {void this.refreshStats(taskId);- this.disposeInactiveSessionIfIdle(taskId);}+ this.disposeInactiveSessionIfIdle(taskId);}private reconcileTurnState(@@ -1047,6 +1131,9 @@ export class PiSessionController {private handleCloudStatus(taskId: string, cloudStatus: TaskRunStatus): void {this.updateSession(taskId, { cloudStatus });+ // The cloud client emits its synthetic turn_completed straight after this+ // callback, so let that event notify before the session can be disposed.+ queueMicrotask(() => this.disposeInactiveSessionIfIdle(taskId));}private async loadStats(@@ -1286,6 +1373,7 @@ export class PiSessionController {queue,status: this.withPendingMessageCount(taskId, queue),});+ this.disposeInactiveSessionIfIdle(taskId);}private withPendingMessageCount(@@ -1384,6 +1472,7 @@ export class PiSessionController {const session = await this.getPiSession(taskId);const status = await session.client.getState();this.updateSession(taskId, { status });+ this.disposeInactiveSessionIfIdle(taskId);}private async sendCloudUserMessage(@@ -1442,8 +1531,7 @@ export class PiSessionController {this.liveEvents.delete(taskId);this.queueRevisions.delete(taskId);this.queuesToRestore.delete(taskId);- this.activeTaskIds.delete(taskId);- await this.ensureConnected(taskId, resumedRun.id);+ await this.reconnect(taskId, resumedRun.id);return this.getPiSession(taskId);}@@ -1472,22 +1560,50 @@ export class PiSessionController {private shouldRetainInactiveSession(taskId: string): boolean {const session = this.getSession(taskId);+ const turnState = this.turnStates.get(taskId);if (session.connectionState === "connecting" ||session.status?.isStreaming ||- this.turnStates.get(taskId)?.phase === "active"+ session.status?.isCompacting ||+ this.submissionsInFlight.has(taskId) ||+ session.isBashRunning ||+ session.authRestoring ||+ // A turn that already recorded a failure receives no turn_completed, so it+ // is finished, not in flight. A recovering turn clears the failure on its+ // next activity event.+ (turnState?.phase === "active" && turnState.stopReason === undefined)) {return true;}+ if (isTerminalCloudStatus(session.cloudStatus)) {+ // A finished run can no longer answer a permission request or drain a queue.+ return false;+ }return (- session.cloudStatus !== undefined &&- session.cloudStatus !== "completed" &&- session.cloudStatus !== "failed" &&- session.cloudStatus !== "cancelled"+ session.cloudStatus !== undefined ||+ session.mcpToolPermissionRequests.size > 0 ||+ session.queue.steering.length > 0 ||+ session.queue.followUp.length > 0);}+ private restoreTurnState(+ taskId: string,+ turnState: PiTurnState | undefined,+ ): void {+ if (turnState) {+ this.turnStates.set(taskId, turnState);+ return;+ }+ this.turnStates.delete(taskId);+ }+private disposeTask(taskId: string): void {+ this.disposeTaskResources(taskId);+ this.updateSession(taskId, disposedSessionState());+ }++ private disposeTaskResources(taskId: string): void {this.cancelAuthRestoration.get(taskId)?.();this.resetTransport(taskId);this.taskRunIds.delete(taskId);@@ -1495,8 +1611,8 @@ export class PiSessionController {this.queueRevisions.delete(taskId);this.queuesToRestore.delete(taskId);this.turnStates.delete(taskId);+ this.submissionsInFlight.delete(taskId);this.notificationContexts.delete(taskId);- this.updateSession(taskId, { mcpToolPermissionRequests: new Map() });}private resetTransport(taskId: string): void {