Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Preserve chat text reveal across tab switches

Rach Pradhanecaf62c213e4
diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsx
index 064ec6ec..8b474da5 100644
--- a/apps/native/components/site/ChatBubbles.tsx
+++ b/apps/native/components/site/ChatBubbles.tsx
@@ -21,11 +21,11 @@ import { turnBlocks, type AssistantTurn } from "@/lib/acp";
import { useSmoothStream } from "./useSmoothStream";
/** Reveal updates belong to this text block, not the entire tool/reasoning tree. */
-const StreamingMarkdown = memo(function StreamingMarkdown({ text, live, onOpenPath, scroller, following }: {
+const StreamingMarkdown = memo(function StreamingMarkdown({ text, live, blockId, onOpenPath, scroller, following }: {
text: string; live: boolean; onOpenPath?: (path: string) => void;
- scroller?: RefObject<HTMLDivElement | null>; following: boolean;
+ blockId: string; scroller?: RefObject<HTMLDivElement | null>; following: boolean;
}) {
- const shown = useSmoothStream(text, live);
+ const shown = useSmoothStream(text, live, blockId);
useLayoutEffect(() => {
pinScrollerTail(scroller?.current ?? null, following);
}, [shown, scroller, following]);
@@ -136,6 +136,7 @@ export const UserBubble = memo(function UserBubble({ text, promptIndex, onEdit }
export const AssistantBody = memo(function AssistantBody({
turn,
+ messageId,
onOpenPath,
onReview,
onAnswer,
@@ -149,6 +150,7 @@ export const AssistantBody = memo(function AssistantBody({
promptIndex,
}: {
turn: AssistantTurn;
+ messageId?: number;
onOpenPath?: (path: string) => void;
onReview?: () => void;
onAnswer?: (text: string, cancelled?: boolean) => void | Promise<void>;
@@ -210,7 +212,7 @@ export const AssistantBody = memo(function AssistantBody({
</div>
) : (
<div key={`text-${i}`} className="mt-3 max-w-[630px]">
- {usage ? <UsageSummary text={block.text} /> : <StreamingMarkdown text={block.text} live={i === lastTextIndex && live}
+ {usage ? <UsageSummary text={block.text} /> : <StreamingMarkdown text={block.text} live={i === lastTextIndex && live} blockId={`${messageId ?? "standalone"}:${i}`}
onOpenPath={onOpenPath} scroller={scroller} following={i === lastTextIndex && following} />}
</div>
),
diff --git a/apps/native/components/site/ChatSplitLayout.tsx b/apps/native/components/site/ChatSplitLayout.tsx
index 66efd034..936d3478 100644
--- a/apps/native/components/site/ChatSplitLayout.tsx
+++ b/apps/native/components/site/ChatSplitLayout.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, type ReactNode } from "react";
import { IconFolder } from "@/lib/icons";
import type { Chat } from "./harness-types";
import { ComposerDraftContext } from "@/components/primitives/useComposerDraft";
+import { SeenTextContext } from "./useSmoothStream";
import { createComposerDraft, type ComposerDraftStore } from "@/lib/composer-draft";
import SplitDivider from "./SplitDivider";
import paneStyles from "./chat-pane.module.css";
@@ -17,11 +18,13 @@ export default function ChatSplitLayout({ threads, liveChatIds, activeId, direct
}) {
const mod = useCommandGlyph();
const drafts = useRef(new Map<number, ComposerDraftStore>());
+ const seenText = useRef(new Map<number, Map<string, string>>());
const liveKey = liveChatIds?.join(",");
useEffect(() => {
if (liveKey === undefined) return;
const live = new Set(liveKey.split(",").filter(Boolean).map(Number));
for (const [id, store] of drafts.current) if (!live.has(id)) { store.dispose(); drafts.current.delete(id); }
+ for (const id of seenText.current.keys()) if (!live.has(id)) seenText.current.delete(id);
}, [liveKey]);
const mounted = useRef(false);
useEffect(() => {
@@ -37,6 +40,11 @@ export default function ChatSplitLayout({ threads, liveChatIds, activeId, direct
if (!store) { store = createComposerDraft(); drafts.current.set(id, store); }
return store;
};
+ const seenFor = (id: number) => {
+ let seen = seenText.current.get(id);
+ if (!seen) { seen = new Map(); seenText.current.set(id, seen); }
+ return seen;
+ };
const shownKey=threads.map(thread=>thread.id).join(',');
const tree=useMemo(()=>layout?pruneSplit(layout,new Set(threads.map(thread=>thread.id)))!:flatSplit(threads.map(thread=>thread.id),direction),[layout,shownKey,direction]);
const geometry=useMemo(()=>splitGeometry(tree),[tree]);
@@ -59,7 +67,7 @@ export default function ChatSplitLayout({ threads, liveChatIds, activeId, direct
{split && <span title={place.path} aria-label={`Project ${place.project}${place.worktree ? ", worktree" : ""}`} className="flex min-w-0 max-w-[50%] items-center gap-1 text-[11px] text-ink-3"><IconFolder size={13}/><span className="truncate">{place.project}</span>{place.worktree && <span className="shrink-0 rounded bg-inset px-1 text-[10px]">worktree</span>}</span>}
{split && <button type="button" aria-label="Close this split" title={`Close this chat (${mod}W)`} onClick={()=>onClose(thread.id)} className="flex size-6 shrink-0 items-center justify-center rounded text-ink-3 hover:bg-hover hover:text-ink">×</button>}
</header>}
- <ComposerDraftContext.Provider value={draftFor(thread.id)}>{body(thread)}</ComposerDraftContext.Provider>
+ <ComposerDraftContext.Provider value={draftFor(thread.id)}><SeenTextContext.Provider value={seenFor(thread.id)}>{body(thread)}</SeenTextContext.Provider></ComposerDraftContext.Provider>
</section>;
})}
{geometry.dividers.map(({node,box},index)=><SplitDivider key={node.key} node={node} box={box} tree={tree} onChange={onLayoutChange} index={index}/>)}
diff --git a/apps/native/components/site/ChatTranscript.tsx b/apps/native/components/site/ChatTranscript.tsx
index 30808628..ad95a282 100644
--- a/apps/native/components/site/ChatTranscript.tsx
+++ b/apps/native/components/site/ChatTranscript.tsx
@@ -83,7 +83,7 @@ export default memo(function ChatTranscript({ messages, register, following, onO
? message.origin === "notification"
? <SessionNotice key={message.id} text={message.text} />
: <UserBubble key={message.id} text={message.text} promptIndex={prompts[start + index]} onEdit={snapshot || !onEditPrompt ? undefined : onEditPrompt} />
- : <AssistantBody key={message.id} turn={message.turn} onOpenPath={onOpenPath} onReview={onReview} onAnswer={onAnswer}
+ : <AssistantBody key={message.id} messageId={message.id} turn={message.turn} onOpenPath={onOpenPath} onReview={onReview} onAnswer={onAnswer}
retryDisabled={busy} promptIndex={prompts[start + index]} onRetry={snapshot || !onEditPrompt || message.turn.status !== "error" ? undefined : retryPrompt}
usage={(() => { const previous = messages[start + index - 1]; return previous?.role === "user" && /^\/(usage|cost)$/.test(previous.text.trim()); })()}
scroller={scroller} following={following && start + index === messages.length - 1} snapshot={snapshot} />)}
diff --git a/apps/native/components/site/useSmoothStream.ts b/apps/native/components/site/useSmoothStream.ts
index af923eb7..2585f7b7 100644
--- a/apps/native/components/site/useSmoothStream.ts
+++ b/apps/native/components/site/useSmoothStream.ts
@@ -1,22 +1,26 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
import { createSmoothStream } from "@/lib/smooth-stream";
+export const SeenTextContext = createContext<Map<string, string> | null>(null);
+
/** Reveal live text only while visible and motion is welcome. Switching either
* condition off flushes the latest text and cancels the pending frame.
- * The controller starts empty so the first live chunk typewrites instead of
- * painting in as one blob — same as `createSmoothStream("")` in the unit tests. */
-export function useSmoothStream(target: string, live: boolean): string {
- const [shown, setShown] = useState(live ? "" : target);
+ * A new block starts empty; a remounted block starts at the last text shown
+ * in its chat so switching tabs cannot replay that text. */
+export function useSmoothStream(target: string, live: boolean, blockId: string): string {
+ const seen = useContext(SeenTextContext);
+ const initial = useRef(live ? seen?.get(blockId) ?? "" : target);
+ const [shown, setShown] = useState(initial.current);
const latest = useRef(target);
latest.current = target;
const animated = useRef(false);
const stream = useRef<ReturnType<typeof createSmoothStream> | null>(null);
+ const paint = useCallback((text: string) => { seen?.set(blockId, text); setShown(text); }, [seen, blockId]);
useEffect(() => {
if (!live) return;
- const controller = createSmoothStream("", setShown);
- setShown("");
+ const controller = createSmoothStream(initial.current, paint);
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
const syncMotion = () => {
animated.current = !document.hidden && !reduced.matches;
@@ -27,15 +31,18 @@ export function useSmoothStream(target: string, live: boolean): string {
document.addEventListener("visibilitychange", syncMotion);
reduced.addEventListener("change", syncMotion);
return () => {
+ // A tab can disappear mid-reveal. Its received text is old by the time
+ // the user returns; only content received while away should animate.
+ seen?.set(blockId, latest.current);
document.removeEventListener("visibilitychange", syncMotion);
reduced.removeEventListener("change", syncMotion);
controller.dispose();
stream.current = null;
};
- }, [live]);
+ }, [live, blockId, seen, paint]);
useEffect(() => {
if (live) stream.current?.update(target, animated.current);
- else setShown(target);
- }, [target, live]);
+ else { seen?.delete(blockId); setShown(target); }
+ }, [target, live, seen, blockId]);
return live && target.startsWith(shown) ? shown : target;
}
diff --git a/apps/native/lib/assistant-body.test.tsx b/apps/native/lib/assistant-body.test.tsx
index ad8cde27..3bbaee6b 100644
--- a/apps/native/lib/assistant-body.test.tsx
+++ b/apps/native/lib/assistant-body.test.tsx
@@ -1,6 +1,7 @@
import { expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import { AssistantBody } from "../components/site/ChatBubbles";
+import { SeenTextContext } from "../components/site/useSmoothStream";
import { emptyTurn } from "./graff-events";
test("completed turns do not retain a synthetic waiting disclosure", () => {
@@ -54,3 +55,17 @@ test("Retry only exists on an errored turn, and waits while another turn is live
expect(busy).toContain("data-retry-turn");
expect(busy).toMatch(/data-retry-turn[^>]*\sdisabled=/);
});
+
+test("remounted live text starts at the prefix already seen in that chat", () => {
+ const turn = { ...emptyTurn(), status: "streaming" as const, text: "Already seen.\nA new line arrived." };
+ const seen = new Map([["42:0", "Already seen."]]);
+ const render = (prefix: Map<string, string>) => renderToStaticMarkup(
+ <SeenTextContext.Provider value={prefix}><AssistantBody turn={turn} messageId={42} following={false} /></SeenTextContext.Provider>,
+ );
+ const resumed = render(seen);
+ expect(resumed).toContain("Already seen.");
+ expect(resumed).not.toContain("A new line arrived.");
+ seen.set("42:0", turn.text);
+ expect(render(seen)).toContain("A new line arrived.");
+ expect(render(new Map())).not.toContain("Already seen.");
+});
diff --git a/apps/native/lib/smooth-stream.test.ts b/apps/native/lib/smooth-stream.test.ts
index ed282291..63f63f20 100644
--- a/apps/native/lib/smooth-stream.test.ts
+++ b/apps/native/lib/smooth-stream.test.ts
@@ -1,15 +1,41 @@
import { test, expect } from "bun:test";
import { createSmoothStream } from "./smooth-stream";
-function fixture() {
+function fixture(initial = "") {
let now = 0;
const frames: ((now: number) => void)[] = [], painted: string[] = [];
- const stream = createSmoothStream("", text => painted.push(text), {
+ const stream = createSmoothStream(initial, text => painted.push(text), {
now: () => now, frame(callback) { frames.push(callback); return frames.length; }, cancel() {},
});
return { stream, frames, painted, tick(index: number) { now += 1000 / 120; frames[index](now); } };
}
+test("a remounted chat reveals only content added after the last visit", () => {
+ const received = "An answer already received before switching tabs. ".repeat(20);
+ const first = fixture();
+ first.stream.update(received, true);
+ first.tick(0);
+ expect(first.painted.at(-1)?.length).toBeLessThan(received.length);
+ first.stream.dispose();
+
+ // Unmount records all text received in the visible chat, including the
+ // queued tail. A second mount with unchanged content schedules no reveal.
+ const returnVisit = fixture(received);
+ returnVisit.stream.update(received, true);
+ expect(returnVisit.frames).toHaveLength(0);
+ const next = `${received}One new line arrived while away.`;
+ returnVisit.stream.update(next, true);
+ expect(returnVisit.frames).toHaveLength(1);
+ returnVisit.tick(0);
+ expect(returnVisit.painted.at(-1)?.startsWith(received)).toBe(true);
+ returnVisit.stream.dispose();
+
+ const again = fixture(next);
+ again.stream.update(next, true);
+ expect(again.frames).toHaveLength(0);
+ again.stream.dispose();
+});
+
test("starting on the full string never typewrites — the live hook must start empty", () => {
const painted: string[] = [];
const frames: ((now: number) => void)[] = [];