Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(chat): keep a just-finished turn's reasoning where the reader left it

Bingxi Zhao (Frank)34d7be082786
diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsx
index 8cc446146..b7489d4db 100644
--- a/web/features/chat/ChatStateAdapter.tsx
+++ b/web/features/chat/ChatStateAdapter.tsx
@@ -39,6 +39,7 @@ import {
TraceCache,
compactTracePreview,
settleMessageTrace,
+ traceSettleAction,
type MessageTraceMetadata,
} from "@/features/chat/trace/memory";
import {
@@ -1006,15 +1007,39 @@ function reducer(state: ProviderState, action: Action): ProviderState {
// settled the message on a trace without its card.
const session = state.sessions[action.key];
if (!session) return state;
+ //
+ // The compaction is deferred by one turn. The turn that just finished is
+ // the one the reader is most likely to open, and trading its events for
+ // a preview means the rows they were watching a second ago have to come
+ // back from the server: the reasoning vanishes from the trace, the fetch
+ // lands, and the whole block jumps. Keeping the newest turn whole costs
+ // one turn's events and makes opening it instant; the turn before it is
+ // compacted now instead, which is what bounds the memory.
let changed = false;
const messages = session.messages.map((message) => {
- if (message.id !== action.messageId || message.role !== "assistant") {
- return message;
- }
+ const settleAction = traceSettleAction(message, action.messageId);
+ if (settleAction === "skip") return message;
changed = true;
+ if (settleAction === "keep") {
+ const settled = settleMessageTrace(
+ message.events ?? [],
+ action.turnId,
+ );
+ return {
+ ...message,
+ // Measured now, over the full stream, exactly as before — only the
+ // events are kept. ``truncated`` describes the preview that was
+ // not taken, so leaving it set would send the reader on a fetch
+ // for rows already in hand.
+ trace: { ...settled.trace, truncated: false },
+ };
+ }
return {
...message,
- ...settleMessageTrace(message.events ?? [], action.turnId),
+ ...settleMessageTrace(
+ message.events ?? [],
+ message.trace?.turn_id ?? "",
+ ),
};
});
if (!changed) return state;
@@ -1881,6 +1906,15 @@ export function ChatStateAdapterProvider({
(item) => item.id === messageId && item.role === "assistant",
);
if (!message?.trace?.turn_id) return;
+ // Already holding the whole thing — the turn that just finished keeps
+ // its events. Fetching would replace them with an identical list and
+ // repaint the trace for nothing.
+ if (
+ !message.trace.truncated &&
+ (message.events?.length ?? 0) >= (message.trace.total ?? 0)
+ ) {
+ return;
+ }
const controller = new AbortController();
traceRequestsRef.current.set(key, controller);
@@ -1906,6 +1940,16 @@ export function ChatStateAdapterProvider({
total: page.total,
last_seq: page.last_seq,
truncated: false,
+ // The turn's span is measured over the whole stream and the trace
+ // pages do not carry it, so dropping it here left the duration to be
+ // re-derived from whatever events came back — and a turn that read
+ // "11s" while collapsed read "12s" the moment it was opened.
+ ...(typeof message.trace.started_at === "number"
+ ? { started_at: message.trace.started_at }
+ : {}),
+ ...(typeof message.trace.ended_at === "number"
+ ? { ended_at: message.trace.ended_at }
+ : {}),
};
const preview = compactTracePreview(message.events ?? []);
const evicted = traceCacheRef.current.retain(key, {
diff --git a/web/features/chat/trace/memory.ts b/web/features/chat/trace/memory.ts
index ade9a3227..66837b8ab 100644
--- a/web/features/chat/trace/memory.ts
+++ b/web/features/chat/trace/memory.ts
@@ -217,6 +217,37 @@ export function settleMessageTrace(
};
}
+/**
+ * What settling a turn means for one message in the session.
+ *
+ * The compaction is deferred by one turn. The turn that just finished is the
+ * one a reader is most likely to open, and trading its events for a preview
+ * means the rows they were watching a second ago have to come back from the
+ * server — the reasoning disappears from the trace, the fetch lands, and the
+ * block jumps. Keeping the newest turn whole costs one turn's events; the turn
+ * before it is compacted instead, which is what bounds the memory.
+ */
+export type TraceSettleAction = "keep" | "compact" | "skip";
+
+export function traceSettleAction(
+ message: {
+ id?: number;
+ role: string;
+ events?: StreamEvent[];
+ trace?: MessageTraceMetadata;
+ },
+ settledMessageId: number,
+): TraceSettleAction {
+ if (message.role !== "assistant") return "skip";
+ if (message.id === settledMessageId) return "keep";
+ // An older turn is due for compaction only while it is still holding every
+ // event it streamed. ``total`` counts the full stream, so a message whose
+ // list is shorter has already been previewed — or was loaded as one.
+ const total = message.trace?.total ?? 0;
+ if (!message.trace?.turn_id || !total) return "skip";
+ return (message.events?.length ?? 0) >= total ? "compact" : "skip";
+}
+
export interface TraceSnapshot {
events: StreamEvent[];
metadata?: MessageTraceMetadata;
diff --git a/web/tests/trace-memory.test.ts b/web/tests/trace-memory.test.ts
index 5eb355647..4422a8061 100644
--- a/web/tests/trace-memory.test.ts
+++ b/web/tests/trace-memory.test.ts
@@ -7,6 +7,7 @@ import {
TraceCache,
compactTracePreview,
settleMessageTrace,
+ traceSettleAction,
} from "../features/chat/trace/memory";
function event(
@@ -175,3 +176,54 @@ test("settling a message keeps its card and stamps where the answer was cut", ()
ended_at: 1,
});
});
+
+/* ------------------------------------------------------------------ */
+/* Deferred compaction */
+/* ------------------------------------------------------------------ */
+
+const assistant = (
+ id: number,
+ events: StreamEvent[],
+ trace?: Record<string, unknown>,
+) => ({ id, role: "assistant", events, ...(trace ? { trace } : {}) });
+
+test("the turn that just finished keeps the events it streamed", () => {
+ // Trading them for a preview here is what made opening a just-finished
+ // trace blank out its reasoning, hitch on a fetch, and then repaint.
+ assert.equal(
+ traceSettleAction(assistant(7, [event("thinking", "…")]), 7),
+ "keep",
+ );
+});
+
+test("the turn before it is the one compacted instead", () => {
+ // Still holding everything it streamed (events.length >= total), and no
+ // longer the turn being looked at.
+ assert.equal(
+ traceSettleAction(
+ assistant(5, [event("thinking", "…"), event("done")], {
+ turn_id: "t5",
+ total: 2,
+ }),
+ 7,
+ ),
+ "compact",
+ );
+});
+
+test("a turn already down to its preview is left alone", () => {
+ // Its list is shorter than the stream it came from, so there is nothing
+ // left to compact and re-settling would only churn the message.
+ assert.equal(
+ traceSettleAction(assistant(5, [event("done")], { turn_id: "t5", total: 9 }), 7),
+ "skip",
+ );
+});
+
+test("nothing is compacted on the strength of a message with no turn", () => {
+ assert.equal(traceSettleAction(assistant(5, [event("done")]), 7), "skip");
+ assert.equal(
+ traceSettleAction({ id: 6, role: "user", events: [] }, 7),
+ "skip",
+ );
+});
diff --git a/web/tests/trace-timing.test.ts b/web/tests/trace-timing.test.ts
index 5b9ba90a9..d71bba0b4 100644
--- a/web/tests/trace-timing.test.ts
+++ b/web/tests/trace-timing.test.ts
@@ -84,3 +84,38 @@ test("durations read as compact human time", () => {
assert.equal(formatTurnDuration(64), "1m 4s");
assert.equal(formatTurnDuration(3600), "1h");
});
+
+test("opening a trace does not move the number it was showing", () => {
+ // A collapsed turn is timed from its preview plus the span recorded over
+ // the whole stream; opening it swaps in every event the server holds. The
+ // label has to survive that, so the recorded span must travel with the
+ // fetched events — dropping it left the duration to be re-derived, and an
+ // 11s turn read 12s the moment it was opened.
+ const bounds = { started_at: 100, ended_at: 111.4 };
+ const preview = [event("tool_call", 104), event("done", 111)];
+ const full = [
+ event("stage_start", 100.2),
+ event("thinking", 101),
+ event("tool_call", 104),
+ event("thinking", 108),
+ event("done", 111),
+ ];
+
+ const collapsed = getTurnDurationSeconds(preview, 0, false, bounds);
+ const opened = getTurnDurationSeconds(full, 0, false, bounds);
+ assert.equal(collapsed, opened);
+ assert.equal(formatTurnDuration(collapsed ?? 0), "11s");
+ assert.equal(formatTurnDuration(opened ?? 0), "11s");
+});
+
+test("losing the recorded span is what made the number move", () => {
+ // Guards the reason rather than the symptom: with no bounds to anchor it,
+ // the same two event sets disagree. This is the state the fetch used to
+ // leave the message in.
+ const preview = [event("tool_call", 104), event("done", 111)];
+ const full = [event("stage_start", 100.2), event("done", 111)];
+ assert.notEqual(
+ getTurnDurationSeconds(preview, 0, false, null),
+ getTurnDurationSeconds(full, 0, false, null),
+ );
+});