: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): notify when Pi sessions need attention (#81192)
Jonathan Mieloocac1b701932b
diff --git a/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.test.ts b/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.test.tsindex ebe322b7e6f3..226c43cae5c5 100644--- a/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.test.ts+++ b/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.test.ts@@ -142,29 +142,35 @@ describe("createPiConversationTranslator", () => {).toEqual([]);});- it("completes a turn using the settlement time", () => {- vi.useFakeTimers();- vi.setSystemTime(30);- const translator = createPiConversationTranslator();- const laterMessage = assistant(- [{ type: "text", text: "later" }],- "stop",- 20,- );- const earlierMessage = assistant(- [{ type: "text", text: "earlier" }],- "stop",- 10,- );+ it.each(["stop", "aborted"] as const)(+ "completes a %s turn using the settlement time and final stop reason",+ (stopReason) => {+ vi.useFakeTimers();+ vi.setSystemTime(30);+ const translator = createPiConversationTranslator();+ const laterMessage = assistant(+ [{ type: "text", text: "later" }],+ stopReason,+ 20,+ );+ const earlierMessage = assistant(+ [{ type: "text", text: "earlier" }],+ "stop",+ 10,+ );- translator.translateEvent({ type: "message_end", message: laterMessage });- translator.translateEvent({ type: "message_end", message: earlierMessage });-- expect(translator.translateEvent({ type: "agent_settled" })).toEqual([- { type: "turn_completed", timestamp: 30 },- ]);- vi.useRealTimers();- });+ translator.translateEvent({+ type: "message_end",+ message: earlierMessage,+ });+ translator.translateEvent({ type: "message_end", message: laterMessage });++ expect(translator.translateEvent({ type: "agent_settled" })).toEqual([+ { type: "turn_completed", timestamp: 30, stopReason },+ ]);+ vi.useRealTimers();+ },+ );it("translates retry lifecycle without rendering transient runtime errors", () => {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 1f78bdc4c06a..6f5417b43926 100644--- a/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.ts+++ b/products/desktop/packages/agent/src/pi/conversation/translatePiConversation.ts@@ -121,6 +121,7 @@ export function createPiConversationTranslator(): PiConversationTranslator {let latestRuntimeTimestamp = 0;let latestConversationTimestamp = 0;let pendingRuntimeError: AgentConversationEvent | undefined;+ let settledStopReason: string | undefined;let retrying = false;let directBashSequence = 0;@@ -485,6 +486,10 @@ export function createPiConversationTranslator(): PiConversationTranslator {return customMessageEvents(event.message);}+ if (isAssistantMessage(event.message)) {+ settledStopReason = event.message.stopReason;+ }+const events = messageTranslator.translate(event.message);const runtimeError = events.find((translated) => translated.type === "runtime_error",@@ -609,9 +614,13 @@ export function createPiConversationTranslator(): PiConversationTranslator {const timestamp = Math.max(Date.now(), latestRuntimeTimestamp);const hadRuntimeActivity = latestRuntimeTimestamp > 0;+ const stopReason = settledStopReason;latestRuntimeTimestamp = 0;+ settledStopReason = undefined;- return hadRuntimeActivity ? [{ type: "turn_completed", timestamp }] : [];+ return hadRuntimeActivity+ ? [{ type: "turn_completed", timestamp, stopReason }]+ : [];}return [];diff --git a/products/desktop/packages/core/src/notification/agentSessionNotifications.ts b/products/desktop/packages/core/src/notification/agentSessionNotifications.tsnew file mode 100644index 000000000000..4625bea62605--- /dev/null+++ b/products/desktop/packages/core/src/notification/agentSessionNotifications.ts@@ -0,0 +1,25 @@+export type AgentSessionNotification =+ | {+ kind: "turn_completed";+ taskId: string;+ taskTitle: string;+ stopReason: string;+ durationMs?: number;+ isTaskAuthor?: boolean;+ agentSpoke?: boolean;+ }+ | {+ kind: "needs_input";+ taskId: string;+ taskTitle: string;+ isTaskAuthor?: boolean;+ agentSpoke?: boolean;+ };++export interface AgentSessionNotifier {+ notify(notification: AgentSessionNotification): void;+}++export const AGENT_SESSION_NOTIFIER = Symbol.for(+ "posthog.notification.agentSessionNotifier",+);diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.tsindex ea0c27fdc4e2..50bdbbbbcb34 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.test.ts@@ -367,7 +367,11 @@ describe("CloudPiSessionClient", () => {context("in_progress"),);const events: AgentConversationEvent[] = [];- session.onConversationEvent((event) => events.push(event), vi.fn());+ const eventContexts: Array<{ isLive: boolean } | undefined> = [];+ session.onConversationEvent((event, context) => {+ events.push(event);+ eventContexts.push(context);+ }, vi.fn());cloud.sendUpdate({taskId: "task-1",@@ -401,6 +405,7 @@ describe("CloudPiSessionClient", () => {group: "setup:run-1",}),]);+ expect(eventContexts).toEqual([{ isLive: true }]);expect(cloud.client.sendCommand).not.toHaveBeenCalled();});@@ -465,7 +470,11 @@ describe("CloudPiSessionClient", () => {context("completed"),);const events: AgentConversationEvent[] = [];- session.onConversationEvent((event) => events.push(event), vi.fn());+ const eventContexts: Array<{ isLive: boolean } | undefined> = [];+ session.onConversationEvent((event, context) => {+ events.push(event);+ eventContexts.push(context);+ }, vi.fn());const conversation = session.getConversation();cloud.sendUpdate({@@ -489,8 +498,12 @@ describe("CloudPiSessionClient", () => {await expect(session.client.getCommands()).resolves.toEqual([]);expect(events).toEqual([expect.objectContaining(snapshotEvent),- expect.objectContaining({ type: "turn_completed" }),+ expect.objectContaining({+ type: "turn_completed",+ stopReason: "end_turn",+ }),]);+ expect(eventContexts).toEqual([{ isLive: false }, { isLive: false }]);expect(cloud.client.sendCommand).not.toHaveBeenCalled();});diff --git a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.tsindex ad1e8af98cca..d5e42b102105 100644--- a/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts+++ b/products/desktop/packages/core/src/pi-runtime/cloudPiSessionClient.ts@@ -26,7 +26,10 @@ import {isTerminalStatus,progressNotificationParams,} from "../cloud-task/schemas";-import type { PiSession } from "./piSessionController";+import type {+ PiConversationEventContext,+ PiSession,+} from "./piSessionController";function createTerminalPiRpcClient(runId: string,@@ -286,7 +289,10 @@ export class CloudPiSessionClient implements PiSession {}onConversationEvent(- onEvent: (event: AgentConversationEvent) => void,+ onEvent: (+ event: AgentConversationEvent,+ context?: PiConversationEventContext,+ ) => void,onError: (error: unknown) => void,onCloudStatus?: (status: TaskRunStatus) => void,): () => void {@@ -332,7 +338,10 @@ export class CloudPiSessionClient implements PiSession {private handleUpdate(update: CloudTaskUpdatePayload,- onEvent: (event: AgentConversationEvent) => void,+ onEvent: (+ event: AgentConversationEvent,+ context?: PiConversationEventContext,+ ) => void,onError: (error: unknown) => void,onCloudStatus?: (status: TaskRunStatus) => void,): void {@@ -377,7 +386,7 @@ export class CloudPiSessionClient implements PiSession {this.markSnapshotReady();for (const event of events) {if (!event.sourceId || !previousSourceIds.has(event.sourceId)) {- onEvent(event);+ onEvent(event, { isLive: false });}}} else if (update.kind === "logs") {@@ -397,7 +406,7 @@ export class CloudPiSessionClient implements PiSession {this.snapshotEvents = [...this.snapshotEvents, ...newEvents];this.markSnapshotReady();for (const event of newEvents) {- onEvent(event);+ onEvent(event, { isLive: true });}}@@ -413,7 +422,16 @@ export class CloudPiSessionClient implements PiSession {this.resolveTerminalStatus();if (!this.terminalEventSent) {this.terminalEventSent = true;- onEvent({ type: "turn_completed", timestamp: Date.now() });+ const stopReason =+ this.runStatus === "completed"+ ? "end_turn"+ : this.runStatus === "cancelled"+ ? "cancelled"+ : "failed";+ onEvent(+ { type: "turn_completed", timestamp: Date.now(), stopReason },+ { isLive: update.kind === "status" },+ );}}diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.tsindex 2f9999665d3d..6215d46cdaf8 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts@@ -1,5 +1,6 @@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 {AgentConversationEvent,@@ -7,6 +8,7 @@ import type {} from "@posthog/shared";import { describe, expect, it, vi } from "vitest";import {+ type PiConversationEventContext,PiOperationError,type PiSession,PiSessionController,@@ -19,11 +21,12 @@ function createController(openTask: vi.fn(async () => ({ success: true })),} as unknown as TaskService,authService?: AuthService,+ notifier?: AgentSessionNotifier,): PiSessionController {const provider: PiSessionProvider = {get: vi.fn(async () => session),};- return new PiSessionController(provider, taskService, authService);+ return new PiSessionController(provider, taskService, authService, notifier);}function createSession(): PiSession {@@ -90,7 +93,16 @@ describe("PiSessionController", () => {return () => {};});session.respondMcpToolPermission = vi.fn(async () => {});- const controller = createController(session);+ const notifier = { notify: vi.fn() };+ const controller = createController(+ session,+ undefined,+ undefined,+ notifier,+ );+ controller.setNotificationContext("task-1", {+ taskTitle: "Fix notifications",+ });await controller.ensureConnected("task-1");const first = {requestId: "call-1",@@ -101,6 +113,7 @@ describe("PiSessionController", () => {};const second = { ...first, requestId: "call-2" };+ onRequest?.(first);onRequest?.(first);onRequest?.(second);@@ -108,6 +121,12 @@ describe("PiSessionController", () => {controller.store.getState().sessions["task-1"]?.mcpToolPermissionRequests.size,).toBe(2);+ expect(notifier.notify).toHaveBeenCalledTimes(2);+ expect(notifier.notify).toHaveBeenCalledWith({+ kind: "needs_input",+ taskId: "task-1",+ taskTitle: "Fix notifications",+ });await controller.respondMcpToolPermission("task-1", first, "reject");expect(controller.store@@ -374,6 +393,34 @@ describe("PiSessionController", () => {);});+ it("disconnects retained sessions when authentication ends", async () => {+ let onAuthStateChange: (+ state: ReturnType<AuthService["getState"]>,+ ) => void = () => {};+ const authService = {+ getState: vi.fn(() => ({ status: "authenticated" })),+ on: vi.fn((_event, handler) => {+ onAuthStateChange = handler;+ }),+ off: vi.fn(),+ } as unknown as AuthService;+ const unsubscribe = vi.fn();+ const session = createSession();+ vi.mocked(session.onConversationEvent).mockReturnValue(unsubscribe);+ const controller = createController(session, undefined, authService);++ await controller.connect("task-1");+ await controller.submit("task-1", "keep running", false, "steer");+ controller.release("task-1");+ expect(unsubscribe).not.toHaveBeenCalled();++ onAuthStateChange({ status: "anonymous" } as ReturnType<+ AuthService["getState"]+ >);++ expect(unsubscribe).toHaveBeenCalledOnce();+ });+it("cancels auth-held submissions on disconnect and preserves the prompt", async () => {const authService = {getState: vi.fn(() => ({ status: "restoring" })),@@ -634,6 +681,165 @@ describe("PiSessionController", () => {);});+ it("notifies when a live completion arrives before history hydration", async () => {+ let onEvent: (+ event: AgentConversationEvent,+ context?: PiConversationEventContext,+ ) => void = () => {};+ let resolveConversation: (events: AgentConversationEvent[]) => void =+ () => {};+ const conversation = new Promise<AgentConversationEvent[]>((resolve) => {+ resolveConversation = resolve;+ });+ const session = createSession();+ vi.mocked(session.getConversation).mockReturnValue(conversation);+ vi.mocked(session.onConversationEvent).mockImplementation((handler) => {+ onEvent = handler;+ return () => {};+ });+ const notifier = { notify: vi.fn() };+ const controller = createController(+ session,+ undefined,+ undefined,+ notifier,+ );+ controller.setNotificationContext("task-1", {+ taskTitle: "Fix notifications",+ });++ const connection = controller.connect("task-1");+ await vi.waitFor(() => {+ expect(session.onConversationEvent).toHaveBeenCalledOnce();+ });+ onEvent(+ { type: "turn_completed", timestamp: 52, stopReason: "stop" },+ { isLive: true },+ );++ expect(notifier.notify).toHaveBeenCalledWith({+ kind: "turn_completed",+ taskId: "task-1",+ taskTitle: "Fix notifications",+ stopReason: "end_turn",+ durationMs: undefined,+ isTaskAuthor: undefined,+ });++ resolveConversation([]);+ await connection;+ });++ it("notifies once for a live completed turn without replaying historical completions", async () => {+ let onEvent: (+ event: AgentConversationEvent,+ context?: PiConversationEventContext,+ ) => void = () => {};+ const session = createSession();+ vi.mocked(session.onConversationEvent).mockImplementation((handler) => {+ onEvent = handler;+ return () => {};+ });+ const notifier = { notify: vi.fn() };+ const controller = createController(+ session,+ undefined,+ undefined,+ notifier,+ );+ controller.setNotificationContext("task-1", {+ taskTitle: "Fix notifications",+ isTaskAuthor: true,+ });+ await controller.connect("task-1");++ onEvent(+ {+ type: "user_message",+ id: "historical-user",+ timestamp: 1,+ content: [{ type: "text", text: "old turn" }],+ },+ { isLive: false },+ );+ onEvent(+ { type: "turn_completed", timestamp: 2, stopReason: "stop" },+ { isLive: false },+ );+ expect(notifier.notify).not.toHaveBeenCalled();++ onEvent(+ {+ type: "user_message",+ id: "live-user",+ timestamp: 10,+ content: [{ type: "text", text: "new turn" }],+ },+ { isLive: true },+ );+ onEvent(+ { type: "turn_completed", timestamp: 52, stopReason: "stop" },+ { isLive: true },+ );+ onEvent(+ { type: "turn_completed", timestamp: 53, stopReason: "stop" },+ { isLive: true },+ );++ expect(notifier.notify).toHaveBeenCalledOnce();+ expect(notifier.notify).toHaveBeenCalledWith({+ kind: "turn_completed",+ taskId: "task-1",+ taskTitle: "Fix notifications",+ stopReason: "end_turn",+ durationMs: 42,+ isTaskAuthor: true,+ });+ });++ it("keeps a backgrounded Pi turn subscribed until it completes", async () => {+ let onEvent: (event: AgentConversationEvent) => void = () => {};+ const unsubscribe = vi.fn();+ const session = createSession();+ vi.mocked(session.onConversationEvent).mockImplementation((handler) => {+ onEvent = handler;+ return unsubscribe;+ });+ const controller = createController(session);++ await controller.connect("task-1");+ await controller.submit("task-1", "continue", false, "steer");+ controller.release("task-1");++ expect(unsubscribe).not.toHaveBeenCalled();++ onEvent({ type: "turn_completed", timestamp: Date.now() });++ expect(unsubscribe).toHaveBeenCalledOnce();+ });++ it("releases a session that finishes connecting after its view unmounts", async () => {+ let resolveHealth: () => void = () => {};+ const health = new Promise<void>((resolve) => {+ resolveHealth = resolve;+ });+ const unsubscribe = vi.fn();+ const session = createSession();+ vi.mocked(session.health).mockImplementation(async () => {+ await health;+ return { state: "idle" };+ });+ vi.mocked(session.onConversationEvent).mockReturnValue(unsubscribe);+ const controller = createController(session);++ const readiness = controller.ensureConnected("task-1");+ controller.release("task-1");+ resolveHealth();+ await readiness;++ expect(unsubscribe).toHaveBeenCalledOnce();+ });+it("restores a native queue after retry replaces the runtime", async () => {let onEvent: (event: AgentConversationEvent) => void = () => {};const session = createSession();diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.tsindex d9ff0d6a3acd..4ed75a71da24 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts@@ -22,6 +22,10 @@ import type { AuthService } from "../auth/auth";import { AUTH_SERVICE } from "../auth/auth.module";import { AuthServiceEvent } from "../auth/schemas";import { parseCommandLine } from "../message-editor/commands";+import {+ AGENT_SESSION_NOTIFIER,+ type AgentSessionNotifier,+} from "../notification/agentSessionNotifications";import { TASK_SERVICE, type TaskService } from "../task-detail/taskService";import {createEmptyPiControllerSession,@@ -45,6 +49,15 @@ export interface PiDeferredConfig {thinkingLevel?: PiThinkingLevel;}+export interface PiSessionNotificationContext {+ taskTitle: string;+ isTaskAuthor?: boolean;+}++export interface PiConversationEventContext {+ isLive: boolean;+}+export const PI_SESSION_PROVIDER = Symbol.for("posthog.pi.sessionProvider");export const LOCAL_PI_SESSION_FACTORY = Symbol.for("posthog.pi.localSessionFactory",@@ -70,7 +83,10 @@ export interface PiSession {health(): Promise<PiRuntimeHealth>;getConversation(): Promise<AgentConversationEvent[]>;onConversationEvent(- onEvent: (event: AgentConversationEvent) => void,+ onEvent: (+ event: AgentConversationEvent,+ context?: PiConversationEventContext,+ ) => void,onError: (error: unknown) => void,onCloudStatus?: (status: TaskRunStatus) => void,): () => void;@@ -101,6 +117,10 @@ export type PiSessionProvider = PiSessionFactory;export type PiSubmitResult = "prompt" | "steer" | "followUp" | "compact";+type PiTurnState =+ | { phase: "active"; startedAt?: number; stopReason?: string }+ | { phase: "completed" };+type PiOperation =| "prompt"| "compact"@@ -156,6 +176,11 @@ export class PiSessionController {private readonly cancelAuthRestoration = new Map<string, () => void>();private readonly taskRunIds = new Map<string, string>();private readonly activeTaskIds = new Set<string>();+ private readonly notificationContexts = new Map<+ string,+ PiSessionNotificationContext+ >();+ private readonly turnStates = new Map<string, PiTurnState>();constructor(@inject(PI_SESSION_PROVIDER) private readonly provider: PiSessionProvider,@@ -163,7 +188,23 @@ export class PiSessionController {@inject(AUTH_SERVICE)@optional()private readonly authService?: AuthService,- ) {}+ @inject(AGENT_SESSION_NOTIFIER)+ @optional()+ private readonly notifier?: AgentSessionNotifier,+ ) {+ this.authService?.on(AuthServiceEvent.StateChanged, (state) => {+ if (state.status === "anonymous") {+ this.disconnectAll();+ }+ });+ }++ setNotificationContext(+ taskId: string,+ context: PiSessionNotificationContext,+ ): void {+ this.notificationContexts.set(taskId, context);+ }ensureConnected(taskId: string, taskRunId?: string): Promise<void> {this.activeTaskIds.add(taskId);@@ -199,6 +240,7 @@ export class PiSessionController {if (this.readiness.get(taskId) === readiness) {this.readiness.delete(taskId);}+ this.disposeInactiveSessionIfIdle(taskId);});this.readiness.set(taskId, readiness);return readiness;@@ -208,7 +250,10 @@ export class PiSessionController {this.activeTaskIds.add(taskId);this.bindTaskRun(taskId, taskRunId);this.ensureSubscription(taskId);+ return this.connectSession(taskId);+ }+ private connectSession(taskId: string): Promise<void> {const existing = this.connections.get(taskId);if (existing) {return existing;@@ -225,15 +270,26 @@ export class PiSessionController {return connection;}+ release(taskId: string): void {+ this.activeTaskIds.delete(taskId);+ this.disposeInactiveSessionIfIdle(taskId);+ }+disconnect(taskId: string): void {- this.cancelAuthRestoration.get(taskId)?.();- this.resetTransport(taskId);- this.taskRunIds.delete(taskId);- this.liveEvents.delete(taskId);- this.queueRevisions.delete(taskId);- this.queuesToRestore.delete(taskId);this.activeTaskIds.delete(taskId);- this.updateSession(taskId, { mcpToolPermissionRequests: new Map() });+ this.disposeTask(taskId);+ }++ disconnectAll(): void {+ const taskIds = new Set([+ ...this.activeTaskIds,+ ...this.sessions.keys(),+ ...this.subscriptions.keys(),+ ...this.notificationContexts.keys(),+ ]);+ for (const taskId of taskIds) {+ this.disconnect(taskId);+ }}async retry(taskId: string): Promise<void> {@@ -585,6 +641,10 @@ export class PiSessionController {}async abort(taskId: string): Promise<void> {+ const turn = this.turnStates.get(taskId);+ if (turn?.phase === "active") {+ this.turnStates.set(taskId, { ...turn, stopReason: "cancelled" });+ }try {const session = await this.getPiSession(taskId);await session.client.abort();@@ -622,9 +682,7 @@ export class PiSessionController {this.ensureSubscription(taskId);}- if (this.activeTaskIds.has(taskId)) {- await this.connect(taskId);- }+ await this.connectSession(taskId);}private ensureSubscription(taskId: string): void {@@ -643,19 +701,31 @@ export class PiSessionController {this.applyPersistedConfig(taskId, session);this.updateSession(taskId, { cloudStatus: session.cloudStatus });unsubscribeConversation = session.onConversationEvent(- (event) => this.handleEvent(taskId, event),+ (event, context) => this.handleEvent(taskId, event, context),(error) => this.applySessionError(taskId, error),- (cloudStatus) => this.updateSession(taskId, { cloudStatus }),+ (cloudStatus) => this.handleCloudStatus(taskId, cloudStatus),);unsubscribePermission = session.onMcpToolPermissionRequest?.((request) => {const requests = new Map(this.getSession(taskId).mcpToolPermissionRequests,);+ if (requests.has(request.requestId)) {+ return;+ }requests.set(request.requestId, request);this.updateSession(taskId, {mcpToolPermissionRequests: requests,});+ const context = this.notificationContexts.get(taskId);+ if (context) {+ this.notifier?.notify({+ kind: "needs_input",+ taskId,+ taskTitle: context.taskTitle,+ isTaskAuthor: context.isTaskAuthor,+ });+ }},(error) => this.applySessionError(taskId, error),);@@ -758,6 +828,12 @@ export class PiSessionController {resolvedQueue.steering.length + resolvedQueue.followUp.length,};+ this.reconcileTurnState(+ taskId,+ reconciledEvents,+ resolvedStatus.isStreaming,+ );+this.setSession(taskId, {connectionState: "connected",events: reconciledEvents,@@ -817,6 +893,8 @@ export class PiSessionController {}}),]);++ this.disposeInactiveSessionIfIdle(taskId);} catch (error) {if (this.getSessionVersion(taskId) === connectedSessionVersion) {this.applySessionError(taskId, error);@@ -825,7 +903,11 @@ export class PiSessionController {}}- private handleEvent(taskId: string, event: AgentConversationEvent): void {+ private handleEvent(+ taskId: string,+ event: AgentConversationEvent,+ context?: PiConversationEventContext,+ ): void {if (event.type === "queue_update") {const queue = {steering: event.steering,@@ -843,6 +925,9 @@ export class PiSessionController {return;}+ const isLive = context?.isLive ?? true;+ this.applyTurnEvent(taskId, event, isLive);+if (event.type === "runtime_error") {this.recordOperationFailure(taskId,@@ -918,7 +1003,107 @@ export class PiSessionController {if (event.type === "turn_completed") {void this.refreshStats(taskId);+ this.disposeInactiveSessionIfIdle(taskId);+ }+ }++ private reconcileTurnState(+ taskId: string,+ events: AgentConversationEvent[],+ isStreaming: boolean,+ ): void {+ this.turnStates.delete(taskId);+ for (const event of events) {+ this.applyTurnEvent(taskId, event, false);+ }+ if (isStreaming && this.turnStates.get(taskId)?.phase !== "active") {+ this.turnStates.set(taskId, { phase: "active" });+ }+ }++ private applyTurnEvent(+ taskId: string,+ event: AgentConversationEvent,+ isLive: boolean,+ ): void {+ const current = this.turnStates.get(taskId);+ const activeTurn = current?.phase === "active" ? current : undefined;+ const isDirectBash =+ (event.type === "tool_call_started" ||+ event.type === "tool_call_updated") &&+ event.toolCall.origin === "user_shell";+ const hasTurnActivity =+ event.type === "user_message" ||+ event.type === "assistant_message_chunk" ||+ event.type === "assistant_thought_chunk" ||+ (!isDirectBash &&+ (event.type === "tool_call_started" ||+ event.type === "tool_call_updated"));++ if (hasTurnActivity) {+ this.turnStates.set(taskId, {+ phase: "active",+ startedAt:+ activeTurn?.startedAt ??+ (event.type === "user_message" ? event.timestamp : undefined),+ });+ return;+ }++ if (event.type === "runtime_error") {+ this.turnStates.set(taskId, {+ phase: "active",+ startedAt: activeTurn?.startedAt,+ stopReason: "failed",+ });+ return;}++ if (event.type !== "turn_completed") {+ return;+ }++ this.turnStates.set(taskId, { phase: "completed" });+ if (!isLive || current?.phase === "completed") {+ return;+ }++ const notificationContext = this.notificationContexts.get(taskId);+ if (!notificationContext) {+ return;+ }++ const stopReason = this.normalizeStopReason(+ event.stopReason ?? activeTurn?.stopReason,+ );+ const durationMs = activeTurn?.startedAt+ ? Math.max(0, event.timestamp - activeTurn.startedAt)+ : undefined;+ this.notifier?.notify({+ kind: "turn_completed",+ taskId,+ taskTitle: notificationContext.taskTitle,+ stopReason,+ durationMs,+ isTaskAuthor: notificationContext.isTaskAuthor,+ });+ }++ private normalizeStopReason(stopReason: string | undefined): string {+ if (stopReason === "stop" || stopReason === undefined) {+ return "end_turn";+ }+ if (stopReason === "aborted") {+ return "cancelled";+ }+ if (stopReason === "error") {+ return "failed";+ }+ return stopReason;+ }++ private handleCloudStatus(taskId: string, cloudStatus: TaskRunStatus): void {+ this.updateSession(taskId, { cloudStatus });}private async refreshStats(taskId: string): Promise<void> {@@ -1178,6 +1363,10 @@ export class PiSessionController {}private markTurnPending(taskId: string): void {+ const current = this.turnStates.get(taskId);+ const startedAt =+ current?.phase === "active" ? current.startedAt : Date.now();+ this.turnStates.set(taskId, { phase: "active", startedAt });this.setTurnStreaming(taskId, true);}@@ -1318,6 +1507,45 @@ export class PiSessionController {this.taskRunIds.set(taskId, taskRunId);}+ private disposeInactiveSessionIfIdle(taskId: string): void {+ if (+ this.activeTaskIds.has(taskId) ||+ this.shouldRetainInactiveSession(taskId)+ ) {+ return;+ }+ this.disposeTask(taskId);+ }++ private shouldRetainInactiveSession(taskId: string): boolean {+ const session = this.getSession(taskId);+ if (+ session.connectionState === "connecting" ||+ session.status?.isStreaming ||+ this.turnStates.get(taskId)?.phase === "active"+ ) {+ return true;+ }+ return (+ session.cloudStatus !== undefined &&+ session.cloudStatus !== "completed" &&+ session.cloudStatus !== "failed" &&+ session.cloudStatus !== "cancelled"+ );+ }++ private disposeTask(taskId: string): void {+ this.cancelAuthRestoration.get(taskId)?.();+ this.resetTransport(taskId);+ this.taskRunIds.delete(taskId);+ this.liveEvents.delete(taskId);+ this.queueRevisions.delete(taskId);+ this.queuesToRestore.delete(taskId);+ this.turnStates.delete(taskId);+ this.notificationContexts.delete(taskId);+ this.updateSession(taskId, { mcpToolPermissionRequests: new Map() });+ }+private resetTransport(taskId: string): void {this.advanceSessionVersion(taskId);this.disposeConversationSubscription(taskId);diff --git a/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts b/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.tsindex d8b73f09ad1f..ed8400bc2dbf 100644--- a/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts+++ b/products/desktop/packages/core/src/sessions/cloudTaskUpdateNotifications.test.ts@@ -145,6 +145,32 @@ function createHarness(isTaskAuthor = true) {const notifyPermissionRequest = vi.fn();const enqueueSpeech = vi.fn();const markActivity = vi.fn();+ const notifyAgentSession: SessionServiceDeps["notifyAgentSession"] = (+ notification,+ ) => {+ if (notification.isTaskAuthor === false) {+ return;+ }+ if (notification.kind === "needs_input") {+ notifyPermissionRequest(notification.taskTitle, notification.taskId);+ if (!notification.agentSpoke) {+ enqueueSpeech({ kind: "needs_input", source: "backstop" });+ }+ return;+ }+ if (notification.stopReason !== "end_turn") {+ return;+ }+ notifyPromptComplete(+ notification.taskTitle,+ notification.stopReason,+ notification.taskId,+ notification.durationMs,+ );+ if (!notification.agentSpoke) {+ enqueueSpeech({ kind: "done", source: "backstop" });+ }+ };const noopLog = {info: vi.fn(),warn: vi.fn(),@@ -155,8 +181,7 @@ function createHarness(isTaskAuthor = true) {const deps = {store,log: noopLog,- notifyPromptComplete,- notifyPermissionRequest,+ notifyAgentSession,enqueueSpeech,taskViewedApi: { markActivity },getPersistedConfigOptions: () => undefined,diff --git a/products/desktop/packages/core/src/sessions/sessionEventBatching.test.ts b/products/desktop/packages/core/src/sessions/sessionEventBatching.test.tsindex c1d47f2c645c..c0799d89741e 100644--- a/products/desktop/packages/core/src/sessions/sessionEventBatching.test.ts+++ b/products/desktop/packages/core/src/sessions/sessionEventBatching.test.ts@@ -85,8 +85,22 @@ function createHarness() {const deps = {store,log: noopLog,- notifyPromptComplete,- notifyPermissionRequest: vi.fn(),+ notifyAgentSession: (notification: {+ kind: string;+ taskTitle: string;+ taskId: string;+ stopReason?: string;+ durationMs?: number;+ }) => {+ if (notification.kind === "turn_completed") {+ notifyPromptComplete(+ notification.taskTitle,+ notification.stopReason,+ notification.taskId,+ notification.durationMs,+ );+ }+ },enqueueSpeech: vi.fn(),taskViewedApi: { markActivity: vi.fn() },getPersistedConfigOptions: () => undefined,diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.tsindex 7d1a14ec1d1d..33a4ae7542e1 100644--- a/products/desktop/packages/core/src/sessions/sessionService.ts+++ b/products/desktop/packages/core/src/sessions/sessionService.ts@@ -54,6 +54,7 @@ import {type Task,} from "@posthog/shared/domain-types";import type { CommentTarget } from "../comments/anchors";+import type { AgentSessionNotification } from "../notification/agentSessionNotifications";import type { SpeechKind, SpeechSource } from "../speech/identifiers";import {CONTEXT_WINDOW_OPTION_CATEGORY,@@ -366,8 +367,7 @@ export interface SessionServiceDeps {};track: (event: string, props?: Record<string, unknown>) => void;buildPermissionToolMetadata: (...args: any[]) => any;- notifyPermissionRequest: (...args: any[]) => any;- notifyPromptComplete: (...args: any[]) => any;+ notifyAgentSession: (notification: AgentSessionNotification) => void;enqueueSpeech: (request: {text: string;taskTitle: string;@@ -415,6 +415,11 @@ type AuthClient = NonNullable<Awaited<ReturnType<SessionServiceDeps["getAuthenticatedClient"]>>>;+type NotifiableAgentSession = Pick<+ AgentSession,+ "taskTitle" | "taskId" | "promptStartedAt" | "isTaskAuthor"+>;+interface AuthCredentials {apiHost: string;projectId: number;@@ -3028,15 +3033,12 @@ export class SessionService {stopReason === "end_turn" &&session.messageQueue.length === 0) {- if (session.isTaskAuthor !== false) {- this.d.notifyPromptComplete(- session.taskTitle,- stopReason,- session.taskId,- turnStartedAtTs ? acpMsg.ts - turnStartedAtTs : undefined,- );- this.speakDeterministic(taskRunId, session, "done");- }+ this.notifyTurnCompleted(+ taskRunId,+ session,+ stopReason,+ turnStartedAtTs ? acpMsg.ts - turnStartedAtTs : undefined,+ );}this.d.taskViewedApi.markActivity(session.taskId);this.finalizeTurnContent(taskRunId, "turn_complete", acpMsg.ts);@@ -3115,36 +3117,50 @@ export class SessionService {}}- /**- * Deterministic backstop for the two moments the user must not miss. Fired- * from the turn-complete and permission events (which happen every time),- * unless the agent already narrated that same moment this turn via the speak- * tool — in which case its expressive line stands. Routes through the same- * speech channel (focus + settings gating + serialized queue).- */- private speakDeterministic(+ private notifyTurnCompleted(taskRunId: string,- session: {- taskTitle: string;- taskId: string;- promptStartedAt: number | null;- },- kind: "done" | "needs_input",+ session: NotifiableAgentSession,+ stopReason: string,+ durationMs?: number,): void {- const turnStart = session.promptStartedAt ?? 0;- const spokeAt = this.agentSpokeAt.get(taskRunId)?.[kind] ?? 0;- if (turnStart > 0 && spokeAt >= turnStart) return; // agent already voiced it- // Deterministic backstop stays plain — no "Hey <name>," greeting.- this.d.enqueueSpeech({- text: kind === "done" ? "finished" : "needs your input",+ this.d.notifyAgentSession({+ kind: "turn_completed",taskTitle: session.taskTitle,taskId: session.taskId,- kind,- source: "backstop",- addressByName: false,+ stopReason,+ durationMs,+ isTaskAuthor: session.isTaskAuthor,+ agentSpoke: this.agentSpokeSinceTurnStarted(taskRunId, session, "done"),+ });+ }++ private notifyNeedsInput(+ taskRunId: string,+ session: NotifiableAgentSession,+ ): void {+ this.d.notifyAgentSession({+ kind: "needs_input",+ taskTitle: session.taskTitle,+ taskId: session.taskId,+ isTaskAuthor: session.isTaskAuthor,+ agentSpoke: this.agentSpokeSinceTurnStarted(+ taskRunId,+ session,+ "needs_input",+ ),});}+ private agentSpokeSinceTurnStarted(+ taskRunId: string,+ session: Pick<AgentSession, "promptStartedAt">,+ kind: "done" | "needs_input",+ ): boolean {+ const turnStart = session.promptStartedAt ?? 0;+ const spokeAt = this.agentSpokeAt.get(taskRunId)?.[kind] ?? 0;+ return turnStart > 0 && spokeAt >= turnStart;+ }+private handleSessionEvent(taskRunId: string, acpMsg: AcpMessage): void {const session = this.d.store.getSessions()[taskRunId];if (!session) return;@@ -3200,20 +3216,13 @@ export class SessionService {: this.drainQueuedMessages(taskRunId, session);// Only notify when nothing is sendable - queued messages start a new turn- if (- stopReason &&- !hasSendableMessages &&- session.isTaskAuthor !== false- ) {- this.d.notifyPromptComplete(- session.taskTitle,+ if (stopReason && !hasSendableMessages) {+ this.notifyTurnCompleted(+ taskRunId,+ session,stopReason,- session.taskId,turnStartedAtTs ? acpMsg.ts - turnStartedAtTs : undefined,);- if (stopReason === "end_turn") {- this.speakDeterministic(taskRunId, session, "done");- }}this.d.taskViewedApi.markActivity(session.taskId);@@ -3450,10 +3459,7 @@ export class SessionService {this.d.store.setPendingPermissions(taskRunId, newPermissions);this.d.taskViewedApi.markActivity(session.taskId);- if (session.isTaskAuthor !== false) {- this.d.notifyPermissionRequest(session.taskTitle, session.taskId);- this.speakDeterministic(taskRunId, session, "needs_input");- }+ this.notifyNeedsInput(taskRunId, session);}private handleCloudPermissionRequest(@@ -3510,10 +3516,7 @@ export class SessionService {this.d.store.setPendingPermissions(taskRunId, newPermissions);this.d.taskViewedApi.markActivity(session.taskId);- if (session.isTaskAuthor !== false) {- this.d.notifyPermissionRequest(session.taskTitle, session.taskId);- this.speakDeterministic(taskRunId, session, "needs_input");- }+ this.notifyNeedsInput(taskRunId, session);}private surfacePersistedPendingPermissions(diff --git a/products/desktop/packages/host-router/src/pi-session-factory.ts b/products/desktop/packages/host-router/src/pi-session-factory.tsindex 34f4ad2b79b3..7ef0cd4eea94 100644--- a/products/desktop/packages/host-router/src/pi-session-factory.ts+++ b/products/desktop/packages/host-router/src/pi-session-factory.ts@@ -116,7 +116,7 @@ class TrpcPiSession implements PiSession {): () => void {const subscription = this.hostClient.piSession.onEvent.subscribe({ taskId: this.taskId },- { onData: onEvent, onError },+ { onData: (event) => onEvent(event, { isLive: true }), onError },);return () => subscription.unsubscribe();diff --git a/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.test.ts b/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.test.tsnew file mode 100644index 000000000000..1e16c6df6f26--- /dev/null+++ b/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it, vi } from "vitest";+import { AgentSessionNotificationService } from "./agentSessionNotifications";+import type { NotificationBus } from "./notifications";+import type { SpeechNotifier } from "./speechNotifier";++function createService() {+ const notifications = {+ notifyPermissionRequest: vi.fn(),+ notifyPromptComplete: vi.fn(),+ } as unknown as NotificationBus;+ const speech = { speak: vi.fn() } as unknown as SpeechNotifier;+ const service = new AgentSessionNotificationService(notifications, speech);+ return { notifications, service, speech };+}++describe("AgentSessionNotificationService", () => {+ it("routes a completed turn through the shared notification channels", () => {+ const { notifications, service, speech } = createService();++ service.notify({+ kind: "turn_completed",+ taskId: "task-1",+ taskTitle: "Fix notifications",+ stopReason: "end_turn",+ durationMs: 42_000,+ isTaskAuthor: true,+ });++ expect(notifications.notifyPromptComplete).toHaveBeenCalledWith(+ "Fix notifications",+ "end_turn",+ "task-1",+ 42_000,+ );+ expect(speech.speak).toHaveBeenCalledWith(+ expect.objectContaining({+ kind: "done",+ source: "backstop",+ taskId: "task-1",+ }),+ );+ });++ it("routes input requests without repeating agent narration", () => {+ const { notifications, service, speech } = createService();++ service.notify({+ kind: "needs_input",+ taskId: "task-1",+ taskTitle: "Fix notifications",+ isTaskAuthor: true,+ agentSpoke: true,+ });++ expect(notifications.notifyPermissionRequest).toHaveBeenCalledWith(+ "Fix notifications",+ "task-1",+ );+ expect(speech.speak).not.toHaveBeenCalled();+ });++ it.each([false, undefined])(+ "does not notify when task ownership is %s",+ (isTaskAuthor) => {+ const { notifications, service, speech } = createService();++ service.notify({+ kind: "turn_completed",+ taskId: "task-1",+ taskTitle: "Fix notifications",+ stopReason: "end_turn",+ isTaskAuthor,+ });++ expect(notifications.notifyPromptComplete).not.toHaveBeenCalled();+ expect(speech.speak).not.toHaveBeenCalled();+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.ts b/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.tsnew file mode 100644index 000000000000..bef6165b6130--- /dev/null+++ b/products/desktop/packages/ui/src/features/notifications/agentSessionNotifications.ts@@ -0,0 +1,58 @@+import type {+ AgentSessionNotification,+ AgentSessionNotifier,+} from "@posthog/core/notification/agentSessionNotifications";+import { inject, injectable } from "inversify";+import { NotificationBus } from "./notifications";+import { SpeechNotifier } from "./speechNotifier";++@injectable()+export class AgentSessionNotificationService implements AgentSessionNotifier {+ constructor(+ @inject(NotificationBus)+ private readonly notifications: NotificationBus,+ @inject(SpeechNotifier)+ private readonly speech: SpeechNotifier,+ ) {}++ notify(notification: AgentSessionNotification): void {+ if (notification.isTaskAuthor !== true) {+ return;+ }++ if (notification.kind === "needs_input") {+ this.notifications.notifyPermissionRequest(+ notification.taskTitle,+ notification.taskId,+ );+ if (!notification.agentSpoke) {+ this.speech.speak({+ text: "needs your input",+ taskTitle: notification.taskTitle,+ taskId: notification.taskId,+ kind: "needs_input",+ source: "backstop",+ addressByName: false,+ });+ }+ return;+ }++ this.notifications.notifyPromptComplete(+ notification.taskTitle,+ notification.stopReason,+ notification.taskId,+ notification.durationMs,+ );+ if (notification.stopReason === "end_turn" && !notification.agentSpoke) {+ this.speech.speak({+ text: "finished",+ taskTitle: notification.taskTitle,+ taskId: notification.taskId,+ kind: "done",+ source: "backstop",+ addressByName: false,+ });+ }+ }+}diff --git a/products/desktop/packages/ui/src/features/notifications/notifications.module.ts b/products/desktop/packages/ui/src/features/notifications/notifications.module.tsindex 52c629c4379e..04952633c5c5 100644--- a/products/desktop/packages/ui/src/features/notifications/notifications.module.ts+++ b/products/desktop/packages/ui/src/features/notifications/notifications.module.ts@@ -1,8 +1,12 @@+import { AGENT_SESSION_NOTIFIER } from "@posthog/core/notification/agentSessionNotifications";import { ContainerModule } from "inversify";+import { AgentSessionNotificationService } from "./agentSessionNotifications";import { NotificationBus } from "./notifications";import { SpeechNotifier } from "./speechNotifier";export const notificationsUiModule = new ContainerModule(({ bind }) => {bind(NotificationBus).toSelf().inSingletonScope();bind(SpeechNotifier).toSelf().inSingletonScope();+ bind(AgentSessionNotificationService).toSelf().inSingletonScope();+ bind(AGENT_SESSION_NOTIFIER).toService(AgentSessionNotificationService);});diff --git a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsxindex 40799fcc850f..93b186ecda9f 100644--- a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx+++ b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx@@ -30,6 +30,9 @@ import {Skeleton,} from "@posthog/quill";import { MCP_TOOL_PERMISSION_OPTIONS } from "@posthog/shared";+import type { Task } from "@posthog/shared/domain-types";+import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";+import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";import { useUsageLimitStore } from "@posthog/ui/features/billing/usageLimitStore";import { PromptInput } from "@posthog/ui/features/message-editor/components/PromptInput";import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";@@ -69,8 +72,7 @@ import {const log = logger.scope("pi-session-view");interface PiSessionViewProps {- taskId: string;- taskRunId?: string;+ task: Task;isCloud: boolean;}@@ -87,13 +89,23 @@ type SetMessagingMode = ReturnType<>["setMode"];function usePiSessionConnection(- taskId: string,- taskRunId: string | undefined,+ task: Task,+ isTaskAuthor: boolean | undefined,): void {const controller = useService<PiSessionController>(PI_SESSION_CONTROLLER);+ const taskId = task.id;+ const taskRunId = task.latest_run?.id;++ useEffect(() => {+ controller.setNotificationContext(taskId, {+ taskTitle: task.title,+ isTaskAuthor,+ });+ }, [controller, isTaskAuthor, task.title, taskId]);+useEffect(() => {void controller.ensureConnected(taskId, taskRunId).catch(() => {});- return () => controller.disconnect(taskId);+ return () => controller.release(taskId);}, [controller, taskId, taskRunId]);}@@ -453,11 +465,15 @@ function usePiRemoveQueue(}, [controller, taskId]);}-export function PiSessionView({- taskId,- taskRunId,- isCloud,-}: PiSessionViewProps) {+export function PiSessionView({ task, isCloud }: PiSessionViewProps) {+ const taskId = task.id;+ const taskRunId = task.latest_run?.id;+ const authenticatedClient = useOptionalAuthenticatedClient();+ const { data: currentUser } = useCurrentUser({ client: authenticatedClient });+ const isTaskAuthor =+ currentUser?.uuid && task.created_by?.uuid+ ? currentUser.uuid === task.created_by.uuid+ : undefined;const piSessionController = useService<PiSessionController>(PI_SESSION_CONTROLLER,);@@ -495,7 +511,7 @@ export function PiSessionView({[],);- usePiSessionConnection(taskId, taskRunId);+ usePiSessionConnection(task, isTaskAuthor);usePiExtensionConnection(taskId,taskRunId,diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.tsindex 422203c6b12f..b7611bf8cc42 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts@@ -188,6 +188,31 @@ vi.mock("@posthog/di/container", () => ({if (typeof token === "function" && token.name === "NotificationBus") {return mockNotificationService;}+ if (token === Symbol.for("posthog.notification.agentSessionNotifier")) {+ return {+ notify: (notification: {+ kind: "needs_input" | "turn_completed";+ taskTitle: string;+ taskId: string;+ stopReason?: string;+ durationMs?: number;+ }) => {+ if (notification.kind === "needs_input") {+ mockNotificationService.notifyPermissionRequest(+ notification.taskTitle,+ notification.taskId,+ );+ } else {+ mockNotificationService.notifyPromptComplete(+ notification.taskTitle,+ notification.stopReason,+ notification.taskId,+ notification.durationMs,+ );+ }+ },+ };+ }throw new Error(`resolveService: unmocked token ${String(token)}`);},}));diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.tsindex 7a384e70d1f8..8f49ba8956ce 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts@@ -238,6 +238,36 @@ const mockSpeechNotifier = vi.hoisted(() => ({speak: vi.fn(),}));+const mockAgentSessionNotifier = vi.hoisted(() => ({+ notify: vi.fn(+ (notification: {+ kind: "needs_input" | "turn_completed";+ taskTitle: string;+ taskId: string;+ stopReason?: string;+ durationMs?: number;+ isTaskAuthor?: boolean;+ }) => {+ if (notification.isTaskAuthor === false) {+ return;+ }+ if (notification.kind === "needs_input") {+ mockNotificationService.notifyPermissionRequest(+ notification.taskTitle,+ notification.taskId,+ );+ return;+ }+ mockNotificationService.notifyPromptComplete(+ notification.taskTitle,+ notification.stopReason,+ notification.taskId,+ notification.durationMs,+ );+ },+ ),+}));+const mockFeatureFlags = vi.hoisted(() => ({isEnabled: vi.fn(() => false),onFlagsLoaded: vi.fn(() => vi.fn()),@@ -322,6 +352,9 @@ vi.mock("@posthog/di/container", () => ({if (typeof token === "function" && token.name === "SpeechNotifier") {return mockSpeechNotifier;}+ if (token === Symbol.for("posthog.notification.agentSessionNotifier")) {+ return mockAgentSessionNotifier;+ }if (token === Symbol.for("posthog.ui.featureFlags")) {return mockFeatureFlags;}diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.tsindex 70522ffc080e..54b8b334a2b6 100644--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts@@ -1,5 +1,9 @@import { DEFAULT_GATEWAY_MODEL } from "@posthog/agent/gateway-models";import { getIsOnline } from "@posthog/core/connectivity/connectivityStore";+import {+ AGENT_SESSION_NOTIFIER,+ type AgentSessionNotifier,+} from "@posthog/core/notification/agentSessionNotifications";import { CloudArtifactService } from "@posthog/core/sessions/cloudArtifactService";import {combineQueuedCloudPrompts,@@ -27,7 +31,6 @@ import {type FeatureFlags,} from "@posthog/ui/features/feature-flags/identifiers";import { useAddDirectoryDialogStore } from "@posthog/ui/features/folder-picker/addDirectoryDialogStore";-import { NotificationBus } from "@posthog/ui/features/notifications/notifications";import { SpeechNotifier } from "@posthog/ui/features/notifications/speechNotifier";import { useSessionAdapterStore } from "@posthog/ui/features/sessions/sessionAdapterStore";import {@@ -96,17 +99,9 @@ function buildSessionServiceDeps(): SessionServiceDeps {);},buildPermissionToolMetadata,- notifyPermissionRequest: (taskTitle, taskId) =>- resolveService(NotificationBus).notifyPermissionRequest(- taskTitle,- taskId,- ),- notifyPromptComplete: (taskTitle, stopReason, taskId, durationMs) =>- resolveService(NotificationBus).notifyPromptComplete(- taskTitle,- stopReason,- taskId,- durationMs,+ notifyAgentSession: (notification) =>+ resolveService<AgentSessionNotifier>(AGENT_SESSION_NOTIFIER).notify(+ notification,),enqueueSpeech: (request) => resolveService(SpeechNotifier).speak(request),getIsOnline,diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsxindex ed0fd56c149e..269ebcd46ce7 100644--- a/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx+++ b/products/desktop/packages/ui/src/features/task-detail/components/TabContentRenderer.tsx@@ -35,12 +35,7 @@ export function TabContentRenderer({switch (data.type) {case "logs":return task.runtime === "pi" ? (- <PiSessionView- key={taskId}- taskId={taskId}- taskRunId={task.latest_run?.id}- isCloud={isCloud}- />+ <PiSessionView key={taskId} task={task} isCloud={isCloud} />) : (<TaskLogsPanel taskId={taskId} task={task} />);