: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): hide routine pi runtime errors (#103029)
Jonathan Mieloofa0b0ddd73d3
diff --git a/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.test.ts b/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.test.tsindex c22a5fc160a0..230fe0748f6a 100644--- a/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.test.ts+++ b/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.test.ts@@ -499,42 +499,46 @@ describe("createPiConversationTranslator", () => {]);});- it("translates compaction lifecycle into generic runtime statuses", () => {- const translator = createPiConversationTranslator();- translator.translateHistoryMessage(- assistant([{ type: "text", text: "complete" }]),- );+ it.each([false, true])(+ "translates compaction lifecycle into a completed runtime status when aborted is %s",+ (aborted) => {+ const translator = createPiConversationTranslator();+ translator.translateHistoryMessage(+ assistant([{ type: "text", text: "complete" }]),+ );- expect(- translator.translateEvent({- type: "compaction_start",- reason: "manual",- }),- ).toEqual([- {- type: "runtime_status",- timestamp: 10,- status: "compacting",- },- ]);+ expect(+ translator.translateEvent({+ type: "compaction_start",+ reason: "manual",+ }),+ ).toEqual([+ {+ type: "runtime_status",+ timestamp: 10,+ status: "compacting",+ },+ ]);- expect(- translator.translateEvent({- type: "compaction_end",- reason: "manual",- result: undefined,- aborted: false,- willRetry: false,- }),- ).toEqual([- {- type: "runtime_status",- timestamp: 10,- status: "compacting",- isComplete: true,- },- ]);- });+ expect(+ translator.translateEvent({+ type: "compaction_end",+ reason: "manual",+ result: undefined,+ aborted,+ willRetry: false,+ ...(aborted ? { errorMessage: "Compaction cancelled" } : {}),+ }),+ ).toEqual([+ {+ type: "runtime_status",+ timestamp: 10,+ status: "compacting",+ isComplete: true,+ },+ ]);+ },+ );it("emits the completed compaction summary without reloading history", () => {const translator = createPiConversationTranslator();diff --git a/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.ts b/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.tsindex 0fdef35023af..7ba9edfc9104 100644--- a/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.ts+++ b/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.ts@@ -661,15 +661,13 @@ export function createPiConversationTranslator(}if (event.type === "compaction_end") {- if (event.aborted || event.errorMessage) {+ if (event.errorMessage && !event.aborted) {return [{type: "runtime_status",timestamp: latestConversationTimestamp,status: "compacting_failed",- error:- event.errorMessage ??- (event.aborted ? "Compaction cancelled" : undefined),+ error: event.errorMessage,},];}diff --git a/products/desktop/packages/agent/src/pi/runtime.test.ts b/products/desktop/packages/agent/src/pi/runtime.test.tsindex 9d7955476ee7..75ee50e2d0ba 100644--- a/products/desktop/packages/agent/src/pi/runtime.test.ts+++ b/products/desktop/packages/agent/src/pi/runtime.test.ts@@ -92,13 +92,39 @@ describe("PiRuntime", () => {});});- it("does not expose tool failures after requesting an interrupt", async () => {- const { client, emit, send } = createClient();- const runtime = new PiRuntime(client);- const conversationListener = vi.fn();- runtime.onConversationEvent(conversationListener);- send.mockImplementation(async (command: { type: string }) => {- if (command.type === "abort") {+ it.each([+ ["abort", (runtime: PiRuntime) => runtime.abort(), false],+ [+ "steer",+ (runtime: PiRuntime) =>+ runtime.sendCommand({ type: "steer", message: "stop" }),+ false,+ ],+ [+ "compact",+ (runtime: PiRuntime) => runtime.sendCommand({ type: "compact" }),+ false,+ ],+ ["abort", (runtime: PiRuntime) => runtime.abort(), true],+ [+ "steer",+ (runtime: PiRuntime) =>+ runtime.sendCommand({ type: "steer", message: "stop" }),+ true,+ ],+ [+ "compact",+ (runtime: PiRuntime) => runtime.sendCommand({ type: "compact" }),+ true,+ ],+ ])(+ "does not expose interrupted tool failures after %s when its command fails: %s",+ async (_command, interrupt, commandFails) => {+ const { client, emit, send } = createClient();+ const runtime = new PiRuntime(client);+ const conversationListener = vi.fn();+ runtime.onConversationEvent(conversationListener);+ send.mockImplementation(async (command: { type: string }) => {emit({type: "tool_execution_end",toolCallId: "tool-1",@@ -124,57 +150,66 @@ describe("PiRuntime", () => {timestamp: 0,},});- }- return { type: "response", command: command.type, success: true };- });+ if (commandFails) {+ throw new Error("Command transport failed");+ }+ return { type: "response", command: command.type, success: true };+ });- await runtime.abort();+ if (commandFails) {+ await expect(interrupt(runtime)).rejects.toThrow(+ "Command transport failed",+ );+ } else {+ await interrupt(runtime);+ }- const interruptedToolUpdate = {- type: "tool_call_updated",- timestamp: 0,- toolCall: {- id: "tool-1",- status: "in_progress",- rawOutput: [],- },- };- expect(conversationListener).toHaveBeenNthCalledWith(- 1,- interruptedToolUpdate,- );- expect(conversationListener).toHaveBeenNthCalledWith(- 2,- interruptedToolUpdate,- );+ const interruptedToolUpdate = {+ type: "tool_call_updated",+ timestamp: 0,+ toolCall: {+ id: "tool-1",+ status: "in_progress",+ rawOutput: [],+ },+ };+ expect(conversationListener).toHaveBeenNthCalledWith(+ 1,+ interruptedToolUpdate,+ );+ expect(conversationListener).toHaveBeenNthCalledWith(+ 2,+ interruptedToolUpdate,+ );- emit({- type: "tool_execution_end",- toolCallId: "tool-2",- toolName: "web_search",- result: {- content: [{ type: "text", text: "Permission denied" }],- details: undefined,- },- isError: true,- });+ emit({+ type: "tool_execution_end",+ toolCallId: "tool-2",+ toolName: "web_search",+ result: {+ content: [{ type: "text", text: "Permission denied" }],+ details: undefined,+ },+ isError: true,+ });- expect(conversationListener).toHaveBeenLastCalledWith({- type: "tool_call_updated",- timestamp: 0,- toolCall: {- id: "tool-2",- status: "failed",- rawOutput: [{ type: "text", text: "Permission denied" }],- content: [- {- type: "content",- content: { type: "text", text: "Permission denied" },- },- ],- },- });- });+ expect(conversationListener).toHaveBeenLastCalledWith({+ type: "tool_call_updated",+ timestamp: 0,+ toolCall: {+ id: "tool-2",+ status: "failed",+ rawOutput: [{ type: "text", text: "Permission denied" }],+ content: [+ {+ type: "content",+ content: { type: "text", text: "Permission denied" },+ },+ ],+ },+ });+ },+ );it("uses the native command id for the echoed user message", async () => {const { client, emit, send } = createClient();diff --git a/products/desktop/packages/agent/src/pi/runtime.ts b/products/desktop/packages/agent/src/pi/runtime.tsindex 27b38c259480..163d83ff3646 100644--- a/products/desktop/packages/agent/src/pi/runtime.ts+++ b/products/desktop/packages/agent/src/pi/runtime.ts@@ -80,7 +80,10 @@ export class PiRuntime {});}if (command.type !== "bash") {- const isInterrupt = command.type === "abort";+ const isInterrupt =+ command.type === "abort" ||+ command.type === "steer" ||+ command.type === "compact";if (isInterrupt) {this.translator.markTurnInterrupted();}@@ -89,18 +92,16 @@ export class PiRuntime {if (!response.success && isUserMessage && command.id) {this.removePendingUserMessageId(command.id);}- if (isInterrupt) {- this.translator.clearTurnInterrupted();- }return response;} catch (error) {if (isUserMessage && command.id) {this.removePendingUserMessageId(command.id);}+ throw error;+ } finally {if (isInterrupt) {this.translator.clearTurnInterrupted();}- throw error;}}diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.tsindex 9c04ec3b9f39..76d66f2a535d 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts@@ -1,4 +1,5 @@import type { TaskService } from "@posthog/core/task-detail/taskService";+import type { RootLogger } from "@posthog/di/logger";import {type AgentConversationEvent,mcpToolKey,@@ -13,6 +14,14 @@ import {type PiSessionProvider,} from "./piSessionController";+const logger: RootLogger = {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ scope: () => logger,+};+function createCloudTaskClient(autoStart = true) {const subscriptions: Array<{onUpdate: (update: CloudTaskUpdatePayload) => void;@@ -789,7 +798,11 @@ describe("CloudPiSessionClient", () => {const provider: PiSessionProvider = {get: vi.fn(async () => session),};- const controller = new PiSessionController(provider, {} as TaskService);+ const controller = new PiSessionController(+ provider,+ {} as TaskService,+ logger,+ );const connection = controller.connect("task-1");await vi.waitFor(() => {diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.tsindex 09f75ddb93f3..7a3198dce047 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts@@ -2,6 +2,7 @@ import type { PiRemoteRpcClient } from "@posthog/agent/pi/remote-rpc-client";import type { AuthService } from "@posthog/core/auth/auth";import type { AgentSessionNotifier } from "@posthog/core/notification/agentSessionNotifications";import type { TaskService } from "@posthog/core/task-detail/taskService";+import type { RootLogger } from "@posthog/di/logger";import type {AgentConversationEvent,McpToolPermissionRequest,@@ -15,6 +16,27 @@ import {type PiSessionProvider,} from "./piSessionController";+function createLogger(): {+ logger: RootLogger;+ scoped: {+ debug: ReturnType<typeof vi.fn>;+ info: ReturnType<typeof vi.fn>;+ warn: ReturnType<typeof vi.fn>;+ error: ReturnType<typeof vi.fn>;+ };+} {+ const scoped = {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ };+ return {+ logger: { ...scoped, scope: vi.fn(() => scoped) },+ scoped,+ };+}+function createController(session = createSession(),taskService = {@@ -22,11 +44,18 @@ function createController(} as unknown as TaskService,authService?: AuthService,notifier?: AgentSessionNotifier,+ logger = createLogger().logger,): PiSessionController {const provider: PiSessionProvider = {get: vi.fn(async () => session),};- return new PiSessionController(provider, taskService, authService, notifier);+ return new PiSessionController(+ provider,+ taskService,+ logger,+ authService,+ notifier,+ );}function createSession(): PiSession {@@ -564,6 +593,45 @@ describe("PiSessionController", () => {);});+ it("logs expected transport interruptions without changing session state", async () => {+ let onError: (error: unknown) => void = () => {};+ const session = createSession();+ vi.mocked(session.onConversationEvent).mockImplementation(+ (_onEvent, handler) => {+ onError = handler;+ return () => {};+ },+ );+ const logger = createLogger();+ const controller = createController(+ session,+ undefined,+ undefined,+ undefined,+ logger.logger,+ );++ await controller.connect("task-1");+ const interruptionError = new DOMException(+ "This operation was aborted",+ "AbortError",+ );+ onError(interruptionError);++ expect(controller.store.getState().sessions["task-1"]).toMatchObject({+ connectionState: "connected",+ error: undefined,+ });+ expect(logger.scoped.info).toHaveBeenCalledWith(+ "Pi session interrupted",+ expect.objectContaining({+ taskId: "task-1",+ scope: "connection",+ errorName: "AbortError",+ }),+ );+ });+it("keeps fatal runtime errors in a retryable disconnected state", async () => {let onEvent: (event: AgentConversationEvent) => void = () => {};const session = createSession();@@ -950,9 +1018,11 @@ describe("PiSessionController", () => {})),} as unknown as TaskService;const notifier = { notify: vi.fn() };+ const logger = createLogger();const controller = new PiSessionController(provider,taskService,+ logger.logger,undefined,notifier,);@@ -960,12 +1030,25 @@ describe("PiSessionController", () => {await controller.connect("task-1");await controller.submit("task-1", "continue", false, "steer");- vi.mocked(session.client.abort).mockRejectedValueOnce(- new Error("Unable to stop"),- );+ const abortError = new Error("Unable to stop");+ vi.mocked(session.client.abort).mockRejectedValueOnce(abortError);await expect(controller.abort("task-1")).rejects.toThrow(PiOperationError,);+ expect(+ controller.store.getState().sessions["task-1"].error,+ ).toBeUndefined();+ expect(logger.scoped.error).toHaveBeenCalledWith(+ "Pi operation failed",+ expect.objectContaining({+ taskId: "task-1",+ operation: "cancel",+ scope: "operation",+ kind: "unknown",+ retryable: false,+ errorName: "Error",+ }),+ );expect(controller.store.getState().sessions["task-1"].status?.isStreaming,).toBe(true);@@ -1574,6 +1657,7 @@ describe("PiSessionController", () => {const controller = new PiSessionController(provider,taskService,+ createLogger().logger,undefined,notifier,);@@ -1613,9 +1697,11 @@ describe("PiSessionController", () => {.mockResolvedValue(resumedSession),} as PiSessionProvider;const resumeCloudPiRun = vi.fn(async () => ({ id: "run-1" }));- const controller = new PiSessionController(provider, {- resumeCloudPiRun,- } as unknown as TaskService);+ const controller = new PiSessionController(+ provider,+ { resumeCloudPiRun } as unknown as TaskService,+ createLogger().logger,+ );await controller.connect("task-1");await controller.submit("task-1", "continue", false, "steer", {@@ -1703,6 +1789,7 @@ describe("PiSessionController", () => {const controller = new PiSessionController(provider,taskService,+ createLogger().logger,undefined,notifier,);@@ -1820,7 +1907,11 @@ describe("PiSessionController", () => {const provider: PiSessionProvider = {get: vi.fn(async () => session),};- const controller = new PiSessionController(provider, {} as TaskService);+ const controller = new PiSessionController(+ provider,+ {} as TaskService,+ createLogger().logger,+ );await controller.ensureConnected("task-1");await controller.setThinkingLevel("task-1", "high");diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.tsindex 91acd4316742..da9103875d7c 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts@@ -8,6 +8,11 @@ import type {PiUsageStats,RpcExtensionUIResponse,} from "@posthog/agent/pi/types";+import {+ ROOT_LOGGER,+ type RootLogger,+ type ScopedLogger,+} from "@posthog/di/logger";import {type AgentConversationEvent,classifyPromptFailure,@@ -195,10 +200,22 @@ function isResumableCloudSendError(error: unknown): boolean {);}+function isExpectedPiInterruption(error: unknown): boolean {+ if (!(error instanceof Error)) {+ return false;+ }+ return (+ error.name === "AbortError" ||+ error.message === "This operation was aborted"+ );+}+@injectable()export class PiSessionController {readonly store: PiSessionStore = createPiSessionStore();+ private readonly log: ScopedLogger;+private readonly sessions = new Map<string, Promise<PiSession>>();private readonly subscriptions = new Map<string, () => void>();private readonly liveEvents = new Map<string, AgentConversationEvent[]>();@@ -239,6 +256,7 @@ export class PiSessionController {constructor(@inject(PI_SESSION_PROVIDER) private readonly provider: PiSessionProvider,@inject(TASK_SERVICE) private readonly taskService: TaskService,+ @inject(ROOT_LOGGER) rootLogger: RootLogger,@inject(AUTH_SERVICE)@optional()private readonly authService?: AuthService,@@ -246,6 +264,7 @@ export class PiSessionController {@optional()private readonly notifier?: AgentSessionNotifier,) {+ this.log = rootLogger.scope("pi-session-controller");this.authService?.on(AuthServiceEvent.StateChanged, (state) => {if (state.status === "anonymous") {this.disconnectAll();@@ -717,7 +736,14 @@ export class PiSessionController {this.setTurnStreaming(taskId, false);await this.refreshStatus(taskId);} catch (error) {- throw this.recordOperationFailure(taskId, "cancel", error);+ throw this.recordOperationFailure(+ taskId,+ "cancel",+ error,+ undefined,+ undefined,+ false,+ );}}@@ -1399,6 +1425,7 @@ export class PiSessionController {error: unknown,errorType?: string,recoveryPrompt?: string,+ storeFailure = true,): PiOperationError {const details = (error as { data?: { details?: string } })?.data?.details;const classified = classifyPromptFailure(error, details, errorType);@@ -1422,14 +1449,24 @@ export class PiSessionController {limitCause: classified.limitCause,recoveryPrompt,};- this.updateSession(taskId, {- error: failure,- ...(scope === "connection"- ? {- connectionState: retryable ? "disconnected" : "error",- }- : {}),+ this.log.error("Pi operation failed", {+ taskId,+ operation,+ scope,+ kind: classified.kind,+ retryable,+ errorName: error instanceof Error ? error.name : typeof error,});+ if (storeFailure) {+ this.updateSession(taskId, {+ error: failure,+ ...(scope === "connection"+ ? {+ connectionState: retryable ? "disconnected" : "error",+ }+ : {}),+ });+ }return new PiOperationError(failure);}@@ -1848,6 +1885,19 @@ export class PiSessionController {this.flushText(taskId);const failure = normalizeSessionError(error);const classified = classifyPromptFailure(error);+ const expectedInterruption = isExpectedPiInterruption(error);+ const logDetails = {+ taskId,+ scope: "connection",+ kind: classified.kind,+ retryable: failure.retryable,+ errorName: error instanceof Error ? error.name : typeof error,+ };+ if (expectedInterruption) {+ this.log.info("Pi session interrupted", logDetails);+ return;+ }+ this.log.error("Pi session transport failed", logDetails);this.updateSession(taskId, {connectionState: failure.retryable ? "disconnected" : "error",error: {