iterate.com / ui

git clone https://git.iterate.com/repos/ui

Agent chat: the fold compares two states part by part, to the first difference (#21)

Card: tasks/let-the-chat-fold-an-older-page-without-refolding-its-whole-held.md.

Pull 20 compared the states of the fold's chunks as text. A profile of the
engineering manager's chat on the local Dash with that release (not pinned
by the Dash) showed one landing of 1,489 ms, of it 978 ms in JSON.stringify:
on a long held log the states are large and stay unequal for many chunks.
The comparison now walks both states and stops at the first difference,
which for an open activity is the count of its steps.

Via: /agents/claude/dash-context-feed-threads-mwy308tb-4d1e63
Session: claude 89f0feea-b83f-4937-8b4a-56af6cb8884b on beelink
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Iterate-Run: /@1866489

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