Skip to content

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

fix(web): resolve optimistic edit refresh race (#753)

szzhoujiarui525a171e10a8
diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsx
index bd280086f..2f6ebecbe 100644
--- a/web/context/UnifiedChatContext.tsx
+++ b/web/context/UnifiedChatContext.tsx
@@ -30,7 +30,10 @@ import {
import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";
import { normalizeMessageContent } from "@/lib/message-content";
import { buildVisiblePath, tipMessageId } from "@/lib/message-branches";
-import { nextOptimisticId } from "@/lib/optimistic-id";
+import {
+ nextOptimisticId,
+ resolvePersistedMessage,
+} from "@/lib/optimistic-id";
import { reconcileTurnIds } from "@/lib/turn-reconcile";
import {
isNarrationMarker,
@@ -836,7 +839,7 @@ interface ChatContextValue {
loadSession: (
sessionId: string,
options?: { signal?: AbortSignal; revalidate?: boolean },
- ) => Promise<void>;
+ ) => Promise<MessageItem[] | undefined>;
/** Select an already-loaded session without fetching. Returns false when
* it isn't in memory, i.e. the caller must load it. */
showCachedSession: (sessionId: string) => boolean;
@@ -1006,9 +1009,9 @@ export function UnifiedChatProvider({
// Forward-declared so ``handleRunnerEvent`` (created above
// ``loadSession`` in source order) can trigger a server refresh after
// a turn finishes without taking a stale closure of ``loadSession``.
- const loadSessionRef = useRef<((sessionId: string) => Promise<void>) | null>(
- null,
- );
+ const loadSessionRef = useRef<
+ ((sessionId: string) => Promise<MessageItem[] | undefined>) | null
+ >(null);
useLayoutEffect(() => {
stateRef.current = state;
@@ -1338,12 +1341,13 @@ export function UnifiedChatProvider({
const local = stateRef.current.sessions[key];
if (!local || local.isStreaming || local.status === "running") return;
}
+ const messages = hydrateMessages(session.messages ?? []);
dispatch({
type: options?.revalidate ? "REVALIDATE_SESSION" : "LOAD_SESSION",
key,
sessionId: key,
title: session.title || "",
- messages: hydrateMessages(session.messages ?? []),
+ messages,
activeTurnId: activeTurn?.turn_id || activeTurn?.id || null,
status:
(session.status as SessionRuntimeStatus | undefined) ||
@@ -1378,6 +1382,7 @@ export function UnifiedChatProvider({
after_seq: 0,
});
}
+ return messages;
},
[hydrateMessages, sendThroughRunner],
);
@@ -1837,35 +1842,21 @@ export function UnifiedChatProvider({
// already running so we don't queue against an in-flight stream
// (matches the delete-turn guard).
if (session.isStreaming) return;
- const idx = session.messages.findIndex(
- (m) => m.id === messageId && m.role === "user",
- );
- if (idx === -1) return;
- let original = session.messages[idx];
- // Optimistic in-flight rows have a negative client-side id — we
- // need a real server id to hang the new sibling under. Refresh
- // from the server, then re-resolve the row by its position in the
- // (now-persisted) thread before continuing.
- if (typeof original.id === "number" && original.id < 0) {
- if (!session.sessionId) return;
- try {
- await loadSession(session.sessionId);
- } catch {
- return;
- }
- const refreshed = stateRef.current.sessions[key];
- const candidate = refreshed?.messages[idx];
- if (
- !candidate ||
- candidate.role !== "user" ||
- typeof candidate.id !== "number" ||
- candidate.id < 0
- ) {
- return;
- }
- original = candidate;
+ let original: MessageItem | undefined;
+ try {
+ original = await resolvePersistedMessage(
+ session.messages,
+ messageId,
+ "user",
+ async () =>
+ session.sessionId
+ ? await loadSession(session.sessionId)
+ : undefined,
+ );
+ } catch {
+ return;
}
- if (typeof original.id !== "number" || original.id < 0) return;
+ if (!original) return;
const parentId = original.parentMessageId ?? null;
sendMessage(
trimmed,
diff --git a/web/lib/optimistic-id.ts b/web/lib/optimistic-id.ts
index 87d68cb0c..5274231f6 100644
--- a/web/lib/optimistic-id.ts
+++ b/web/lib/optimistic-id.ts
@@ -25,3 +25,40 @@ export function nextOptimisticId(): number {
lastOptimisticId = stamp < lastOptimisticId ? stamp : lastOptimisticId - 1;
return lastOptimisticId;
}
+
+interface IdentifiedMessage {
+ id?: number;
+ role: string;
+}
+
+/**
+ * Resolve a message to its persisted row before a server-side mutation.
+ * The refresh result is used directly because React state refs are only
+ * updated after the reducer commit and can still contain the optimistic id.
+ */
+export async function resolvePersistedMessage<T extends IdentifiedMessage>(
+ messages: readonly T[],
+ messageId: number,
+ expectedRole: string,
+ refreshMessages: () => Promise<readonly T[] | undefined>,
+): Promise<T | undefined> {
+ const index = messages.findIndex(
+ (message) => message.id === messageId && message.role === expectedRole,
+ );
+ if (index === -1) return undefined;
+
+ const original = messages[index];
+ if (typeof original.id === "number" && original.id >= 0) return original;
+
+ const refreshed = await refreshMessages();
+ const candidate = refreshed?.[index];
+ if (
+ !candidate ||
+ candidate.role !== expectedRole ||
+ typeof candidate.id !== "number" ||
+ candidate.id < 0
+ ) {
+ return undefined;
+ }
+ return candidate;
+}
diff --git a/web/tests/optimistic-id.test.ts b/web/tests/optimistic-id.test.ts
index fe542e8b6..6c2b105dd 100644
--- a/web/tests/optimistic-id.test.ts
+++ b/web/tests/optimistic-id.test.ts
@@ -1,6 +1,9 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { nextOptimisticId } from "../lib/optimistic-id";
+import {
+ nextOptimisticId,
+ resolvePersistedMessage,
+} from "../lib/optimistic-id";
import { reconcileTurnIds } from "../lib/turn-reconcile";
import { buildVisiblePath, tipMessageId } from "../lib/message-branches";
import type { MessageItem } from "../context/UnifiedChatContext";
@@ -17,6 +20,28 @@ test("optimistic ids are negative and strictly decreasing", () => {
assert.equal(new Set(ids).size, ids.length, "ids must be unique");
});
+// Issue #739: loadSession dispatches the persisted snapshot, but stateRef is
+// only updated after React commits. The first edit must use the snapshot that
+// loadSession just returned instead of immediately reading the stale ref.
+test("an optimistic message resolves from the returned refresh snapshot", async () => {
+ const optimistic = [
+ { id: -100, role: "user", content: "question", parentMessageId: 10 },
+ ];
+ const persisted = [
+ { id: 11, role: "user", content: "question", parentMessageId: 10 },
+ ];
+
+ const resolved = await resolvePersistedMessage(
+ optimistic,
+ -100,
+ "user",
+ async () => persisted,
+ );
+
+ assert.equal(resolved?.id, 11);
+ assert.equal(optimistic[0].id, -100, "the state ref can still be stale");
+});
+
// Issue #698: the user row and the assistant placeholder are minted
// back-to-back (ADD_USER_MSG then STREAM_START). When they shared an id, the
// remap in reconcileTurnIds collapsed both onto the user's persisted id, so