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): stop agent threads jumping to the first message (#79224)

Adam Leith8a2a23718483
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 63c91490154d..aa2be863cb19 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
@@ -70,6 +70,7 @@ import {
type FlatThreadRow,
FOLLOWING_END,
flattenTurnRows,
+ keyTurnRows,
nextThreadFollowState,
SCROLL_PREVIOUS_ITEM_PEEK,
SCROLL_UP_KEYS,
@@ -995,13 +996,7 @@ function ThreadScrollBody({
/** Continuously updated so the virtualized body can take over mid-session (see {@link ThreadScrollResume}). */
resumeStateRef: RefObject<ThreadScrollResume>;
}) {
- const keyedRows = useMemo(() => {
- let userTurn = 0;
- return rows.map((item) => ({
- item,
- key: item.type === "user_message" ? `user-turn-${userTurn++}` : item.id,
- }));
- }, [rows]);
+ const keyedRows = useMemo(() => keyTurnRows(rows), [rows]);
const autoFollowRef = useRef<ThreadFollowState>(FOLLOWING_END);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts
index 46ecee662cf4..55d89e4ce4c2 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.test.ts
@@ -6,6 +6,7 @@ import {
computeStickyAnchor,
countFlatRows,
flattenTurnRows,
+ keyTurnRows,
nextThreadFollowState,
type StickyAnchorEntry,
sampleThreadScroll,
@@ -56,6 +57,44 @@ function agentTurn(
return { type: "agent_turn", id, items: items as AgentTurn["items"], prompt };
}
+describe("keyTurnRows", () => {
+ const thought = sessionUpdate("t1");
+ const tool1 = sessionUpdate("c1");
+ const tool2 = sessionUpdate("c2");
+
+ const skillAction = (id: string): TurnRow => ({
+ type: "skill_button_action",
+ id,
+ buttonId: "review" as never,
+ });
+
+ // A row whose id moves while the row stays in place. Keying on the id remounts it, and the
+ // scroller engine answers that remount by scrolling to the first user message.
+ it.each([
+ {
+ name: "tool grouping moves a turn's id to its first tool call",
+ before: [userMessage("u1"), agentTurn("t1", [thought, tool1])],
+ after: [
+ userMessage("u1"),
+ agentTurn("c1", [toolGroup("c1", [thought, tool1, tool2])]),
+ ],
+ keys: ["user-turn-0", "agent-turn-0"],
+ },
+ {
+ name: "a skill-button row swaps its optimistic id for the real one",
+ before: [
+ userMessage("u1"),
+ skillAction("optimistic-1700000000000-ab12cd"),
+ ],
+ after: [userMessage("u1"), skillAction("turn-1-skill-action")],
+ keys: ["user-turn-0", "skill-action-0"],
+ },
+ ])("holds the key steady when $name", ({ before, after, keys }) => {
+ expect(keyTurnRows(before).map((r) => r.key)).toEqual(keys);
+ expect(keyTurnRows(after).map((r) => r.key)).toEqual(keys);
+ });
+});
+
describe("flattenTurnRows", () => {
it("passes standalone rows through with ordinal keys for user messages", () => {
const rows: TurnRow[] = [
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts
index b73c829c1554..6f50d1bc9a4e 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/threadVirtualization.ts
@@ -138,6 +138,59 @@ export function flattenTurnRows(rows: TurnRow[]): FlatThreadRow[] {
return out;
}
+/** A top-level thread row paired with the list key the non-virtualized body renders it under. */
+export interface KeyedTurnRow {
+ key: string;
+ item: TurnRow;
+}
+
+/** Key prefix per top-level row kind, or null for a kind turn grouping never emits as its own row. */
+function turnRowKeyPrefix(row: TurnRow): string | null {
+ switch (row.type) {
+ case "user_message":
+ return "user-turn";
+ case "agent_turn":
+ return "agent-turn";
+ case "git_action":
+ return "git-action";
+ case "skill_button_action":
+ return "skill-action";
+ default:
+ return null;
+ }
+}
+
+/**
+ * Assign list keys to the non-virtualized body's top-level rows.
+ *
+ * Every row is keyed by ordinal rather than by id, because a row's id moves while the row itself
+ * stays in place. A user message and a skill-button action each swap an optimistic id for the real
+ * one when the prompt echoes back, in the single commit that drops the optimistic item and appends
+ * the event. An agent turn takes the id of its first item, and that item is replaced whenever tool
+ * grouping reshapes the head of the turn: a turn that opens with a thought and then makes a second
+ * tool call folds thought plus tools into one `tool_group`, so the turn's id moves from the thought
+ * to the first tool call.
+ *
+ * Keying on those ids remounts the row. The scroller engine watches its content element for child
+ * list changes, and a remount that neither adds nor removes a row reads to it as "the row count is
+ * unchanged but here is a scroll-anchor element I have never scrolled to", which it answers by
+ * scrolling that anchor to the top of the viewport. User messages are the anchors, so the thread
+ * jumps to the oldest one the engine has not already scrolled to, which on the first such remount
+ * is the start of the conversation.
+ *
+ * Rows are only ever appended, so an ordinal is stable for the life of the row.
+ */
+export function keyTurnRows(rows: TurnRow[]): KeyedTurnRow[] {
+ const ordinals = new Map<string, number>();
+ return rows.map((item) => {
+ const prefix = turnRowKeyPrefix(item);
+ if (prefix === null) return { key: item.id, item };
+ const ordinal = ordinals.get(prefix) ?? 0;
+ ordinals.set(prefix, ordinal + 1);
+ return { key: `${prefix}-${ordinal}`, item };
+ });
+}
+
/** Number of rows {@link flattenTurnRows} would produce, without building them. */
export function countFlatRows(rows: TurnRow[]): number {
let count = 0;