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): only uncollapse the last renderable tool call per turn (#106030)

Daniel Parker237608334a02
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 a4bba6ab9e16..f931cbf849c9 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/buildConversationItems.ts
@@ -43,6 +43,8 @@ export interface TurnContext {
turnComplete: boolean;
/** From the prompt response; null when the agent reported no gateway trace. */
traceId?: string | null;
+ /** True for a turn with no user prompt behind it (e.g. background setup activity). */
+ isImplicit?: boolean;
}
export type ConversationItem =
@@ -1161,6 +1163,7 @@ function ensureImplicitTurn(b: ItemBuilder, ts: number) {
childItems,
turnCancelled: false,
turnComplete: false,
+ isImplicit: true,
};
b.currentTurn = {
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 bd2a6e6d571c..abfc7e5cb494 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
@@ -50,6 +50,7 @@ import {
type BuildResult,
type ConversationItem,
hasSetupProgressForRun,
+ type TurnContext,
} from "@posthog/ui/features/sessions/components/buildConversationItems";
import {
ChatMarkdown,
@@ -209,6 +210,61 @@ function isThoughtItem(item: ConversationItem): boolean {
);
}
+function isTurnDecided(
+ turnContext: TurnContext,
+ erroredTurns: Set<TurnContext>,
+ supersededTurns: Set<TurnContext>,
+ isSessionIdle: boolean,
+): boolean {
+ // A cloud turn that errors out never gets a `turn_completed` event.
+ if (erroredTurns.has(turnContext)) return true;
+ if (!turnContext.turnComplete) return false;
+ // `turnComplete` flips true the instant an implicit turn opens, so trust it only once
+ // superseded or the session goes idle.
+ return turnContext.isImplicit
+ ? supersededTurns.has(turnContext) || isSessionIdle
+ : true;
+}
+
+function lastRenderableIdsByTurn(
+ items: ConversationItem[],
+ isSessionIdle: boolean,
+): Map<TurnContext, string> {
+ const erroredTurns = new Set<TurnContext>();
+ const lastIndexByTurn = new Map<TurnContext, number>();
+ let lastSessionUpdateIndex = -1;
+ items.forEach((item, index) => {
+ if (!isSessionUpdateItem(item)) return;
+ lastIndexByTurn.set(item.turnContext, index);
+ lastSessionUpdateIndex = index;
+ if (item.update.sessionUpdate === "error") {
+ erroredTurns.add(item.turnContext);
+ }
+ });
+ const supersededTurns = new Set<TurnContext>();
+ for (const [turnContext, lastIndex] of lastIndexByTurn) {
+ if (lastIndex < lastSessionUpdateIndex) supersededTurns.add(turnContext);
+ }
+
+ const out = new Map<TurnContext, string>();
+ for (const item of items) {
+ if (!isToolCallItem(item)) continue;
+ if (
+ !isTurnDecided(
+ item.turnContext,
+ erroredTurns,
+ supersededTurns,
+ isSessionIdle,
+ )
+ ) {
+ continue;
+ }
+ if (!hasUiAppResult(item)) continue;
+ out.set(item.turnContext, item.id);
+ }
+ return out;
+}
+
/**
* An item that must render as its own row, never folded into a `ToolGroupItem`:
* a plan awaiting approval, a show-actions handoff, or a call whose result
@@ -222,8 +278,16 @@ function isThoughtItem(item: ConversationItem): boolean {
* hide behind a collapsed panel. Keeping the chart outside the group is the
* rule that fixes both.
*/
-function rendersStandalone(item: ConversationItem): boolean {
- return isPlanItem(item) || isShowActionsItem(item) || hasUiAppResult(item);
+function rendersStandalone(
+ item: ConversationItem,
+ lastRenderableIds: Map<TurnContext, string>,
+): boolean {
+ return (
+ isPlanItem(item) ||
+ isShowActionsItem(item) ||
+ (isToolCallItem(item) &&
+ lastRenderableIds.get(item.turnContext) === item.id)
+ );
}
/**
@@ -260,7 +324,15 @@ function stableRunItems(run: SessionUpdateItem[]): SessionUpdateItem[] {
return run;
}
-export function groupToolRuns(items: ConversationItem[]): ThreadItem[] {
+export function groupToolRuns(
+ items: ConversationItem[],
+ isPromptPending: boolean | null = true,
+): ThreadItem[] {
+ // `=== false` matches `incrementalConversationItems`'s own idle check.
+ const lastRenderableIds = lastRenderableIdsByTurn(
+ items,
+ isPromptPending === false,
+ );
const out: ThreadItem[] = [];
// The buffer holds the active run in order: tools, the thoughts between them, and any invisible
// items interleaved with either.
@@ -268,7 +340,13 @@ export function groupToolRuns(items: ConversationItem[]): ThreadItem[] {
let toolCount = 0;
const flush = () => {
- if (toolCount >= 2) {
+ const hasEarlierRenderableCall = buffer.some(
+ (item) =>
+ isToolCallItem(item) &&
+ hasUiAppResult(item) &&
+ lastRenderableIds.get(item.turnContext) !== item.id,
+ );
+ if (toolCount >= 2 || hasEarlierRenderableCall) {
out.push({
type: "tool_group",
// Keyed on the first tool call so the id survives thoughts appending around it.
@@ -284,7 +362,7 @@ export function groupToolRuns(items: ConversationItem[]): ThreadItem[] {
for (const item of items) {
if (isToolCallItem(item)) {
- if (rendersStandalone(item)) {
+ if (rendersStandalone(item, lastRenderableIds)) {
flush();
out.push(item);
continue;
@@ -1390,8 +1468,11 @@ function ChatThreadRenderer({
);
const rows = useMemo<TurnRow[]>(
- () => groupIntoTurns(groupToolCalls ? groupToolRuns(items) : items),
- [items, groupToolCalls],
+ () =>
+ groupIntoTurns(
+ groupToolCalls ? groupToolRuns(items, isPromptPending) : items,
+ ),
+ [items, groupToolCalls, isPromptPending],
);
// Virtualization ratchet: past the threshold the thread switches to the windowed body and
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
index 872bef5c5435..1e6fc29b4556 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/groupToolRuns.test.ts
@@ -152,6 +152,343 @@ describe("groupToolRuns", () => {
expect(out[1]).toMatchObject({ id: "chart" });
});
+ it("stands only the last chart-rendering call of a turn alone, folding earlier ones back into their run", () => {
+ const turnContext = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: true,
+ };
+ const chart = (id: string) => {
+ const item = toolItem(id, { toolCallId: id });
+ item.turnContext = turnContext;
+ turnContext.toolCalls.set(id, {
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ return item;
+ };
+ const inTurn = (id: string) => {
+ const item = toolItem(id);
+ item.turnContext = turnContext;
+ return item;
+ };
+
+ const out = groupToolRuns([
+ inTurn("before-1"),
+ inTurn("before-2"),
+ chart("chart-1"),
+ inTurn("between-1"),
+ inTurn("between-2"),
+ chart("chart-2"),
+ inTurn("after-1"),
+ inTurn("after-2"),
+ ]);
+
+ expect(out.map((row) => row.type)).toEqual([
+ "tool_group",
+ "session_update",
+ "tool_group",
+ ]);
+ expect(out[1]).toMatchObject({ id: "chart-2" });
+ expect(out[0]).toMatchObject({
+ items: expect.arrayContaining([
+ expect.objectContaining({ id: "chart-1" }),
+ ]),
+ });
+ });
+
+ it("groups an earlier chart even when it's the only other call in the run", () => {
+ const turnContext = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: true,
+ };
+ const chart = (id: string) => {
+ const item = toolItem(id, { toolCallId: id });
+ item.turnContext = turnContext;
+ turnContext.toolCalls.set(id, {
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ return item;
+ };
+
+ const out = groupToolRuns([chart("chart-1"), chart("chart-2")]);
+
+ expect(out.map((row) => row.type)).toEqual([
+ "tool_group",
+ "session_update",
+ ]);
+ expect(out[0]).toMatchObject({
+ items: [expect.objectContaining({ id: "chart-1" })],
+ });
+ expect(out[1]).toMatchObject({ id: "chart-2" });
+ });
+
+ it("holds every chart-rendering call inside its group until the turn completes", () => {
+ const turnContext = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: false,
+ };
+ const chart = (id: string) => {
+ const item = toolItem(id, { toolCallId: id });
+ item.turnContext = turnContext;
+ turnContext.toolCalls.set(id, {
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ return item;
+ };
+ const inTurn = (id: string) => {
+ const item = toolItem(id);
+ item.turnContext = turnContext;
+ return item;
+ };
+
+ const out = groupToolRuns([inTurn("before"), chart("chart-1")]);
+
+ expect(out.map((row) => row.type)).toEqual(["tool_group"]);
+ });
+
+ it("stands a chart alone once its turn errors out, even without turnComplete", () => {
+ const turnContext = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: false,
+ };
+ const chartCall = toolItem("chart-1", { toolCallId: "chart-1" });
+ chartCall.turnContext = turnContext;
+ turnContext.toolCalls.set("chart-1", {
+ toolCallId: "chart-1",
+ title: "chart-1",
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ const inTurn = (id: string) => {
+ const item = toolItem(id);
+ item.turnContext = turnContext;
+ return item;
+ };
+ const errorItem: SessionUpdateItem = {
+ type: "session_update",
+ id: "error",
+ update: { sessionUpdate: "error", errorType: "runtime", message: "boom" },
+ turnContext,
+ };
+
+ const out = groupToolRuns([inTurn("before"), chartCall, errorItem]);
+
+ expect(out.map((row) => row.type)).toEqual([
+ "session_update",
+ "session_update",
+ "session_update",
+ ]);
+ expect(out[1]).toMatchObject({ id: "chart-1" });
+ });
+
+ it("keeps every chart grouped while an implicit turn is still growing", () => {
+ const turnContext = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: true,
+ isImplicit: true,
+ };
+ const chart = (id: string) => {
+ const item = toolItem(id, { toolCallId: id });
+ item.turnContext = turnContext;
+ turnContext.toolCalls.set(id, {
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ return item;
+ };
+
+ const out = groupToolRuns([chart("chart-1"), chart("chart-2")]);
+
+ expect(out.map((row) => row.type)).toEqual(["tool_group"]);
+ });
+
+ it("doesn't treat a turnless item after the chart as supersession", () => {
+ const turnContext = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: true,
+ isImplicit: true,
+ };
+ const chart = (id: string) => {
+ const item = toolItem(id, { toolCallId: id });
+ item.turnContext = turnContext;
+ turnContext.toolCalls.set(id, {
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ return item;
+ };
+ const shellExecuteItem: ConversationItem = {
+ type: "user_shell_execute",
+ id: "shell",
+ command: "ls",
+ cwd: "/repo",
+ };
+
+ const out = groupToolRuns([
+ chart("chart-1"),
+ chart("chart-2"),
+ shellExecuteItem,
+ ]);
+
+ expect(out.filter((row) => row.type === "tool_group")).toHaveLength(1);
+ });
+
+ it("stands the last chart alone once the session goes idle, even with nothing to supersede the implicit turn", () => {
+ const turnContext = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: true,
+ isImplicit: true,
+ };
+ const chart = (id: string) => {
+ const item = toolItem(id, { toolCallId: id });
+ item.turnContext = turnContext;
+ turnContext.toolCalls.set(id, {
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ return item;
+ };
+
+ const isPromptPending = false;
+ const out = groupToolRuns(
+ [chart("chart-1"), chart("chart-2")],
+ isPromptPending,
+ );
+
+ expect(out.map((row) => row.type)).toEqual([
+ "tool_group",
+ "session_update",
+ ]);
+ expect(out[0]).toMatchObject({
+ items: [expect.objectContaining({ id: "chart-1" })],
+ });
+ expect(out[1]).toMatchObject({ id: "chart-2" });
+ });
+
+ it("stands the last chart alone once a later turn supersedes the implicit one", () => {
+ const turnContext = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: true,
+ isImplicit: true,
+ };
+ const chart = (id: string) => {
+ const item = toolItem(id, { toolCallId: id });
+ item.turnContext = turnContext;
+ turnContext.toolCalls.set(id, {
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ return item;
+ };
+
+ const out = groupToolRuns([
+ chart("chart-1"),
+ chart("chart-2"),
+ toolItem("next-turn"),
+ ]);
+
+ expect(out.map((row) => row.type)).toEqual([
+ "tool_group",
+ "session_update",
+ "session_update",
+ ]);
+ expect(out[0]).toMatchObject({
+ items: [expect.objectContaining({ id: "chart-1" })],
+ });
+ expect(out[1]).toMatchObject({ id: "chart-2" });
+ });
+
+ it("keeps a finished turn's standalone chart in place once a new turn starts", () => {
+ const finishedTurn = {
+ toolCalls: new Map(),
+ childItems: new Map(),
+ turnCancelled: false,
+ turnComplete: true,
+ };
+ const chart = (id: string) => {
+ const item = toolItem(id, { toolCallId: id });
+ item.turnContext = finishedTurn;
+ finishedTurn.toolCalls.set(id, {
+ toolCallId: id,
+ title: id,
+ kind: "execute",
+ status: "completed",
+ rawOutput: {
+ _meta: { ui: { resourceUri: "ui://posthog/mock-app.html" } },
+ },
+ });
+ return item;
+ };
+ const chartCall = chart("chart-1");
+
+ const before = groupToolRuns([toolItem("before"), chartCall]);
+ const after = groupToolRuns([
+ toolItem("before"),
+ chartCall,
+ toolItem("next-turn-1"),
+ toolItem("next-turn-2"),
+ ]);
+
+ expect(before[1]).toMatchObject({ id: "chart-1" });
+ expect(after[1]).toMatchObject({ id: "chart-1" });
+ });
+
it("still groups an MCP tool call whose result has no UI app", () => {
const execCall = toolItem("exec", {
toolCallId: "exec",
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 675172d95aae..02ffd25b99a8 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/incrementalConversationItems.ts
@@ -266,6 +266,7 @@ function assembleItems(
childItems: new Map(turn.context.childItems),
turnCancelled: turn.context.turnCancelled,
turnComplete: turn.context.turnComplete,
+ isImplicit: turn.context.isImplicit,
}
: null;