Agent chat: the fold compares two states part by part, to the first difference (#21)
jonas, 2026-11-28 17:51 UTC · d68d7e164ff5aaa8d02edde0052b042915e93e70 · parent 1613b55
1 file changed
M src/components/agent-chat/agent-events.ts
@@ -99,9 +99,31 @@ return chunks; } -/** Two states that the reducer cannot tell apart: plain data, compared as its text. */ -const sameState = (one: AgentUiState, other: AgentUiState) => - one === other || JSON.stringify(one) === JSON.stringify(other); +/** Two states that the reducer cannot tell apart: plain data, compared part by part, and no + * further than the first difference. A state can be large (an answer that runs holds its scripts + * and its words), and two states that differ do so near their top (the count of the open + * activity's steps). As text they cost a second of a frame on a long chat (a profile of the + * engineering manager's chat, 28 Nov 2026: 978 ms of one landing in `JSON.stringify`). */ +function sameState(one: unknown, other: unknown): boolean { + if (one === other) return true; + if (typeof one !== "object" || typeof other !== "object" || one === null || other === null) + return false; + if (Array.isArray(one) !== Array.isArray(other)) return false; + if (Array.isArray(one)) { + const others = other as unknown[]; + if (one.length !== others.length) return false; + for (let at = 0; at < one.length; at += 1) if (!sameState(one[at], others[at])) return false; + return true; + } + const mine = one as Record<string, unknown>; + const theirs = other as Record<string, unknown>; + // a key that holds nothing is no key: the reducer reads `undefined` and a missing key alike + const keys = Object.keys(mine).filter((key) => mine[key] !== undefined); + if (keys.length !== Object.keys(theirs).filter((key) => theirs[key] !== undefined).length) + return false; + for (const key of keys) if (!sameState(mine[key], theirs[key])) return false; + return true; +} /** AN OLDER PAGE, WITHOUT FOLDING THE HELD LOG AGAIN. The page is folded from the start, and then * each held chunk again only until the state reaches what a held chunk began from: from that