Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor(agents): project the transcript with Solid's keyed reconcile (#9474)

Wolf Mermelstein71993c65d7f5
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index ff935ff001..977366dde3 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -961,10 +961,12 @@ persisted `turnState` is `failed`; open the session to inspect its error.
### Agent transcript projection
-Keep folded messages ordered by turn and author in the transcript store: append
-at the new index, reconcile matching rows in place, binary-search earlier
-updates, and splice only for real insertion/removal. Never `produce` the whole
-array per append; it makes initial projection quadratic. Check with the
+Key transcript rows by the fold's `FoldedMessage.key` (`<turn>:<author kind>`);
+never rebuild it from `turn` and `author`. Apply a load or rebase as one keyed
+`reconcile(messages, { key: 'key' })`, without `merge`. A streamed message
+reconciles the tail row in place or writes the next index; only an out-of-order
+one takes the keyed path. Never `produce` the whole array per append; it makes
+initial projection quadratic. Check with the
[session-open runner](src/features/block-agent/browser-test/README.md).
### Agent system events
diff --git a/apps/web/src/features/agent-activity/agent-activity.test.tsx b/apps/web/src/features/agent-activity/agent-activity.test.tsx
index a002955ec5..2225b635f4 100644
--- a/apps/web/src/features/agent-activity/agent-activity.test.tsx
+++ b/apps/web/src/features/agent-activity/agent-activity.test.tsx
@@ -71,6 +71,7 @@ const snapshot: AgentActivityRow[] = [
function reply(rows: ActivityRow[]): FoldedMessage {
return {
agentSessionId: 'session',
+ key: '2:agent',
turn: 2,
author: { kind: 'agent' },
requestId: null,
diff --git a/apps/web/src/features/agent-activity/agent-typing.test.tsx b/apps/web/src/features/agent-activity/agent-typing.test.tsx
index b047001f24..b850df9e06 100644
--- a/apps/web/src/features/agent-activity/agent-typing.test.tsx
+++ b/apps/web/src/features/agent-activity/agent-typing.test.tsx
@@ -126,6 +126,7 @@ function typing(phase: 'thinking' | 'writing' | 'working' | 'waiting') {
function writing(text: string): FoldedMessage {
return {
agentSessionId: 'session',
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
requestId: null,
diff --git a/apps/web/src/features/agent-activity/core/live-reply.test.ts b/apps/web/src/features/agent-activity/core/live-reply.test.ts
index 837bd8f9a2..5db08ca948 100644
--- a/apps/web/src/features/agent-activity/core/live-reply.test.ts
+++ b/apps/web/src/features/agent-activity/core/live-reply.test.ts
@@ -20,6 +20,7 @@ function reply(
): FoldedMessage {
return {
agentSessionId: 'session',
+ key: `${turn}:agent`,
turn,
author: { kind: 'agent' },
requestId: null,
diff --git a/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx b/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx
index 3027f4de5c..16b8e550f7 100644
--- a/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx
+++ b/apps/web/src/features/agent-activity/debug/ProgressPlayground.tsx
@@ -634,6 +634,7 @@ function phaseOf(parts: readonly MessagePart[]): TurnPhase {
function foldedReply(scenario: Scenario): FoldedMessage {
return {
agentSessionId: SESSION,
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
requestId: null,
diff --git a/apps/web/src/features/agent-activity/queries/live-session.test.tsx b/apps/web/src/features/agent-activity/queries/live-session.test.tsx
index d19bbe6c3c..3be97aff97 100644
--- a/apps/web/src/features/agent-activity/queries/live-session.test.tsx
+++ b/apps/web/src/features/agent-activity/queries/live-session.test.tsx
@@ -35,6 +35,7 @@ function session() {
function message(text: string): FoldedMessage {
return {
agentSessionId: 'session',
+ key: '0:agent',
turn: 0,
author: { kind: 'agent' },
requestId: null,
diff --git a/apps/web/src/features/agent-activity/queries/live-session.ts b/apps/web/src/features/agent-activity/queries/live-session.ts
index 04d2870af8..0bc8fce39f 100644
--- a/apps/web/src/features/agent-activity/queries/live-session.ts
+++ b/apps/web/src/features/agent-activity/queries/live-session.ts
@@ -55,7 +55,6 @@ export function createLiveSession(sessionId: Accessor<string | undefined>) {
const rows = new Map<string, FoldedMessage>();
let disposed = false;
let timer: ReturnType<typeof setTimeout> | undefined;
- const key = (row: FoldedMessage) => `${row.turn}:${row.author.kind}`;
const flush = () => {
timer = undefined;
if (!disposed) setMessages([...rows.values()]);
@@ -65,8 +64,8 @@ export function createLiveSession(sessionId: Accessor<string | undefined>) {
if (event.kind === 'metadata') setMetadata(event.metadata);
else if (event.kind === 'replace') {
rows.clear();
- for (const row of event.messages) rows.set(key(row), row);
- } else rows.set(key(event.message), event.message);
+ for (const row of event.messages) rows.set(row.key, row);
+ } else rows.set(event.message.key, event.message);
}
timer ??= setTimeout(flush, 250);
};
diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsx
index 3e4076d01b..5524a78bad 100644
--- a/apps/web/src/features/block-agent/agent-session-provider.tsx
+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx
@@ -81,6 +81,7 @@ export function AgentSessionProvider(
return [
{
agentSessionId: sessionId() ?? props.blockId,
+ key: '0:user',
turn: 0,
author: { kind: 'user', userId: userId() ?? null },
requestId: null,
diff --git a/apps/web/src/features/block-agent/browser-test/main.tsx b/apps/web/src/features/block-agent/browser-test/main.tsx
index 44d34f9974..e038b9ae29 100644
--- a/apps/web/src/features/block-agent/browser-test/main.tsx
+++ b/apps/web/src/features/block-agent/browser-test/main.tsx
@@ -68,6 +68,7 @@ const events: SessionNotification[] = [
// gives it: reports first, then the reply.
const taskReply: FoldedMessage = {
agentSessionId: session.sessionId(),
+ key: '2:agent',
requestId: null,
pending: false,
postedAt: null,
diff --git a/apps/web/src/features/block-agent/browser-test/mentions.tsx b/apps/web/src/features/block-agent/browser-test/mentions.tsx
index 8cef047689..c324f91fe9 100644
--- a/apps/web/src/features/block-agent/browser-test/mentions.tsx
+++ b/apps/web/src/features/block-agent/browser-test/mentions.tsx
@@ -29,6 +29,7 @@ function Fixture() {
const literal = new URLSearchParams(location.search).has('literal');
const reply = (): FoldedMessage => ({
agentSessionId: 'fixture',
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
parts: [
diff --git a/apps/web/src/features/block-agent/browser-test/session.ts b/apps/web/src/features/block-agent/browser-test/session.ts
index 4164e0b41b..07dd293039 100644
--- a/apps/web/src/features/block-agent/browser-test/session.ts
+++ b/apps/web/src/features/block-agent/browser-test/session.ts
@@ -58,6 +58,7 @@ export function receiveText(turn: number) {
...values,
{
agentSessionId: session.sessionId(),
+ key: `${turn}:agent`,
turn,
author: { kind: 'agent' },
parts: [
diff --git a/apps/web/src/features/block-agent/component/AgentConnections.tsx b/apps/web/src/features/block-agent/component/AgentConnections.tsx
index cee16ec096..4986dc38c1 100644
--- a/apps/web/src/features/block-agent/component/AgentConnections.tsx
+++ b/apps/web/src/features/block-agent/component/AgentConnections.tsx
@@ -23,7 +23,7 @@ export function AgentConnections(props: ParentProps) {
revision: () =>
`${state.sessionId()}:${state
.messages()
- .map((message) => `${message.turn}:${message.author.kind}`)
+ .map((message) => message.key)
.join(',')}`,
connect: connectPipedreamApp,
resume: async (app) => {
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
index b9058ad3c3..62d2d8bfd2 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
@@ -164,6 +164,7 @@ const message = (
stop: FoldedMessage['stop'] = { kind: 'end_turn' }
): FoldedMessage => ({
agentSessionId: 'session',
+ key: '0:agent',
requestId: null,
pending: false,
postedAt: null,
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index 1cb26047c6..7a6bb4e5fe 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -122,8 +122,7 @@ function AgentMessagePart(props: {
part={part()}
context={{
sessionId: props.message.agentSessionId,
- // Turn and side identify a message within its session.
- messageId: `${props.message.agentSessionId}:${props.message.turn}:${props.message.author.kind}`,
+ messageId: `${props.message.agentSessionId}:${props.message.key}`,
partIndex: props.index,
inFlight: props.inFlight,
followedBy: toolUsedAfter(props.message.parts, props.index),
diff --git a/apps/web/src/features/block-agent/component/Transcript.test.tsx b/apps/web/src/features/block-agent/component/Transcript.test.tsx
index 90e8b11d95..f569c643a7 100644
--- a/apps/web/src/features/block-agent/component/Transcript.test.tsx
+++ b/apps/web/src/features/block-agent/component/Transcript.test.tsx
@@ -62,6 +62,7 @@ vi.mock('./ReplyToSelection', () => ({
const message = (turn: number, text = 'hello'): FoldedMessage =>
({
agentSessionId: 'session',
+ key: `${turn}:agent`,
turn,
author: { kind: 'agent' },
parts: [{ kind: 'text', text }],
@@ -219,7 +220,11 @@ describe('Transcript live turn', () => {
session.turn = () => 'running';
const view = mount([
message(0),
- { ...message(1), author: { kind: 'user', userId: 'u' } } as FoldedMessage,
+ {
+ ...message(1),
+ key: '1:user',
+ author: { kind: 'user', userId: 'u' },
+ } as FoldedMessage,
]);
await settle();
expect(inFlight(view)).toEqual(['0:agent=false', '1:user=false']);
@@ -258,6 +263,7 @@ describe('Transcript with the shared TanStack ThreadList', () => {
setMessages([
{
...message(0),
+ key: '0:user',
author: { kind: 'user', userId: 'owner' },
} as FoldedMessage,
...Array.from({ length: 80 }, (_, turn) => message(turn)),
diff --git a/apps/web/src/features/block-agent/component/Transcript.tsx b/apps/web/src/features/block-agent/component/Transcript.tsx
index b084259698..0236e7fa9e 100644
--- a/apps/web/src/features/block-agent/component/Transcript.tsx
+++ b/apps/web/src/features/block-agent/component/Transcript.tsx
@@ -52,7 +52,7 @@ export function Transcript(props: { searchTarget?: AgentMessageTarget }) {
() =>
new Map(
messages().map((message) => [
- `${message.agentSessionId}:${message.turn}:${message.author.kind}`,
+ `${message.agentSessionId}:${message.key}`,
message,
])
)
diff --git a/apps/web/src/features/block-agent/context/create-agent-session.test.tsx b/apps/web/src/features/block-agent/context/create-agent-session.test.tsx
index 7159d3467a..a167274861 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session.test.tsx
+++ b/apps/web/src/features/block-agent/context/create-agent-session.test.tsx
@@ -226,109 +226,212 @@ it('settles view readiness when provisioning fails without a session id', async
expect(readiness.painted).toHaveBeenCalledOnce();
});
-it('appends without traversing settled history and preserves keyed rows across updates and rebases', async () => {
- const firstParts = [{ kind: 'text' as const, text: 'settled' }];
- let traversals = 0;
- const first = new Proxy<FoldedMessage>(
- {
- agentSessionId: SESSION,
- turn: 0,
- author: { kind: 'agent' },
- requestId: null,
- parts: firstParts,
- stop: null,
- pending: false,
- segments: [],
- phase: null,
- postedAt: null,
- },
- {
- ownKeys(target) {
- traversals++;
- return Reflect.ownKeys(target);
- },
- }
- );
- fold.readSession.mockResolvedValue({
- messages: [first],
- metadata: { turn: 'idle' },
- });
- let handle: AgentSessionHandle | undefined;
- function TranscriptState() {
- handle = createAgentSession(() => SESSION, {
- userId: () => 'me',
- provisioning: () => false,
- });
- return <h1>{handle.session()?.name}</h1>;
- }
- render(() => (
- <Suspense fallback={null}>
- <TranscriptState />
- </Suspense>
- ));
- await screen.findByText('A session');
- if (!handle) throw new Error('session was not mounted');
- const messages = handle.messages;
- const shared = AgentSession.get(SESSION);
- if (!shared) throw new Error('session was not acquired');
- const row: AgentSessionLogEntryDto = {
- id: 'row',
- direction: 'to_server',
- createdAt: '2026-01-01T00:00:00Z',
- content: { type: 'event', event: 'acp_ready' },
- };
- const publish = async (events: FoldedStreamEvent[]) => {
- fold.pushSession.mockResolvedValueOnce(events);
- AgentSession.ingest({ agentSessionId: SESSION, entries: [row] });
- await shared.snapshot();
- };
- const settled = messages()[0];
- traversals = 0;
- const tail: FoldedMessage = {
- ...first,
- turn: 2,
- parts: [{ kind: 'text', text: 'tail' }],
+describe('the transcript store', () => {
+ const settledReply: FoldedMessage = {
+ agentSessionId: SESSION,
+ key: '0:agent',
+ turn: 0,
+ author: { kind: 'agent' },
+ requestId: null,
+ parts: [{ kind: 'text', text: 'settled' }],
+ stop: { kind: 'end_turn' },
+ pending: false,
+ segments: [],
+ phase: null,
+ postedAt: null,
};
- // Count only traversal by the projection, excluding construction above.
- traversals = 0;
- await publish([{ kind: 'new', message: tail }]);
- expect(traversals).toBe(0);
- expect(messages()[0]).toBe(settled);
- const tailIdentity = messages()[1];
-
- const middle: FoldedMessage = {
- ...tail,
+ const prompt: FoldedMessage = {
+ agentSessionId: SESSION,
+ key: '1:user',
turn: 1,
author: { kind: 'user', userId: 'me' },
+ requestId: null,
+ parts: [{ kind: 'text', text: 'and then?' }],
+ stop: null,
+ pending: false,
+ segments: [],
+ phase: null,
+ postedAt: null,
};
const reply: FoldedMessage = {
- ...middle,
+ agentSessionId: SESSION,
+ key: '1:agent',
+ turn: 1,
author: { kind: 'agent' },
+ requestId: null,
+ parts: [{ kind: 'text', text: 'working' }],
+ stop: null,
+ pending: false,
+ segments: [],
+ phase: null,
+ postedAt: null,
};
- await publish([
- { kind: 'new', message: reply },
- { kind: 'new', message: middle },
- {
- kind: 'update',
- message: { ...tail, parts: [{ kind: 'text', text: 'updated' }] },
- },
- ]);
- expect(
- messages().map((message) => [message.turn, message.author.kind])
- ).toEqual([
- [0, 'agent'],
- [1, 'user'],
- [1, 'agent'],
- [2, 'agent'],
- ]);
- expect(messages()[0]).toBe(settled);
- expect(messages()[3]).toBe(tailIdentity);
- const middleIdentity = messages()[1];
- await publish([
- { kind: 'replace', messages: [middle, { ...tail, pending: true }] },
- ]);
- expect(messages().map((message) => message.turn)).toEqual([1, 2]);
- expect(messages()[0]).toBe(middleIdentity);
- expect(messages()[1]).toBe(tailIdentity);
- expect(messages()[1]?.pending).toBe(true);
+
+ /** Mounts a session that loads `initial`, and publishes fold events to it. */
+ async function mountTranscript(initial: FoldedMessage[]) {
+ fold.readSession.mockResolvedValue({
+ messages: initial,
+ metadata: { turn: 'idle' },
+ });
+ let handle: AgentSessionHandle | undefined;
+ function TranscriptState() {
+ handle = createAgentSession(() => SESSION, {
+ userId: () => 'me',
+ provisioning: () => false,
+ });
+ return <h1>{handle.session()?.name}</h1>;
+ }
+ render(() => (
+ <Suspense fallback={null}>
+ <TranscriptState />
+ </Suspense>
+ ));
+ await screen.findByText('A session');
+ const shared = AgentSession.get(SESSION);
+ if (!handle || !shared) throw new Error('session was not mounted');
+ const row: AgentSessionLogEntryDto = {
+ id: 'row',
+ direction: 'to_server',
+ createdAt: '2026-01-01T00:00:00Z',
+ content: { type: 'event', event: 'acp_ready' },
+ };
+ const publish = async (events: FoldedStreamEvent[]) => {
+ fold.pushSession.mockResolvedValueOnce(events);
+ AgentSession.ingest({ agentSessionId: SESSION, entries: [row] });
+ await shared.snapshot();
+ };
+ return { messages: handle.messages, publish };
+ }
+
+ it('appends without reading settled rows', async () => {
+ let traversals = 0;
+ const watched = new Proxy<FoldedMessage>(settledReply, {
+ ownKeys(target) {
+ traversals++;
+ return Reflect.ownKeys(target);
+ },
+ });
+ const { messages, publish } = await mountTranscript([watched]);
+ const settled = messages()[0];
+ traversals = 0;
+
+ await publish([{ kind: 'new', message: prompt }]);
+ await publish([{ kind: 'new', message: reply }]);
+
+ expect(traversals).toBe(0);
+ expect(messages().map((message) => message.key)).toEqual([
+ '0:agent',
+ '1:user',
+ '1:agent',
+ ]);
+ expect(messages()[0]).toBe(settled);
+ });
+
+ it('keeps a streaming row the same object as it updates', async () => {
+ const { messages, publish } = await mountTranscript([
+ settledReply,
+ prompt,
+ reply,
+ ]);
+ const streaming = messages()[2];
+
+ await publish([
+ {
+ kind: 'update',
+ message: {
+ ...reply,
+ parts: [{ kind: 'text', text: 'working on it' }],
+ },
+ },
+ ]);
+ await publish([
+ {
+ kind: 'update',
+ message: {
+ ...reply,
+ parts: [{ kind: 'text', text: 'done' }],
+ stop: { kind: 'end_turn' },
+ },
+ },
+ ]);
+
+ expect(messages()[2]).toBe(streaming);
+ expect(messages()[2]?.parts).toEqual([{ kind: 'text', text: 'done' }]);
+ expect(messages()[2]?.stop).toEqual({ kind: 'end_turn' });
+ });
+
+ it('drops a speculated row on rebase and keeps rows the rebase retains', async () => {
+ const { messages, publish } = await mountTranscript([settledReply]);
+ const settled = messages()[0];
+ const speculated: FoldedMessage = { ...prompt, pending: true };
+ await publish([{ kind: 'new', message: speculated }]);
+ const speculatedRow = messages()[1];
+
+ // The log has not confirmed the prompt yet: a rebase without it.
+ await publish([{ kind: 'replace', messages: [settledReply] }]);
+ expect(messages().map((message) => message.key)).toEqual(['0:agent']);
+ expect(messages()[0]).toBe(settled);
+
+ // Confirmed: the prompt is back, no longer pending, ahead of its reply.
+ await publish([
+ { kind: 'replace', messages: [settledReply, prompt, reply] },
+ ]);
+ expect(messages().map((message) => message.key)).toEqual([
+ '0:agent',
+ '1:user',
+ '1:agent',
+ ]);
+ expect(messages()[0]).toBe(settled);
+ expect(messages()[1]).not.toBe(speculatedRow);
+ expect(messages()[1]?.pending).toBe(false);
+ });
+
+ it('keeps a confirmed speculation in place across a rebase', async () => {
+ const { messages, publish } = await mountTranscript([settledReply]);
+ await publish([{ kind: 'new', message: { ...prompt, pending: true } }]);
+ const speculatedRow = messages()[1];
+
+ await publish([{ kind: 'replace', messages: [settledReply, prompt] }]);
+
+ expect(messages()[1]).toBe(speculatedRow);
+ expect(messages()[1]?.pending).toBe(false);
+ });
+
+ it('inserts a message that arrives out of order between its neighbours', async () => {
+ const { messages, publish } = await mountTranscript([settledReply]);
+ const settled = messages()[0];
+ await publish([{ kind: 'new', message: reply }]);
+ const replyRow = messages()[1];
+
+ await publish([{ kind: 'new', message: prompt }]);
+
+ expect(messages().map((message) => message.key)).toEqual([
+ '0:agent',
+ '1:user',
+ '1:agent',
+ ]);
+ expect(messages()[0]).toBe(settled);
+ expect(messages()[2]).toBe(replyRow);
+ });
+
+ it('updates a row before the tail in place', async () => {
+ const { messages, publish } = await mountTranscript([
+ settledReply,
+ { ...prompt, pending: true },
+ reply,
+ ]);
+ const promptRow = messages()[1];
+ const replyRow = messages()[2];
+
+ await publish([{ kind: 'update', message: prompt }]);
+
+ expect(messages().map((message) => message.key)).toEqual([
+ '0:agent',
+ '1:user',
+ '1:agent',
+ ]);
+ expect(messages()[1]).toBe(promptRow);
+ expect(messages()[1]?.pending).toBe(false);
+ expect(messages()[2]).toBe(replyRow);
+ });
});
diff --git a/apps/web/src/features/block-agent/context/create-agent-session.ts b/apps/web/src/features/block-agent/context/create-agent-session.ts
index 79a4d941c4..49312f767a 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session.ts
@@ -42,7 +42,7 @@ import {
onCleanup,
untrack,
} from 'solid-js';
-import { createStore, produce, reconcile } from 'solid-js/store';
+import { createStore, reconcile, unwrap } from 'solid-js/store';
import { issueSessionAction } from '../queries/issue-session-action';
import type { EffortSelection } from '../state/session-config';
import { configureSessionModel } from './configure-session-model';
@@ -99,10 +99,6 @@ function compareMessages(a: FoldedMessage, b: FoldedMessage): number {
return authorRank(a) - authorRank(b);
}
-function sameMessage(a: FoldedMessage, b: FoldedMessage): boolean {
- return a.turn === b.turn && a.author.kind === b.author.kind;
-}
-
/**
* `sessionId` is absent while a just-created session's `POST` is still on the
* wire (`pending-session.ts`). `createResource` treats an absent source as
@@ -139,71 +135,42 @@ export function createAgentSession(
const [bot, setBot] = createSignal<SessionBot>();
const [metadata, setMetadata] = createSignal<SessionMetadata>();
- const upsert = (messages: FoldedMessage[]) =>
- batch(() => {
- for (const message of messages) {
- // The fold publishes ordered snapshots as well as individual updates.
- // Find the row without scanning settled history for each snapshot row.
- let start = 0;
- let end = list.length;
- while (start < end) {
- const middle = (start + end) >>> 1;
- if (compareMessages(list[middle]!, message) < 0) start = middle + 1;
- else end = middle;
- }
- if (start < list.length && sameMessage(list[start]!, message)) {
- // Path-scoped reconcile preserves settled rows and streaming parts.
- setList(start, reconcile(message));
- } else if (start === list.length) {
- // Producing the whole array unwraps all earlier messages on every
- // append. Write only the new index, including during initial load.
- setList(start, message);
- } else {
- const at = start;
- setList(
- produce((current: FoldedMessage[]) =>
- current.splice(at, 0, message)
- )
- );
- }
- }
- });
-
- /** A row's identity in the transcript, and the transcript's render key. */
- const keyOf = (message: FoldedMessage) =>
- `${message.turn}:${message.author.kind}`;
-
// A whole new view of the conversation: what a load reports, and what every
// rebase reports while something is speculated.
//
- // Merged row by row rather than spliced wholesale. A splice hands the store
- // a fresh object for every index, so Solid remounts every row - the
- // transcript re-measures, entrance motions replay, and a streaming turn
- // visibly jumps. A rebase happens on *every* confirmed frame while an
- // action is pending, so that jump was the whole turn flickering. Reconciling
- // each row against the one already there keeps identity for everything that
- // did not actually change.
+ // Keyed by each message's stable `key` (`<turn>:<author kind>`), so a row
+ // the new view still holds stays the same store object, reconciled in place,
+ // and only rows that came or went mount or unmount. A rebase happens on
+ // every confirmed frame while an action is pending; reconciling by position
+ // or swapping in fresh objects would remount the transcript and replay the
+ // whole turn. Not `merge`: a row can move.
const replace = (messages: FoldedMessage[]) =>
- batch(() => {
- const wanted = new Set(messages.map(keyOf));
- // Tail first, so the indices ahead of each removal still hold.
- for (let index = list.length - 1; index >= 0; index--) {
- if (wanted.has(keyOf(list[index]!))) continue;
- setList(
- produce((current: FoldedMessage[]) => {
- current.splice(index, 1);
- })
- );
- }
- upsert(messages);
- });
+ setList(reconcile(messages, { key: 'key' }));
+
+ // One streamed message. The fold appends in transcript order, so the tail is
+ // the only row this reads: settled history is never walked per event.
+ const upsert = (message: FoldedMessage) => {
+ const last = list.at(-1);
+ if (last?.key === message.key) {
+ setList(list.length - 1, reconcile(message));
+ } else if (!last || compareMessages(last, message) < 0) {
+ setList(list.length, message);
+ } else {
+ // Out of order or an earlier row's update: rare, so take the keyed
+ // path over the whole list.
+ const next = unwrap(list).filter((row) => row.key !== message.key);
+ const at = next.findIndex((row) => compareMessages(row, message) > 0);
+ next.splice(at === -1 ? next.length : at, 0, message);
+ replace(next);
+ }
+ };
const applyEvents = (events: FoldedStreamEvent[]) =>
batch(() => {
for (const event of events) {
if (event.kind === 'replace') replace(event.messages);
else if (event.kind === 'metadata') setMetadata(event.metadata);
- else upsert([event.message]);
+ else upsert(event.message);
}
});
diff --git a/apps/web/src/features/block-agent/context/pending-session.test.tsx b/apps/web/src/features/block-agent/context/pending-session.test.tsx
index a5153786af..5a7262c3cb 100644
--- a/apps/web/src/features/block-agent/context/pending-session.test.tsx
+++ b/apps/web/src/features/block-agent/context/pending-session.test.tsx
@@ -165,6 +165,7 @@ describe('pending navigation ownership', () => {
kind: 'update',
message: {
agentSessionId: id,
+ key: '1:user',
turn: 1,
author: { kind: 'user', userId: 'me' },
requestId: request.actionId ?? null,
@@ -180,6 +181,7 @@ describe('pending navigation ownership', () => {
kind: 'new',
message: {
agentSessionId: id,
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
requestId: null,
@@ -421,6 +423,7 @@ describe('first prompt on the create', () => {
kind: 'update',
message: {
agentSessionId: id,
+ key: '1:user',
turn: 1,
author: { kind: 'user', userId: 'me' },
requestId: actionId,
@@ -436,6 +439,7 @@ describe('first prompt on the create', () => {
kind: 'new',
message: {
agentSessionId: id,
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
requestId: null,
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index 01b5e0ffea..66fa71e22d 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -413,6 +413,7 @@ function ToolReplayDemo() {
onCleanup(() => clearInterval(timer));
const message = (): FoldedMessage => ({
agentSessionId: 'tool-replay',
+ key: '0:agent',
requestId: null,
pending: false,
segments: [],
@@ -463,6 +464,7 @@ function DisplayResultsDemo() {
const [pending, setPending] = createSignal(false);
const message = (): FoldedMessage => ({
agentSessionId: 'display-results-demo',
+ key: '0:agent',
requestId: null,
pending: false,
segments: [],
@@ -544,6 +546,7 @@ function presentViewPart(id: string): MessagePart {
function PresentViewDemo() {
const message: FoldedMessage = {
agentSessionId: 'present-view-demo',
+ key: '0:agent',
requestId: null,
pending: false,
segments: [],
@@ -591,6 +594,7 @@ function PresentViewDmDemo() {
const FIXTURE_MESSAGE: FoldedMessage = {
agentSessionId: 'demo',
+ key: '0:agent',
requestId: null,
pending: false,
segments: [],
@@ -840,6 +844,7 @@ const FIXTURE_MESSAGE: FoldedMessage = {
/** A live Cursor-shaped turn: earlier reasoning has settled, the tail has not. */
const FIXTURE_IN_FLIGHT: FoldedMessage = {
agentSessionId: 'demo',
+ key: '1:agent',
requestId: null,
pending: false,
segments: [],
@@ -886,6 +891,7 @@ const FIXTURE_IN_FLIGHT: FoldedMessage = {
*/
const FIXTURE_UNCLOSED: FoldedMessage = {
agentSessionId: 'demo',
+ key: '2:agent',
requestId: null,
pending: false,
segments: [],
@@ -955,6 +961,7 @@ function PromptAuthorDemo() {
const userId = useUserId();
const prompt = (userId: string | null, text: string): FoldedMessage => ({
agentSessionId: 'demo',
+ key: '0:user',
requestId: null,
pending: false,
segments: [],
diff --git a/apps/web/src/features/block-agent/state/live-turn.test.ts b/apps/web/src/features/block-agent/state/live-turn.test.ts
index cc23340b17..51194a9646 100644
--- a/apps/web/src/features/block-agent/state/live-turn.test.ts
+++ b/apps/web/src/features/block-agent/state/live-turn.test.ts
@@ -4,6 +4,7 @@ import { isLiveTurn, liveTurnMessage } from './live-turn';
const agent = (turn: number, stop: FoldedMessage['stop']): FoldedMessage => ({
agentSessionId: 'session',
+ key: `${turn}:agent`,
pending: false,
segments: [],
phase: null,
@@ -16,6 +17,7 @@ const agent = (turn: number, stop: FoldedMessage['stop']): FoldedMessage => ({
});
const user = (turn: number): FoldedMessage => ({
agentSessionId: 'session',
+ key: `${turn}:user`,
pending: false,
segments: [],
phase: null,
@@ -28,6 +30,7 @@ const user = (turn: number): FoldedMessage => ({
});
const control = (turn: number): FoldedMessage => ({
agentSessionId: 'session',
+ key: `${turn}:user`,
pending: false,
segments: [],
phase: null,
diff --git a/apps/web/src/features/block-agent/state/session-notifications.test.ts b/apps/web/src/features/block-agent/state/session-notifications.test.ts
index cbb84c9c95..c575c5b9e8 100644
--- a/apps/web/src/features/block-agent/state/session-notifications.test.ts
+++ b/apps/web/src/features/block-agent/state/session-notifications.test.ts
@@ -158,6 +158,7 @@ it('suppresses review events only when their trusted card is in the thread', ()
];
const card: FoldedMessage = {
agentSessionId: 'session',
+ key: '0:agent',
turn: 0,
author: { kind: 'agent' },
requestId: null,
diff --git a/apps/web/src/features/block-agent/state/session-summary.test.ts b/apps/web/src/features/block-agent/state/session-summary.test.ts
index eca724bdb5..db45666269 100644
--- a/apps/web/src/features/block-agent/state/session-summary.test.ts
+++ b/apps/web/src/features/block-agent/state/session-summary.test.ts
@@ -12,6 +12,7 @@ import {
function message(turn: number, parts: MessagePart[]): FoldedMessage {
return {
agentSessionId: 'session',
+ key: `${turn}:agent`,
requestId: null,
pending: false,
segments: [],
diff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.ts
index 820df933bf..74da0060fc 100644
--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts
+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts
@@ -1237,6 +1237,7 @@ describe('AgentSession', () => {
live.rendered('fetched', [
{
agentSessionId: SESSION,
+ key: '0:user',
turn: 0,
author: { kind: 'user', userId: null },
requestId: null,
@@ -1249,6 +1250,7 @@ describe('AgentSession', () => {
},
{
agentSessionId: SESSION,
+ key: '0:agent',
turn: 0,
author: { kind: 'agent' },
requestId: null,
@@ -1380,6 +1382,7 @@ describe('AgentSession', () => {
kind: 'update',
message: {
agentSessionId: SESSION,
+ key: '1:user',
turn: 1,
author: { kind: 'user', userId: 'macro|[email protected]' },
requestId: actionId,
@@ -1395,6 +1398,7 @@ describe('AgentSession', () => {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
requestId: null,
@@ -1446,6 +1450,7 @@ describe('AgentSession', () => {
kind: 'update',
message: {
agentSessionId: SESSION,
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
requestId: null,
diff --git a/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts b/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts
index f88b24904d..6d44a3378a 100644
--- a/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts
+++ b/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts
@@ -91,6 +91,7 @@ function withText(text = 'Hello'): PromptTrace {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '1:user',
turn: 1,
author: { kind: 'user', userId: null },
requestId: ACTION,
@@ -106,6 +107,7 @@ function withText(text = 'Hello'): PromptTrace {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
requestId: null,
@@ -362,6 +364,7 @@ describe('PromptTrace', () => {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '1:user',
turn: 1,
author: { kind: 'user', userId: 'macro|[email protected]' },
requestId: ACTION,
@@ -380,6 +383,7 @@ describe('PromptTrace', () => {
kind: 'update',
message: {
agentSessionId: SESSION,
+ key: '1:user',
turn: 1,
author: { kind: 'user', userId: 'macro|[email protected]' },
requestId: ACTION,
@@ -398,6 +402,7 @@ describe('PromptTrace', () => {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '1:agent',
turn: 1,
author: { kind: 'agent' },
requestId: null,
@@ -469,6 +474,7 @@ describe('PromptTrace', () => {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '0:user',
turn: 0,
author: { kind: 'user', userId: null },
requestId: ACTION,
@@ -484,6 +490,7 @@ describe('PromptTrace', () => {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '0:agent',
turn: 0,
author: { kind: 'agent' },
requestId: null,
@@ -525,6 +532,7 @@ describe('PromptTrace', () => {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '0:user',
turn: 0,
author: { kind: 'user', userId: null },
requestId: ACTION,
@@ -540,6 +548,7 @@ describe('PromptTrace', () => {
kind: 'new',
message: {
agentSessionId: SESSION,
+ key: '0:agent',
turn: 0,
author: { kind: 'agent' },
requestId: null,
@@ -580,6 +589,7 @@ describe('PromptTrace', () => {
messages: [
{
agentSessionId: SESSION,
+ key: '0:agent',
turn: 0,
author: { kind: 'agent' },
requestId: null,
@@ -592,6 +602,7 @@ describe('PromptTrace', () => {
},
{
agentSessionId: SESSION,
+ key: '1:user',
turn: 1,
author: { kind: 'user', userId: 'macro|[email protected]' },
requestId: ACTION,
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
index 690f824a4b..7a630b3ef4 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
@@ -104,6 +104,7 @@ function createModel(props: MagicChipDecoratorProps) {
const prompt: FoldedMessage = {
requestId: null,
agentSessionId: 'session',
+ key: '0:user',
turn: 0,
author: { kind: 'user', userId: 'macro|[email protected]' },
parts: [{ kind: 'text', text: 'Say hi' }],
@@ -117,6 +118,7 @@ const prompt: FoldedMessage = {
const response: FoldedMessage = {
requestId: null,
agentSessionId: 'session',
+ key: '0:agent',
turn: 0,
author: { kind: 'agent' },
parts: [{ kind: 'text', text: 'Hi!' }],
@@ -239,6 +241,7 @@ describe('createMagicChipModel', () => {
{
...openResponse,
turn: 4,
+ key: '4:agent',
parts: [
{
kind: 'tool_use',
@@ -468,6 +471,7 @@ describe('createMagicChipModel', () => {
{
...openResponse,
turn: 3,
+ key: '3:agent',
parts: [{ kind: 'text', text: 'Newest stream' }],
},
]);
@@ -479,6 +483,7 @@ describe('createMagicChipModel', () => {
{
...response,
turn: 1,
+ key: '1:agent',
parts: [{ kind: 'text', text: 'Late old patch' }],
},
]);
@@ -487,6 +492,7 @@ describe('createMagicChipModel', () => {
{
...response,
turn: 3,
+ key: '3:agent',
parts: [{ kind: 'text', text: 'Newest answer' }],
},
]);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
index 76a499dc72..b36e676e1d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
@@ -8,6 +8,7 @@ import {
const response = (overrides: Partial<FoldedMessage> = {}): FoldedMessage => ({
agentSessionId: 'session',
+ key: '0:agent',
requestId: null,
turn: 0,
author: { kind: 'agent' },
diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
index aeea109fa3..0bb2b4e284 100644
--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
@@ -974,6 +974,12 @@ export type FoldedMessage = FoldedMessage_Serialize | FoldedMessage_Deserialize;
export type FoldedMessage_Deserialize = {
/** Session that scopes this message id. */
agentSessionId: string;
+ /**
+ * The message's identity within its session, `<turn>:<author kind>`
+ * (`3:agent`): stable across streaming updates, rebases, and pending
+ * flipping off, so a reader can key and reconcile rows by it.
+ */
+ key: string;
/** The turn within the session, assigned in log order from zero. */
turn: number;
/** Who produced the message. */
@@ -1016,6 +1022,12 @@ export type FoldedMessage_Deserialize = {
export type FoldedMessage_Serialize = {
/** Session that scopes this message id. */
agentSessionId: string;
+ /**
+ * The message's identity within its session, `<turn>:<author kind>`
+ * (`3:agent`): stable across streaming updates, rebases, and pending
+ * flipping off, so a reader can key and reconcile rows by it.
+ */
+ key: string;
/** The turn within the session, assigned in log order from zero. */
turn: number;
/** Who produced the message. */
diff --git a/crates/folds/agent_fold/src/inbound/wire.rs b/crates/folds/agent_fold/src/inbound/wire.rs
index 171fb6cadb..585655e4cf 100644
--- a/crates/folds/agent_fold/src/inbound/wire.rs
+++ b/crates/folds/agent_fold/src/inbound/wire.rs
@@ -26,6 +26,10 @@ mod test;
pub struct FoldedMessage {
/// Session that scopes this message id.
agent_session_id: String,
+ /// The message's identity within its session, `<turn>:<author kind>`
+ /// (`3:agent`): stable across streaming updates, rebases, and pending
+ /// flipping off, so a reader can key and reconcile rows by it.
+ key: String,
/// The turn within the session, assigned in log order from zero.
turn: u32,
/// Who produced the message.
@@ -58,6 +62,7 @@ impl FoldedMessage {
/// Build the browser form of `message`, keyed to `session`.
#[must_use]
pub fn new(session: AgentSessionId, message: ModelFoldedMessage) -> Self {
+ let id = message.id();
let parts = message.parts.into_inner();
let closed = message.stop.is_some();
let (segments, phase) = if matches!(message.author, Author::Agent) {
@@ -70,6 +75,7 @@ impl FoldedMessage {
};
Self {
agent_session_id: session.to_string(),
+ key: format!("{}:{}", id.turn.0, id.author),
turn: message.id.0,
author: message.author,
request_id: message.request_id.map(|id| id.to_string()),
diff --git a/crates/folds/agent_fold/src/inbound/wire/test.rs b/crates/folds/agent_fold/src/inbound/wire/test.rs
index b854730a83..ce9a64626f 100644
--- a/crates/folds/agent_fold/src/inbound/wire/test.rs
+++ b/crates/folds/agent_fold/src/inbound/wire/test.rs
@@ -32,6 +32,7 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {
serde_json::to_value(FoldedMessage::new(session, message)).unwrap(),
json!({
"agentSessionId": session.to_string(),
+ "key": "3:agent",
"turn": 3,
"author": { "kind": "agent" },
"requestId": null,
@@ -151,3 +152,24 @@ fn a_prompt_carries_when_it_was_posted() {
json!("2026-10-15T14:02:00+00:00")
);
}
+
+#[test]
+fn a_message_key_names_its_turn_and_side() {
+ let message = ModelFoldedMessage {
+ id: TurnId(12),
+ author: Author::User { user_id: None },
+ request_id: None,
+ parts: NonEmpty::one(MessagePart::Text {
+ text: "again".to_owned(),
+ }),
+ stop: None,
+ pending: true,
+ posted_at: None,
+ };
+ let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));
+
+ assert_eq!(
+ serde_json::to_value(FoldedMessage::new(session, message)).unwrap()["key"],
+ json!("12:user")
+ );
+}
diff --git a/packages/sdk/generated/agent-fold/index.ts b/packages/sdk/generated/agent-fold/index.ts
index f7d72490a1..2c58a30a0b 100644
--- a/packages/sdk/generated/agent-fold/index.ts
+++ b/packages/sdk/generated/agent-fold/index.ts
@@ -853,6 +853,12 @@ export type FoldedMessage = FoldedMessage_Serialize | FoldedMessage_Deserialize;
export type FoldedMessage_Deserialize = {
/** Session that scopes this message id. */
agentSessionId: string,
+ /**
+ * The message's identity within its session, `<turn>:<author kind>`
+ * (`3:agent`): stable across streaming updates, rebases, and pending
+ * flipping off, so a reader can key and reconcile rows by it.
+ */
+ key: string,
/** The turn within the session, assigned in log order from zero. */
turn: number,
/** Who produced the message. */
@@ -895,6 +901,12 @@ export type FoldedMessage_Deserialize = {
export type FoldedMessage_Serialize = {
/** Session that scopes this message id. */
agentSessionId: string,
+ /**
+ * The message's identity within its session, `<turn>:<author kind>`
+ * (`3:agent`): stable across streaming updates, rebases, and pending
+ * flipping off, so a reader can key and reconcile rows by it.
+ */
+ key: string,
/** The turn within the session, assigned in log order from zero. */
turn: number,
/** Who produced the message. */
diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.ts
index 7cccee7f5b..4412b0d965 100644
--- a/packages/sdk/tests/agent-sessions.test.ts
+++ b/packages/sdk/tests/agent-sessions.test.ts
@@ -530,6 +530,7 @@ describe('AgentSession', () => {
const messages: FoldedMessage[] = [
{
agentSessionId: sessionId,
+ key: '0:agent',
turn: 0,
author: { kind: 'agent' },
requestId: null,