Skip to content

Commit 1df4a4e

Browse files
authored
fix(observer): align scroll-anchor ids with transcript display-block keys (#1849)
1 parent 458c7f9 commit 1df4a4e

7 files changed

Lines changed: 1448 additions & 41 deletions

‎desktop/src/features/agents/ui/AgentSessionTranscriptList.tsx‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
} from "@/features/agents/observerRelayStore";
1313
import type { UserProfileLookup } from "@/features/profile/lib/identity";
1414
import { useAnchoredScroll } from "@/features/messages/ui/useAnchoredScroll";
15+
import { useStableArrayShallow } from "@/shared/hooks/useStableReference";
1516
import { cn } from "@/shared/lib/cn";
1617
import {
1718
Dialog,
@@ -48,6 +49,7 @@ import type { FileEditDiff } from "./agentSessionFileEditDiff";
4849
import {
4950
buildTranscriptDisplayBlocks,
5051
formatTurnSetupLabel,
52+
getDisplayBlockKey,
5153
turnSetupDetail,
5254
turnSetupTimestamp,
5355
type TranscriptDisplayBlock,
@@ -154,13 +156,27 @@ export function AgentSessionTranscriptList({
154156
() => buildTranscriptDisplayBlocks(items, latestLiveSessionId),
155157
[items, latestLiveSessionId],
156158
);
159+
// Derive the same block keys the DOM renders as `data-message-id` so
160+
// useAnchoredScroll anchors on real DOM rows. Value-stabilized so the
161+
// hook's restoration effect only fires when the ordered block sequence
162+
// actually changes (same pattern as AgentSessionThreadPanel).
163+
const blockKeys = React.useMemo(
164+
() => (autoTail ? displayBlocks.map(getDisplayBlockKey) : []),
165+
[autoTail, displayBlocks],
166+
);
167+
const stableBlockKeys = useStableArrayShallow(blockKeys);
168+
const scrollMessages = React.useMemo(
169+
() => stableBlockKeys.map((id) => ({ id })),
170+
[stableBlockKeys],
171+
);
172+
157173
const scrollContainerRef = React.useRef<HTMLDivElement>(null);
158174
const contentRef = React.useRef<HTMLDivElement>(null);
159175
const anchoredScroll = useAnchoredScroll({
160176
channelId: autoTail ? (scrollScopeKey ?? agentPubkey) : null,
161177
contentRef,
162178
isLoading: false,
163-
messages: items,
179+
messages: scrollMessages,
164180
scrollContainerRef,
165181
});
166182

@@ -333,18 +349,6 @@ function TranscriptAcpSourceBadge({ source }: { source: string }) {
333349
);
334350
}
335351

336-
function getDisplayBlockKey(block: TranscriptDisplayBlock) {
337-
if (block.kind === "single") {
338-
return block.item.id;
339-
}
340-
if (block.kind === "session-boundary") {
341-
// Use firstItemId (stable across prepend) rather than runIndex (shifts when
342-
// older sessions are prepended, causing unnecessary boundary remounts).
343-
return `session-boundary:${block.sessionId}:${block.firstItemId}`;
344-
}
345-
return `turn:${block.turnId}`;
346-
}
347-
348352
function TranscriptDisplayBlockView({
349353
agentAvatarUrl,
350354
agentName,

‎desktop/src/features/agents/ui/agentSessionTranscript.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1156,14 +1156,18 @@ export function processTranscriptEvent(
11561156
};
11571157
}
11581158

1159-
export function buildTranscriptState(events: ObserverEvent[]): TranscriptState {
1159+
export function buildTranscriptState(
1160+
events: readonly ObserverEvent[],
1161+
): TranscriptState {
11601162
let state = createEmptyTranscriptState();
11611163
for (const event of events) {
11621164
state = processTranscriptEvent(state, event);
11631165
}
11641166
return state;
11651167
}
11661168

1167-
export function buildTranscript(events: ObserverEvent[]): TranscriptItem[] {
1169+
export function buildTranscript(
1170+
events: readonly ObserverEvent[],
1171+
): TranscriptItem[] {
11681172
return buildTranscriptState(events).items;
11691173
}

‎desktop/src/features/agents/ui/agentSessionTranscriptGrouping.test.mjs‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
buildTranscriptDisplayBlocks,
66
flattenDisplayBlocks,
77
formatTurnSetupLabel,
8+
getDisplayBlockKey,
89
} from "./agentSessionTranscriptGrouping.ts";
910
import { isObserverEventAfter } from "../observerRelayStore.ts";
1011

@@ -1709,3 +1710,166 @@ test("buildTranscriptDisplayBlocks_leadingSingleBeforeSessionNew_emittedInline",
17091710
`sp (${spIdx}) must precede toolA (${toolAIdx}) — system-prompt must be hoisted even after a leading item`,
17101711
);
17111712
});
1713+
1714+
// ── getDisplayBlockKey ──────────────────────────────────────────────────────────
1715+
1716+
test("getDisplayBlockKey_single_returnsItemId", () => {
1717+
const block = { kind: "single", item: { id: "item-42" } };
1718+
assert.equal(getDisplayBlockKey(block), "item-42");
1719+
});
1720+
1721+
test("getDisplayBlockKey_turn_returnsPrefixedTurnId", () => {
1722+
const block = { kind: "turn", turnId: "t-99", segments: [] };
1723+
assert.equal(getDisplayBlockKey(block), "turn:t-99");
1724+
});
1725+
1726+
test("getDisplayBlockKey_sessionBoundary_usesFirstItemIdNotRunIndex", () => {
1727+
const block = {
1728+
kind: "session-boundary",
1729+
sessionId: "sess-2",
1730+
sessionStartTimestamp: "2026-07-08T00:00:00.000Z",
1731+
labelState: "most-recent",
1732+
runIndex: 3,
1733+
firstItemId: "first-item-abc",
1734+
};
1735+
assert.equal(
1736+
getDisplayBlockKey(block),
1737+
"session-boundary:sess-2:first-item-abc",
1738+
"key must use firstItemId, not runIndex",
1739+
);
1740+
});
1741+
1742+
test("getDisplayBlockKey_independentOfLatestLiveSessionId", () => {
1743+
// Build blocks for the same items with different latestLiveSessionId values.
1744+
// Keys must be identical — only labelState differs.
1745+
const items = [
1746+
sessionItem("a", "sess-1", "2026-07-08T00:00:01.000Z"),
1747+
sessionItem("b", "sess-2", "2026-07-08T00:00:02.000Z"),
1748+
];
1749+
1750+
const blocksLive = buildTranscriptDisplayBlocks(items, "sess-2");
1751+
const blocksNoLive = buildTranscriptDisplayBlocks(items, null);
1752+
const blocksDiffLive = buildTranscriptDisplayBlocks(items, "sess-other");
1753+
1754+
const keysLive = blocksLive.map(getDisplayBlockKey);
1755+
const keysNoLive = blocksNoLive.map(getDisplayBlockKey);
1756+
const keysDiffLive = blocksDiffLive.map(getDisplayBlockKey);
1757+
1758+
assert.deepEqual(
1759+
keysLive,
1760+
keysNoLive,
1761+
"keys must not vary with latestLiveSessionId=null",
1762+
);
1763+
assert.deepEqual(
1764+
keysLive,
1765+
keysDiffLive,
1766+
"keys must not vary with latestLiveSessionId=other",
1767+
);
1768+
1769+
// Sanity check: labelState DID change (proves the test setup matters).
1770+
const boundaryLive = blocksLive.find((b) => b.kind === "session-boundary");
1771+
const boundaryNoLive = blocksNoLive.find(
1772+
(b) => b.kind === "session-boundary",
1773+
);
1774+
assert.notEqual(
1775+
boundaryLive.labelState,
1776+
boundaryNoLive.labelState,
1777+
"labelState must differ (test setup sanity check)",
1778+
);
1779+
});
1780+
1781+
test("getDisplayBlockKey_parity_matchesBuildTranscriptDisplayBlocksOutput", () => {
1782+
// End-to-end: derive keys from buildTranscriptDisplayBlocks and assert they
1783+
// match the expected key for each block kind (the load-bearing invariant that
1784+
// outer-panel-derived ids match inner DOM data-message-id).
1785+
const items = [
1786+
sessionItem("orphan", "sess-1", "2026-07-08T00:00:00.000Z"),
1787+
// Multi-session to get a boundary block.
1788+
sessionItem("tool-a", "sess-2", "2026-07-08T00:00:01.000Z"),
1789+
];
1790+
1791+
// Give orphan no turnId so it becomes a "single" block.
1792+
items[0].turnId = undefined;
1793+
1794+
const blocks = buildTranscriptDisplayBlocks(items, null);
1795+
const keys = blocks.map(getDisplayBlockKey);
1796+
1797+
// Expect: [single:orphan, boundary:sess-2:tool-a, turn:turn-tool-a]
1798+
assert.ok(keys.includes("orphan"), "single block key = item.id");
1799+
assert.ok(
1800+
keys.some((k) => k.startsWith("session-boundary:sess-2:")),
1801+
"boundary block key uses session-boundary: prefix",
1802+
);
1803+
assert.ok(
1804+
keys.some((k) => k.startsWith("turn:")),
1805+
"turn block key uses turn: prefix",
1806+
);
1807+
1808+
// No duplicates.
1809+
assert.equal(new Set(keys).size, keys.length, "all keys must be unique");
1810+
});
1811+
1812+
// ── Key-parity invariant: transient [turn, single] → [single, turn] reorder ──
1813+
1814+
test("getDisplayBlockKey_firstTurnReorder_keysStableAcrossReorder", () => {
1815+
// Partial sequence: turn_started → session/new (two items, before session_resolved).
1816+
// At this point the key set is some combination of single + turn keys.
1817+
const ts = "2026-07-08T10:00:00.000Z";
1818+
const partialItems = [
1819+
{
1820+
id: "turn-started",
1821+
type: "lifecycle",
1822+
renderClass: "lifecycle",
1823+
title: "Turn started",
1824+
text: "",
1825+
timestamp: ts,
1826+
acpSource: "turn_started",
1827+
turnId: "turn-001",
1828+
sessionId: null,
1829+
channelId: "chan-1",
1830+
},
1831+
{
1832+
id: "system-prompt:chan-1",
1833+
type: "metadata",
1834+
renderClass: "raw-rail",
1835+
title: "System prompt",
1836+
sections: [{ title: "Base", body: "You are a helpful AI assistant." }],
1837+
timestamp: ts,
1838+
acpSource: "session/new",
1839+
turnId: null,
1840+
sessionId: null,
1841+
channelId: "chan-1",
1842+
},
1843+
];
1844+
1845+
const partialBlocks = buildTranscriptDisplayBlocks(partialItems);
1846+
const partialKeys = new Set(partialBlocks.map(getDisplayBlockKey));
1847+
1848+
// Full sequence: add session_resolved (same turnId) — this seals the open
1849+
// batch and may reorder [turn, single] → [single, turn].
1850+
const fullItems = [
1851+
...partialItems,
1852+
{
1853+
id: "session-resolved",
1854+
type: "lifecycle",
1855+
renderClass: "lifecycle",
1856+
title: "Session ready",
1857+
text: "",
1858+
timestamp: ts,
1859+
acpSource: "session_resolved",
1860+
turnId: "turn-001",
1861+
sessionId: "session-001",
1862+
channelId: "chan-1",
1863+
},
1864+
];
1865+
1866+
const fullBlocks = buildTranscriptDisplayBlocks(fullItems);
1867+
const fullKeys = new Set(fullBlocks.map(getDisplayBlockKey));
1868+
1869+
// The KEY IDENTITIES must be identical — only the ORDER may differ.
1870+
assert.deepEqual(
1871+
partialKeys,
1872+
fullKeys,
1873+
"block key identities must be identical before and after session_resolved seals the open batch (order may differ)",
1874+
);
1875+
});

‎desktop/src/features/agents/ui/agentSessionTranscriptGrouping.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import type { TranscriptItem } from "./agentSessionTypes";
1+
import { buildTranscriptState } from "./agentSessionTranscript";
2+
import type { ObserverEvent, TranscriptItem } from "./agentSessionTypes";
23
import { classifyToolItem } from "./agentSessionToolClassifier";
34

45
export type TranscriptTurnSegment =
@@ -742,6 +743,46 @@ export function flattenDisplayBlocks(
742743
return result;
743744
}
744745

746+
/**
747+
* Stable display key for a transcript block — used as the React list key and
748+
* as the `data-message-id` attribute that `useAnchoredScroll` anchors on.
749+
*
750+
* Must be kept in sync with the `data-message-id` rendered by
751+
* `AgentSessionTranscriptList` so outer scroll-anchor ids and inner DOM ids
752+
* always agree 1:1.
753+
*/
754+
export function getDisplayBlockKey(block: TranscriptDisplayBlock): string {
755+
if (block.kind === "single") {
756+
return block.item.id;
757+
}
758+
if (block.kind === "session-boundary") {
759+
// Use firstItemId (stable across prepend) rather than runIndex (shifts when
760+
// older sessions are prepended, causing unnecessary boundary remounts).
761+
return `session-boundary:${block.sessionId}:${block.firstItemId}`;
762+
}
763+
return `turn:${block.turnId}`;
764+
}
765+
766+
/**
767+
* Derive the ordered display-block key sequence from raw observer events.
768+
*
769+
* Pure function: `buildTranscriptState(events).items` →
770+
* `buildTranscriptDisplayBlocks` → `getDisplayBlockKey`. This is the exact
771+
* chain `AgentSessionThreadPanel` uses to produce the id list fed to
772+
* `useAnchoredScroll` — extracted so both production and tests share one
773+
* code path.
774+
*
775+
* `latestLiveSessionId` is intentionally omitted: it only affects boundary
776+
* `labelState`, never keys.
777+
*/
778+
export function deriveTranscriptBlockIds(
779+
events: readonly ObserverEvent[],
780+
): string[] {
781+
const items = buildTranscriptState(events).items;
782+
const blocks = buildTranscriptDisplayBlocks(items);
783+
return blocks.map(getDisplayBlockKey);
784+
}
785+
745786
/** Human-readable labels for a collapsed turn setup row. */
746787
export function formatTurnSetupLabel(
747788
items: Extract<TranscriptItem, { type: "lifecycle" }>[],

0 commit comments

Comments
 (0)