Skip to content

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

fix(desktop): batch pi streaming and reuse transcript derivation (#98932)

Charles Vienb58061a1fa8c
diff --git a/products/desktop/docs/STREAMING_TRANSCRIPTS.md b/products/desktop/docs/STREAMING_TRANSCRIPTS.md
new file mode 100644
index 000000000000..d936172a42dd
--- /dev/null
+++ b/products/desktop/docs/STREAMING_TRANSCRIPTS.md
@@ -0,0 +1,17 @@
+# Streaming transcripts
+
+Pi text and thought chunks publish together at most once per 16 ms batch.
+Tool, queue, error, and completion events flush preceding text before they apply, preserving transcript order.
+Disconnect cancels pending batches, and source ID indexes reject duplicate delivery without scanning the transcript for each chunk.
+
+Pi and ACP use the same incremental transcript builder.
+Completed rows retain their identity while the active turn streams.
+Pi history revisions invalidate the builder when hydration or an optimistic acknowledgement changes an earlier message.
+The chat footer consumes the body's derived state instead of parsing the same transcript again.
+
+Verification:
+
+- Deliver a burst of chunks and check that one transcript publication contains each source ID once.
+- Complete or disconnect during a pending batch and check ordering and cleanup.
+- Compare incremental output with a full build at every prefix, including late events and tool updates.
+- Replace an optimistic message inside a consumed prefix and check that the confirmed content appears.
diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts
index fd58c6547685..aef3c8e39b59 100644
--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts
+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.test.ts
@@ -6,7 +6,7 @@ import type {
AgentConversationEvent,
McpToolPermissionRequest,
} from "@posthog/shared";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
type PiConversationEventContext,
PiOperationError,
@@ -85,6 +85,133 @@ function createSession(): PiSession {
}
describe("PiSessionController", () => {
+ afterEach(() => vi.useRealTimers());
+ it("publishes a burst once, deduplicates chunks, and flushes before completion", async () => {
+ vi.useFakeTimers();
+ const session = createSession();
+ let receive: (event: AgentConversationEvent) => void = () => {};
+ vi.mocked(session.onConversationEvent).mockImplementation((handler) => {
+ receive = handler;
+ return () => {};
+ });
+ const controller = createController(session);
+ await controller.connect("task-1");
+ await controller.submit("task-1", "continue", false, "steer");
+ const published = vi.fn();
+ controller.store.subscribe(published);
+ const chunks: AgentConversationEvent[] = Array.from(
+ { length: 100 },
+ (_, i) => ({
+ type: "assistant_message_chunk",
+ timestamp: i + 1,
+ sourceId: `chunk-${i}`,
+ content: { type: "text", text: `part ${i}` },
+ }),
+ );
+ for (const chunk of chunks) receive(chunk);
+ receive(chunks[0]);
+ expect(published).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(16);
+ expect(published).toHaveBeenCalledOnce();
+ expect(controller.store.getState().sessions["task-1"].events).toEqual(
+ chunks,
+ );
+ const tail: AgentConversationEvent = {
+ type: "assistant_thought_chunk",
+ timestamp: 101,
+ content: { type: "text", text: "done" },
+ sourceId: "tail",
+ };
+ const completion: AgentConversationEvent = {
+ type: "turn_completed",
+ timestamp: 102,
+ };
+ receive(tail);
+ receive(completion);
+ expect(controller.store.getState().sessions["task-1"].events).toEqual([
+ ...chunks,
+ tail,
+ completion,
+ ]);
+ receive(chunks[0]);
+ vi.advanceTimersByTime(16);
+ expect(
+ controller.store.getState().sessions["task-1"].status?.isStreaming,
+ ).toBe(false);
+ expect(controller.store.getState().sessions["task-1"].events).toHaveLength(
+ 102,
+ );
+ });
+
+ it("keeps a cancelled turn cancelled when a buffered chunk is redelivered", async () => {
+ vi.useFakeTimers();
+ const session = createSession();
+ let receive: (
+ event: AgentConversationEvent,
+ context?: PiConversationEventContext,
+ ) => void = () => {};
+ vi.mocked(session.onConversationEvent).mockImplementation((handler) => {
+ receive = handler;
+ return () => {};
+ });
+ const notifier = { notify: vi.fn() };
+ const controller = createController(
+ session,
+ undefined,
+ undefined,
+ notifier,
+ );
+ await controller.connect("task-1");
+ await controller.submit("task-1", "continue", false, "steer");
+ controller.setNotificationContext("task-1", { taskTitle: "Cancel me" });
+
+ const chunk: AgentConversationEvent = {
+ type: "assistant_message_chunk",
+ timestamp: 1,
+ sourceId: "chunk-0",
+ content: { type: "text", text: "part" },
+ };
+ // The chunk opens an active turn and sits in the 16 ms batch, unflushed.
+ receive(chunk, { isLive: true });
+ // The user cancels while the chunk is still buffered.
+ await controller.abort("task-1");
+ // A redelivery of the same still-buffered chunk must not reopen the turn:
+ // if it reaches applyTurnEvent it discards the "cancelled" stop reason.
+ receive(chunk, { isLive: true });
+ receive({ type: "turn_completed", timestamp: 2 }, { isLive: true });
+ vi.advanceTimersByTime(16);
+
+ expect(notifier.notify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ kind: "turn_completed",
+ stopReason: "cancelled",
+ }),
+ );
+ });
+
+ it("cancels buffered text on disconnect without repopulating released history", async () => {
+ vi.useFakeTimers();
+ const session = createSession();
+ let receive: (event: AgentConversationEvent) => void = () => {};
+ vi.mocked(session.onConversationEvent).mockImplementation((handler) => {
+ receive = handler;
+ return () => {};
+ });
+ const controller = createController(session);
+ await controller.connect("task-1");
+ receive({
+ type: "assistant_message_chunk",
+ timestamp: 1,
+ content: { type: "text", text: "pending" },
+ });
+ controller.disconnect("task-1");
+ vi.advanceTimersByTime(100);
+ expect(controller.store.getState().sessions["task-1"].events).toEqual([]);
+ expect(controller.store.getState().sessions["task-1"].connectionState).toBe(
+ "disconnected",
+ );
+ });
+
it("queues concurrent MCP permission requests", async () => {
const session = createSession();
const unsubscribe = vi.fn();
@@ -705,6 +832,7 @@ describe("PiSessionController", () => {
});
it("keeps a backgrounded Pi turn subscribed until it completes", async () => {
+ vi.useFakeTimers();
let onEvent: (event: AgentConversationEvent) => void = () => {};
const unsubscribe = vi.fn();
const session = createSession();
@@ -722,6 +850,7 @@ describe("PiSessionController", () => {
content: { type: "text", text: "Working" },
});
controller.release("task-1");
+ vi.advanceTimersByTime(16);
expect(unsubscribe).not.toHaveBeenCalled();
expect(controller.store.getState().sessions["task-1"].events).not.toEqual(
@@ -1679,6 +1808,7 @@ describe("PiSessionController", () => {
});
it("does not briefly duplicate retained events during reconnect snapshots", async () => {
+ vi.useFakeTimers();
const retainedEvent: AgentConversationEvent = {
type: "assistant_message_chunk",
timestamp: 1,
@@ -1709,6 +1839,7 @@ describe("PiSessionController", () => {
expect(session.onConversationEvent).toHaveBeenCalledTimes(2),
);
onEvent(retainedEvent);
+ vi.advanceTimersByTime(16);
expect(controller.store.getState().sessions["task-1"].events).toEqual([
retainedEvent,
diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts
index 3bab0b0de13b..67b445687e9f 100644
--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts
+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts
@@ -116,6 +116,15 @@ export type PiSessionProvider = PiSessionFactory;
export type PiSubmitResult = "prompt" | "steer" | "followUp" | "compact";
+type TextEvent = Extract<
+ AgentConversationEvent,
+ {
+ type: "assistant_message_chunk" | "assistant_thought_chunk";
+ }
+>;
+
+const STREAM_BATCH_MS = 16;
+
type PiTurnState =
| { phase: "active"; startedAt?: number; stopReason?: string }
| { phase: "completed" };
@@ -200,6 +209,25 @@ 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 pendingText = new Map<
+ string,
+ {
+ events: TextEvent[];
+ /** Source ids held in this batch. They reach `session.events` only at
+ * flush, so without them a repeat delivery inside one window would pass
+ * the dedup guard and mutate turn state. */
+ sourceIds: Set<string>;
+ timer: ReturnType<typeof setTimeout>;
+ }
+ >();
+ private readonly eventSources = new Map<
+ string,
+ {
+ events: AgentConversationEvent[];
+ ids: Set<string>;
+ }
+ >();
+
private readonly notificationContexts = new Map<
string,
PiSessionNotificationContext
@@ -309,6 +337,7 @@ export class PiSessionController {
disconnect(taskId: string): void {
this.activeTaskIds.delete(taskId);
this.disposeTask(taskId);
+ this.updateSession(taskId, { connectionState: "disconnected" });
}
disconnectAll(): void {
@@ -727,7 +756,7 @@ export class PiSessionController {
this.applyPersistedConfig(taskId, session);
this.updateSession(taskId, { cloudStatus: session.cloudStatus });
unsubscribeConversation = session.onConversationEvent(
- (event, context) => this.handleEvent(taskId, event, context),
+ (event, context) => this.receiveEvent(taskId, event, context),
(error) => this.applySessionError(taskId, error),
(cloudStatus) => this.handleCloudStatus(taskId, cloudStatus),
);
@@ -815,6 +844,7 @@ export class PiSessionController {
return;
}
+ this.flushText(taskId);
const currentSession = this.getSession(taskId);
const conversationEvents = events.filter(
(event) => event.type !== "queue_update",
@@ -866,6 +896,7 @@ export class PiSessionController {
cloudStatus: currentSession.cloudStatus ?? session.cloudStatus,
status: resolvedStatus,
stats,
+ historyVersion: currentSession.historyVersion + 1,
models: currentSession.models,
modelsLoaded: currentSession.modelsLoaded,
thinkingLevels: currentSession.thinkingLevels,
@@ -929,6 +960,87 @@ export class PiSessionController {
}
}
+ private receiveEvent(
+ taskId: string,
+ event: AgentConversationEvent,
+ context?: PiConversationEventContext,
+ ): void {
+ if (
+ event.type !== "assistant_message_chunk" &&
+ event.type !== "assistant_thought_chunk"
+ ) {
+ this.flushText(taskId);
+ this.handleEvent(taskId, event, context);
+ return;
+ }
+ const pending = this.pendingText.get(taskId);
+ if (
+ event.sourceId &&
+ (this.sourceIndex(taskId).ids.has(event.sourceId) ||
+ pending?.sourceIds.has(event.sourceId))
+ )
+ return;
+ // Track activity immediately so navigation cannot dispose a pending batch.
+ this.applyTurnEvent(taskId, event, context?.isLive ?? true);
+ if (!this.getSession(taskId).status?.isStreaming) {
+ this.setTurnStreaming(taskId, true);
+ }
+ if (pending) {
+ pending.events.push(event);
+ if (event.sourceId) pending.sourceIds.add(event.sourceId);
+ } else {
+ this.pendingText.set(taskId, {
+ events: [event],
+ sourceIds: new Set(event.sourceId ? [event.sourceId] : []),
+ timer: setTimeout(() => this.flushText(taskId), STREAM_BATCH_MS),
+ });
+ }
+ }
+
+ private sourceIndex(taskId: string): {
+ events: AgentConversationEvent[];
+ ids: Set<string>;
+ } {
+ const events = this.getSession(taskId).events;
+ let index = this.eventSources.get(taskId);
+ if (!index || index.events !== events) {
+ index = {
+ events,
+ ids: new Set(
+ events.flatMap((event) => (event.sourceId ? [event.sourceId] : [])),
+ ),
+ };
+ this.eventSources.set(taskId, index);
+ }
+ return index;
+ }
+
+ private flushText(taskId: string): void {
+ const pending = this.pendingText.get(taskId);
+ if (!pending) return;
+ clearTimeout(pending.timer);
+ this.pendingText.delete(taskId);
+ const session = this.getSession(taskId);
+ const index = this.sourceIndex(taskId);
+ const accepted = pending.events.filter((event) => {
+ if (!event.sourceId) return true;
+ if (index.ids.has(event.sourceId)) return false;
+ index.ids.add(event.sourceId);
+ return true;
+ });
+ if (accepted.length === 0) return;
+ const events = [...session.events, ...accepted];
+ const liveEvents = this.liveEvents.get(taskId) ?? [];
+ liveEvents.push(...accepted);
+ this.liveEvents.set(taskId, liveEvents);
+ index.events = events;
+ this.updateSession(taskId, {
+ events,
+ connectionState: "connected",
+ error: session.error?.scope === "operation" ? session.error : undefined,
+ });
+ }
+
private handleEvent(
taskId: string,
event: AgentConversationEvent,
@@ -944,10 +1056,8 @@ export class PiSessionController {
}
const session = this.getSession(taskId);
- if (
- event.sourceId &&
- session.events.some((existing) => existing.sourceId === event.sourceId)
- ) {
+ const index = this.sourceIndex(taskId);
+ if (event.sourceId && index.ids.has(event.sourceId)) {
return;
}
@@ -963,7 +1073,8 @@ export class PiSessionController {
);
}
- const liveEvents = [...(this.liveEvents.get(taskId) ?? []), event];
+ const liveEvents = this.liveEvents.get(taskId) ?? [];
+ liveEvents.push(event);
this.liveEvents.set(taskId, liveEvents);
let status = session.status;
if (status && event.type === "runtime_status") {
@@ -1009,6 +1120,12 @@ export class PiSessionController {
events.push(event);
}
+ if (existingUserMessageIndex >= 0) {
+ this.eventSources.delete(taskId);
+ } else {
+ if (event.sourceId) index.ids.add(event.sourceId);
+ index.events = events;
+ }
const latestSession = this.getSession(taskId);
const preserveConnectionError =
event.type === "runtime_error" &&
@@ -1020,6 +1137,8 @@ export class PiSessionController {
? latestSession.connectionState
: "connected",
events,
+ historyVersion:
+ session.historyVersion + (existingUserMessageIndex >= 0 ? 1 : 0),
status,
error:
preserveConnectionError || preserveOperationError
@@ -1130,6 +1249,7 @@ export class PiSessionController {
}
private handleCloudStatus(taskId: string, cloudStatus: TaskRunStatus): void {
+ this.flushText(taskId);
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.
@@ -1446,6 +1566,7 @@ export class PiSessionController {
private removeUserMessage(taskId: string, messageId: string): void {
const session = this.getSession(taskId);
this.updateSession(taskId, {
+ historyVersion: session.historyVersion + 1,
events: session.events.filter(
(event) => event.type !== "user_message" || event.id !== messageId,
),
@@ -1616,6 +1737,10 @@ export class PiSessionController {
}
private resetTransport(taskId: string): void {
+ const pending = this.pendingText.get(taskId);
+ if (pending) clearTimeout(pending.timer);
+ this.pendingText.delete(taskId);
+ this.eventSources.delete(taskId);
this.advanceSessionVersion(taskId);
this.disposeConversationSubscription(taskId);
this.sessions.delete(taskId);
@@ -1672,6 +1797,7 @@ export class PiSessionController {
}
private applySessionError(taskId: string, error: unknown): void {
+ this.flushText(taskId);
const failure = normalizeSessionError(error);
const classified = classifyPromptFailure(error);
this.updateSession(taskId, {
diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionStore.ts b/products/desktop/packages/core/src/pi-runtime/piSessionStore.ts
index 04727b86f0fb..4f470fffc0fa 100644
--- a/products/desktop/packages/core/src/pi-runtime/piSessionStore.ts
+++ b/products/desktop/packages/core/src/pi-runtime/piSessionStore.ts
@@ -30,6 +30,7 @@ export interface PiSessionError {
export interface PiControllerSessionState {
connectionState: SessionStatus;
events: AgentConversationEvent[];
+ historyVersion: number;
models: Array<Pick<PiNativeModelInfo, "provider" | "id">>;
modelsLoaded: boolean;
thinkingLevels: PiThinkingLevel[];
@@ -59,6 +60,7 @@ export function createEmptyPiControllerSession(): PiControllerSessionState {
return {
connectionState: "connecting",
events: [],
+ historyVersion: 0,
models: [],
modelsLoaded: false,
thinkingLevels: [],
diff --git a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
index 6bb095f2678b..2bc881144186 100644
--- a/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
+++ b/products/desktop/packages/ui/src/features/pi-sessions/PiSessionView.tsx
@@ -659,6 +659,7 @@ export function PiSessionView({ task, isCloud }: PiSessionViewProps) {
<div className="min-h-0 flex-1">
<ChatThread
events={session.events}
+ historyVersion={session.historyVersion}
isPromptPending={isStreaming}
taskId={taskId}
repoPath={repoPath}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
index 442bc943ed95..6faf5fe7b8ca 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
@@ -418,7 +418,7 @@ export function buildAgentConversationItems(
};
}
-function processAgentConversationEvent(
+export function processAgentConversationEvent(
b: ItemBuilder,
event: AgentConversationEvent,
): void {
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
index 746fcfbffd3f..06a46131885d 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx
@@ -1241,7 +1241,6 @@ interface SharedChatThreadProps {
repoPath?: string | null;
task?: Task;
taskId?: string;
- footerState?: Omit<BuildResult, "items">;
hasPendingPermission?: boolean;
currentWork?: string;
/**
@@ -1255,6 +1254,7 @@ interface SharedChatThreadProps {
export interface ChatThreadProps extends SharedChatThreadProps {
events: AgentConversationEvent[];
+ historyVersion: number;
}
/** Serves scroll-to-message requests from panes outside this tree (the Activity
@@ -1299,10 +1299,15 @@ export interface AcpChatThreadProps extends SharedChatThreadProps {
events: AcpMessage[];
}
-export function ChatThread({ events, ...props }: ChatThreadProps) {
+export function ChatThread({
+ events,
+ historyVersion,
+ ...props
+}: ChatThreadProps) {
const { items, ...footerState } = useAgentConversationItems(
events,
props.isPromptPending,
+ historyVersion,
);
return (
@@ -1311,7 +1316,6 @@ export function ChatThread({ events, ...props }: ChatThreadProps) {
key={props.taskId}
{...props}
conversationItems={items}
- footerEvents={[]}
footerState={footerState}
/>
</RawLogsToggleContext.Provider>
@@ -1320,9 +1324,13 @@ export function ChatThread({ events, ...props }: ChatThreadProps) {
export function AcpChatThread({ events, ...props }: AcpChatThreadProps) {
const showDebugLogs = useSettingsStore((state) => state.debugLogsCloudRuns);
- const { items } = useConversationItems(events, props.isPromptPending, {
- showDebugLogs,
- });
+ const { items, ...footerState } = useConversationItems(
+ events,
+ props.isPromptPending,
+ {
+ showDebugLogs,
+ },
+ );
return (
<RawLogsToggleContext.Provider value={true}>
@@ -1330,7 +1338,7 @@ export function AcpChatThread({ events, ...props }: AcpChatThreadProps) {
key={props.taskId}
{...props}
conversationItems={items}
- footerEvents={events}
+ footerState={footerState}
/>
</RawLogsToggleContext.Provider>
);
@@ -1338,12 +1346,11 @@ export function AcpChatThread({ events, ...props }: AcpChatThreadProps) {
interface ChatThreadRendererProps extends SharedChatThreadProps {
conversationItems: ConversationItem[];
- footerEvents: AcpMessage[];
+ footerState: Omit<BuildResult, "items">;
}
function ChatThreadRenderer({
conversationItems,
- footerEvents,
groupToolCalls = true,
isPromptPending,
promptStartedAt,
@@ -1470,7 +1477,6 @@ function ChatThreadRenderer({
const footer = (
<>
<ChatThreadFooter
- events={footerEvents}
isPromptPending={isPromptPending}
promptStartedAt={promptStartedAt}
task={task}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
index 53c32dec8d29..b05bfdf19036 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThreadFooter.tsx
@@ -1,24 +1,20 @@
-import type { AcpMessage } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
import type { BuildResult } from "@posthog/ui/features/sessions/components/buildConversationItems";
import { SessionFooter } from "@posthog/ui/features/sessions/components/SessionFooter";
import { SessionStartupRow } from "@posthog/ui/features/sessions/components/SessionStartupRow";
-import { useConversationItems } from "@posthog/ui/features/sessions/hooks/useConversationItems";
import {
usePendingPermissionsForTask,
useQueuedMessagesForTask,
useSessionForTask,
} from "@posthog/ui/features/sessions/sessionStore";
-import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
import { resolvePendingPermissionVisibility } from "./pendingPermissionVisibility";
interface ChatThreadFooterProps {
- events: AcpMessage[];
isPromptPending: boolean | null;
promptStartedAt?: number | null;
task?: Task;
taskId?: string;
- footerState?: Omit<BuildResult, "items">;
+ footerState: Omit<BuildResult, "items">;
hasPendingPermission?: boolean;
currentWork?: string;
}
@@ -27,13 +23,8 @@ interface ChatThreadFooterProps {
* The session status footer (duration / queued / diff stats) for the new chat thread, rendered as
* the last item in the thread. The legacy `ConversationView` renders the same `SessionFooter` the
* same way. Context usage is not here — it sits in the composer's own toolbar.
- *
- * Re-derives the turn / usage / queue state from `events` with the same hooks the thread uses —
- * `ChatThread` runs its own `useConversationItems`, so this is a second (incremental, memoized)
- * parse pass.
*/
export function ChatThreadFooter({
- events,
isPromptPending,
promptStartedAt,
task,
@@ -42,23 +33,14 @@ export function ChatThreadFooter({
hasPendingPermission,
currentWork,
}: ChatThreadFooterProps) {
- const showDebugLogs = useSettingsStore((s) => s.debugLogsCloudRuns);
- const eventFooterState = useConversationItems(events, isPromptPending, {
- showDebugLogs,
- });
- const lastTurnInfo =
- footerState?.lastTurnInfo ?? eventFooterState.lastTurnInfo;
- const isCompacting =
- footerState?.isCompacting ?? eventFooterState.isCompacting;
- const isClearing = footerState?.isClearing ?? eventFooterState.isClearing;
- const completedToolCallCount =
- footerState?.completedToolCallCount ??
- eventFooterState.completedToolCallCount;
- const lastActivityAt =
- footerState?.lastActivityAt ?? eventFooterState.lastActivityAt;
- const isBackgroundTurnActive =
- footerState?.isBackgroundTurnActive ??
- eventFooterState.isBackgroundTurnActive;
+ const {
+ lastTurnInfo,
+ isCompacting,
+ isClearing,
+ completedToolCallCount,
+ lastActivityAt,
+ isBackgroundTurnActive,
+ } = footerState;
const pendingPermissions = usePendingPermissionsForTask(taskId ?? "");
const pendingPermissionVisible = resolvePendingPermissionVisibility(
hasPendingPermission,
diff --git a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.test.ts
index e2e6e94e4e21..21e028932bde 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.test.ts
@@ -1,12 +1,16 @@
-import type { AcpMessage } from "@posthog/shared";
+import type { AcpMessage, AgentConversationEvent } from "@posthog/shared";
import { describe, expect, it } from "vitest";
import {
type BuildResult,
+ buildAgentConversationItems,
buildConversationItems,
type ConversationItem,
type TurnContext,
} from "./buildConversationItems";
-import { createIncrementalConversationBuilder } from "./incrementalConversationItems";
+import {
+ createIncrementalAgentConversationBuilder,
+ createIncrementalConversationBuilder,
+} from "./incrementalConversationItems";
// --- event builders -------------------------------------------------------
@@ -321,6 +325,120 @@ const EQUIVALENCE_CASES = Object.entries(SCENARIOS).flatMap(([name, events]) =>
);
describe("createIncrementalConversationBuilder", () => {
+ it.each([true, false, null])(
+ "matches Pi history at every prefix (pending=%s)",
+ (pending) => {
+ const events: AgentConversationEvent[] = [
+ {
+ type: "user_message",
+ id: "user-1",
+ timestamp: 1,
+ content: [{ type: "text", text: "Inspect example.ts" }],
+ },
+ {
+ type: "assistant_thought_chunk",
+ timestamp: 2,
+ content: { type: "text", text: "Inspecting" },
+ },
+ {
+ type: "tool_call_started",
+ timestamp: 3,
+ toolCall: {
+ id: "read-1",
+ title: "Read",
+ kind: "read",
+ status: "in_progress",
+ },
+ },
+ {
+ type: "tool_call_updated",
+ timestamp: 4,
+ toolCall: { id: "read-1", status: "completed" },
+ },
+ {
+ type: "assistant_message_chunk",
+ timestamp: 5,
+ content: { type: "text", text: "Found " },
+ },
+ {
+ type: "assistant_message_chunk",
+ timestamp: 6,
+ content: { type: "text", text: "it" },
+ },
+ { type: "turn_completed", timestamp: 7 },
+ {
+ type: "user_message",
+ id: "user-2",
+ timestamp: 8,
+ content: [{ type: "text", text: "Continue" }],
+ },
+ { type: "runtime_status", timestamp: 9, status: "compacting" },
+ {
+ type: "runtime_status",
+ timestamp: 10,
+ status: "compacting",
+ isComplete: true,
+ },
+ {
+ type: "assistant_message_chunk",
+ timestamp: 11,
+ content: { type: "text", text: "Done" },
+ },
+ {
+ type: "assistant_thought_chunk",
+ timestamp: 8.5,
+ content: { type: "text", text: "Late thought" },
+ },
+ { type: "turn_completed", timestamp: 12 },
+ ];
+ const builder = createIncrementalAgentConversationBuilder();
+ for (let count = 1; count <= events.length; count++) {
+ const prefix = events.slice(0, count);
+ expect(normalize(builder.update(prefix, pending))).toEqual(
+ normalize(buildAgentConversationItems(prefix, pending)),
+ );
+ }
+ },
+ );
+
+ it("preserves completed Pi rows while the next turn streams", () => {
+ const events: AgentConversationEvent[] = [
+ {
+ type: "user_message",
+ id: "user-1",
+ timestamp: 1,
+ content: [{ type: "text", text: "Hello" }],
+ },
+ {
+ type: "assistant_message_chunk",
+ timestamp: 2,
+ content: { type: "text", text: "Hello back" },
+ },
+ { type: "turn_completed", timestamp: 3 },
+ {
+ type: "user_message",
+ id: "user-2",
+ timestamp: 4,
+ content: [{ type: "text", text: "Continue" }],
+ },
+ ];
+ const builder = createIncrementalAgentConversationBuilder();
+ const before = builder.update(events, true);
+ const after = builder.update(
+ [
+ ...events,
+ {
+ type: "assistant_message_chunk",
+ timestamp: 5,
+ content: { type: "text", text: "Next" },
+ },
+ ],
+ true,
+ );
+ expect(after.items[0]).toBe(before.items[0]);
+ expect(after.items[1]).toBe(before.items[1]);
+ });
+
it.each(EQUIVALENCE_CASES)(
"matches buildConversationItems at every prefix — $name (pending=$pending)",
({ events, pending }) => {
diff --git a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts
index 3a91784eeb96..675172d95aae 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts
@@ -1,7 +1,8 @@
-import type { AcpMessage } from "@posthog/shared";
+import type { AcpMessage, AgentConversationEvent } from "@posthog/shared";
import {
type BuildConversationOptions,
type BuildResult,
+ buildAgentConversationItems,
buildConversationItems,
type ConversationItem,
createItemBuilder,
@@ -9,6 +10,7 @@ import {
type ItemBuilder,
markThoughtCompletion,
orderEventsByTimestamp,
+ processAgentConversationEvent,
processEvent,
readLastTurnInfo,
type TurnContext,
@@ -20,19 +22,31 @@ import {
* the last event fed, so a late arrival that belongs earlier in the transcript
* fails here and forces a re-read of the whole array in sorted order.
*/
-function extendsTimestampOrder(
- events: AcpMessage[],
+function extendsTimestampOrder<Event>(
+ events: Event[],
from: number,
lastTs: number,
+ timestamp: (event: Event) => number,
): boolean {
let previous = lastTs;
for (let i = from; i < events.length; i++) {
- if (events[i].ts < previous) return false;
- previous = events[i].ts;
+ if (timestamp(events[i]) < previous) return false;
+ previous = timestamp(events[i]);
}
return true;
}
+export interface IncrementalConversationBuilder<Event> {
+ /** Derives the transcript for `events`, reusing the work of earlier calls. */
+ update(
+ events: Event[],
+ isPromptPending: boolean | null,
+ options?: BuildConversationOptions,
+ ): BuildResult;
+ /** Drops the retained state so the next `update` starts from scratch. */
+ reset(): void;
+}
+
/**
* Incremental front end for `buildConversationItems`.
*
@@ -49,11 +63,39 @@ function extendsTimestampOrder(
* state (idle, non-append event change, options change, or a progress card in
* an already-frozen turn being mutated).
*/
-export function createIncrementalConversationBuilder() {
+export function createIncrementalConversationBuilder(): IncrementalConversationBuilder<AcpMessage> {
+ return createBuilder<AcpMessage>({
+ timestamp: (event) => event.ts,
+ process: processEvent,
+ build: buildConversationItems,
+ });
+}
+
+export function createIncrementalAgentConversationBuilder(): IncrementalConversationBuilder<AgentConversationEvent> {
+ return createBuilder<AgentConversationEvent>({
+ timestamp: (event) => event.timestamp,
+ process: processAgentConversationEvent,
+ build: buildAgentConversationItems,
+ });
+}
+
+function createBuilder<Event>(adapter: {
+ timestamp: (event: Event) => number;
+ process: (
+ builder: ItemBuilder,
+ event: Event,
+ options?: BuildConversationOptions,
+ ) => void;
+ build: (
+ events: Event[],
+ pending: boolean | null,
+ options?: BuildConversationOptions,
+ ) => BuildResult;
+}): IncrementalConversationBuilder<Event> {
let b: ItemBuilder | null = null;
let processedCount = 0;
- let firstEventRef: AcpMessage | null = null;
- let boundaryEventRef: AcpMessage | null = null;
+ let firstEventRef: Event | null = null;
+ let boundaryEventRef: Event | null = null;
let showDebugLogs: boolean | undefined;
/** Timestamp of the last event fed to `b`, so a late arrival is detectable. */
let lastProcessedTs = Number.NEGATIVE_INFINITY;
@@ -67,7 +109,7 @@ export function createIncrementalConversationBuilder() {
}
function update(
- events: AcpMessage[],
+ events: Event[],
isPromptPending: boolean | null,
options?: BuildConversationOptions,
): BuildResult {
@@ -86,12 +128,17 @@ export function createIncrementalConversationBuilder() {
(processedCount === 0 || events[0] === firstEventRef) &&
(processedCount === 0 ||
events[processedCount - 1] === boundaryEventRef) &&
- extendsTimestampOrder(events, processedCount, lastProcessedTs);
+ extendsTimestampOrder(
+ events,
+ processedCount,
+ lastProcessedTs,
+ adapter.timestamp,
+ );
if (canFinalizeInPlace) {
const builder = b as ItemBuilder;
for (let i = processedCount; i < events.length; i++) {
- processEvent(builder, events[i], options);
+ adapter.process(builder, events[i], options);
}
finalizeBuilder(builder, isPromptPending);
const result: BuildResult = {
@@ -110,7 +157,7 @@ export function createIncrementalConversationBuilder() {
}
reset();
- return buildConversationItems(events, isPromptPending, options);
+ return adapter.build(events, isPromptPending, options);
}
// The fast path is valid only when this call appends to the exact prefix we
@@ -127,7 +174,12 @@ export function createIncrementalConversationBuilder() {
(processedCount === 0 || events[0] === firstEventRef) &&
(processedCount === 0 ||
events[processedCount - 1] === boundaryEventRef) &&
- extendsTimestampOrder(events, processedCount, lastProcessedTs);
+ extendsTimestampOrder(
+ events,
+ processedCount,
+ lastProcessedTs,
+ adapter.timestamp,
+ );
if (!canAppend) {
b = createItemBuilder();
@@ -142,14 +194,16 @@ export function createIncrementalConversationBuilder() {
// a sequence already in ts-order and takes the new events as they came.
const ordered =
processedCount === 0
- ? orderEventsByTimestamp(events, (event) => event.ts)
+ ? orderEventsByTimestamp(events, adapter.timestamp)
: events;
for (let i = processedCount; i < ordered.length; i++) {
- processEvent(builder, ordered[i], options);
+ adapter.process(builder, ordered[i], options);
}
processedCount = events.length;
lastProcessedTs =
- ordered[ordered.length - 1]?.ts ?? Number.NEGATIVE_INFINITY;
+ ordered.length > 0
+ ? adapter.timestamp(ordered[ordered.length - 1])
+ : Number.NEGATIVE_INFINITY;
firstEventRef = events[0] ?? null;
boundaryEventRef = events[processedCount - 1] ?? null;
@@ -164,7 +218,7 @@ export function createIncrementalConversationBuilder() {
// show that, so rebuild fully this frame (the persistent builder stays
// valid for the next one).
if (builder.lowestTouchedProgressIndex < activeStart) {
- return buildConversationItems(events, isPromptPending, options);
+ return adapter.build(events, isPromptPending, options);
}
// `buildConversationItems` always marks a trailing implicit turn complete.
diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useAgentConversationItems.test.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useAgentConversationItems.test.ts
new file mode 100644
index 000000000000..9b7e948de4bb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useAgentConversationItems.test.ts
@@ -0,0 +1,47 @@
+import type { AgentConversationEvent } from "@posthog/shared";
+import { buildAgentConversationItems } from "@posthog/ui/features/sessions/components/buildConversationItems";
+import { renderHook } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { useAgentConversationItems } from "./useAgentConversationItems";
+
+describe("useAgentConversationItems", () => {
+ it("rebuilds when a server acknowledgement replaces a message inside the consumed prefix", () => {
+ let events: AgentConversationEvent[] = [
+ {
+ type: "user_message",
+ id: "first",
+ timestamp: 1,
+ content: [{ type: "text", text: "First" }],
+ },
+ { type: "turn_completed", timestamp: 2 },
+ {
+ type: "user_message",
+ id: "optimistic",
+ timestamp: 3,
+ content: [{ type: "text", text: "Draft" }],
+ },
+ {
+ type: "assistant_message_chunk",
+ timestamp: 4,
+ content: { type: "text", text: "Response" },
+ },
+ ];
+ let version = 0;
+ const { result, rerender } = renderHook(() =>
+ useAgentConversationItems(events, true, version),
+ );
+ const previous = result.current;
+ rerender();
+ expect(result.current).toBe(previous);
+ events = [...events];
+ events[2] = {
+ type: "user_message",
+ id: "optimistic",
+ timestamp: 3,
+ content: [{ type: "text", text: "Confirmed" }],
+ };
+ version++;
+ rerender();
+ expect(result.current).toEqual(buildAgentConversationItems(events, true));
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useAgentConversationItems.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useAgentConversationItems.ts
index cca1a2294745..bc8f3b825674 100644
--- a/products/desktop/packages/ui/src/features/sessions/hooks/useAgentConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useAgentConversationItems.ts
@@ -1,16 +1,44 @@
import type { AgentConversationEvent } from "@posthog/shared";
-import {
- type BuildResult,
- buildAgentConversationItems,
-} from "@posthog/ui/features/sessions/components/buildConversationItems";
-import { useMemo } from "react";
+import type { BuildResult } from "@posthog/ui/features/sessions/components/buildConversationItems";
+import { createIncrementalAgentConversationBuilder } from "@posthog/ui/features/sessions/components/incrementalConversationItems";
+import { useRef } from "react";
export function useAgentConversationItems(
events: AgentConversationEvent[],
isPromptPending: boolean | null,
+ historyVersion: number,
): BuildResult {
- return useMemo(
- () => buildAgentConversationItems(events, isPromptPending),
- [events, isPromptPending],
- );
+ const ref = useRef<{
+ builder: ReturnType<typeof createIncrementalAgentConversationBuilder>;
+ events: AgentConversationEvent[] | null;
+ pending: boolean | null;
+ version: number;
+ result: BuildResult | null;
+ } | null>(null);
+ if (!ref.current) {
+ ref.current = {
+ builder: createIncrementalAgentConversationBuilder(),
+ events: null,
+ pending: null,
+ version: historyVersion,
+ result: null,
+ };
+ }
+ const cache = ref.current;
+ // A server acknowledgement can replace an optimistic message inside the prefix.
+ if (cache.version !== historyVersion) {
+ cache.builder.reset();
+ cache.result = null;
+ }
+ if (
+ !cache.result ||
+ cache.events !== events ||
+ cache.pending !== isPromptPending
+ ) {
+ cache.result = cache.builder.update(events, isPromptPending);
+ cache.events = events;
+ cache.pending = isPromptPending;
+ cache.version = historyVersion;
+ }
+ return cache.result;
}