DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(web): preserve failed chat submissions across retries and storage races
Bingxi Zhao (Frank)348176291e54
diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex 3bb37970a..c3077d9c9 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -3,6 +3,7 @@import { activeWorkspaceId } from "@/lib/workspace-scope";import {clearFailedSubmission,+ moveFailedSubmissions,readFailedSubmissions,serverContainsFailedSubmission,storeFailedSubmission,@@ -212,6 +213,8 @@ export interface ChatState {submissionFailed: boolean;/** The text was recovered without its attachments or other request context. */submissionNeedsReview: boolean;+ /** No browser storage accepted even the text. Copy before leaving this tab. */+ submissionNotSaved: boolean;}export interface SessionConfiguration {@@ -266,6 +269,9 @@ export interface MessageRequestSnapshot {content: string;capability?: string | null;workspaceMode?: WorkspaceMode | null;+ workspaceId?: string | null;+ courseId?: string | null;+ replyLanguageOverride?: string | null;enabledTools: string[];knowledgeBases: string[];language: string;@@ -288,6 +294,9 @@ export interface MessageRequestSnapshot {readingMaterialRevision?: number;/** The passage the question was asked about, and the unit it came from. */readingSelection?: ReadingSelectionSnapshot;+ /** Complete wire context captured at first send for deterministic retry. */+ readingTurnFields?: ReturnType<typeof readingTurnFields>;+ watchingTurnFields?: ReturnType<typeof watchingTurnFields>;/** `capability` ran for this turn only (see SendMessageOptions.capability). */capabilityOnce?: boolean;}@@ -315,6 +324,7 @@ export interface MessageItem {* "unsent" marker; its requestSnapshot drives the retry. */failedSubmission?: boolean;failedSubmissionNeedsReview?: boolean;+ failedSubmissionNotSaved?: boolean;failedSubmissionId?: string;}@@ -387,6 +397,7 @@ type Action =parentMessageId?: number | null;failedSubmissionId?: string;}+ | { type: "SET_SUBMISSION_PERSISTENCE"; key: string; submissionId: string; saved: boolean }| { type: "POP_LAST_ASSISTANT"; key: string }| { type: "RESTORE_ASSISTANT"; key: string; message: MessageItem }| { type: "STREAM_START"; key: string; startedAt: number }@@ -491,6 +502,7 @@ function createSessionEntry(lastTurnFailed: false,submissionFailed: false,submissionNeedsReview: false,+ submissionNotSaved: false,};}@@ -762,6 +774,23 @@ function reducer(state: ProviderState, action: Action): ProviderState {},};}+ case "SET_SUBMISSION_PERSISTENCE": {+ const session = state.sessions[action.key];+ if (!session) return state;+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [action.key]: {+ ...session,+ messages: session.messages.map((message) =>+ message.failedSubmissionId === action.submissionId+ ? { ...message, failedSubmissionNotSaved: !action.saved }+ : message),+ },+ },+ };+ }case "POP_LAST_ASSISTANT": {const session = state.sessions[action.key];if (!session || session.messages.length === 0) return state;@@ -1388,15 +1417,18 @@ function reducer(state: ProviderState, action: Action): ProviderState {},};}- // Idempotent variant of NEW_SESSION: guarantees there is *a* selected- // session without discarding one a page already selected and configured.- // The check belongs here rather than in the caller because a mount effect- // only ever sees the state of the render that created it, which is stale- // the moment anything else has dispatched.+ // A chat page's child effect can create and configure a draft before this+ // provider's mount effect runs. Hydrate that empty draft in place; never+ // replace its configuration or a URL-selected server session. Repeated+ // mount effects are harmless once the failed rows have been attached.case "ENSURE_DRAFT_SESSION": {- if (state.selectedKey && state.sessions[state.selectedKey]) return state;- const fresh = selectFreshDraft(state, action.key);- if (!action.failedRecords?.length) return fresh;+ const fresh = state.selectedKey && state.sessions[state.selectedKey]+ ? state+ : selectFreshDraft(state, action.key);+ const selectedKey = fresh.selectedKey;+ if (!selectedKey || !action.failedRecords?.length) return fresh;+ const selected = fresh.sessions[selectedKey];+ if (selected.sessionId || selected.messages.length) return fresh;const messages: MessageItem[] = [];for (const record of action.failedRecords) {messages.push(restoredFailedMessage(record, messages.at(-1)?.id ?? null));@@ -1405,8 +1437,8 @@ function reducer(state: ProviderState, action: Action): ProviderState {...fresh,sessions: {...fresh.sessions,- [action.key]: {- ...fresh.sessions[action.key],+ [selectedKey]: {+ ...selected,messages,status: "failed",},@@ -1758,7 +1790,7 @@ export function ChatStateAdapterProvider({const pendingRegenerateRef = useRef<Map<string, MessageItem>>(new Map());const pendingResendRef = useRef<Map<string, MessageItem>>(new Map());const pendingSubmissionIdsRef = useRef<- Map<string, { storageKey: string; submissionId: string }>+ Map<string, { storageKey: string; sourceStorageKey?: string; submissionId: string; visibleSubmissionIds: string[] }>>(new Map());const resolvingResendRef = useRef<Set<string>>(new Set());const traceCacheRef = useRef<TraceCache>(new TraceCache());@@ -1889,9 +1921,29 @@ export function ChatStateAdapterProvider({null;if (sessionId) {const pendingSubmission = pendingSubmissionIdsRef.current.get(effectiveKey);+ const draftSession = stateRef.current.sessions[effectiveKey];+ const movedIds = pendingSubmission && !draftSession?.sessionId+ ? moveFailedSubmissions(+ pendingSubmission.storageKey,+ sessionId,+ pendingSubmission.visibleSubmissionIds,+ )+ : [];+ if (pendingSubmission && !draftSession?.sessionId &&+ movedIds.length < new Set(pendingSubmission.visibleSubmissionIds).size) {+ notify(i18n.t(+ "Some unsent messages could not be moved into this conversation. Open a new chat to recover them.",+ ), { tone: "error", durationMs: 10_000 });+ }if (pendingSubmission) {pendingSubmissionIdsRef.current.delete(effectiveKey);- pendingSubmissionIdsRef.current.set(sessionId, pendingSubmission);+ pendingSubmissionIdsRef.current.set(sessionId, movedIds.includes(pendingSubmission.submissionId)+ ? {+ ...pendingSubmission,+ sourceStorageKey: pendingSubmission.storageKey,+ storageKey: sessionId,+ }+ : pendingSubmission);}dispatch({type: "BIND_SERVER_SESSION",@@ -1961,6 +2013,9 @@ export function ChatStateAdapterProvider({} | undefined)?.user_message_id;if (pendingSubmission && doneUserMessageId != null) {clearFailedSubmission(pendingSubmission.storageKey, pendingSubmission.submissionId);+ if (pendingSubmission.sourceStorageKey) {+ clearFailedSubmission(pendingSubmission.sourceStorageKey, pendingSubmission.submissionId);+ }}pendingSubmissionIdsRef.current.delete(effectiveKey);dispatch({@@ -2609,7 +2664,9 @@ export function ChatStateAdapterProvider({}const session = currentState.sessions[key] ?? createSessionEntry(key);const replaySnapshot = options?.requestSnapshotOverride;+ const exactReplay = Boolean(options?.retrySubmissionId && replaySnapshot);const effectiveCapability =+ exactReplay ? (replaySnapshot?.capability ?? null) :replaySnapshot?.capability ??options?.capability ??session.activeCapability;@@ -2617,18 +2674,22 @@ export function ChatStateAdapterProvider({? replaySnapshot.capabilityOnce === true: Boolean(options?.capability);const effectiveWorkspaceMode =+ exactReplay ? (replaySnapshot?.workspaceMode ?? null) :replaySnapshot?.workspaceMode ?? session.workspaceMode;const effectiveTools =replaySnapshot?.enabledTools ?? session.enabledTools;const effectiveKnowledgeBases =replaySnapshot?.knowledgeBases ?? session.knowledgeBases;const effectiveLLMSelection =+ exactReplay ? (replaySnapshot?.llmSelection ?? null) :replaySnapshot && "llmSelection" in replaySnapshot? (replaySnapshot.llmSelection ?? null): session.llmSelection;const effectiveMasteryPathId =+ exactReplay ? (replaySnapshot?.masteryPathId ?? null) :replaySnapshot?.masteryPathId ?? session.masteryPathId;const effectiveMasterySessionMode =+ exactReplay ? (replaySnapshot?.masterySessionMode ?? null) :replaySnapshot?.masterySessionMode ?? session.masterySessionMode;const effectiveLanguage =replaySnapshot?.language ??@@ -2638,15 +2699,20 @@ export function ChatStateAdapterProvider({// persona (quiz follow-up surface); then the session-level preference.// Always a string — "" means Default / no persona.const effectivePersona =+ exactReplay ? (replaySnapshot?.persona ?? "") :replaySnapshot?.persona ?? persona ?? session.personaSelection ?? "";// Replays retain the original resource selection, including one-turn choices.const effectiveResources =+ exactReplay ? (replaySnapshot?.resourceSelection ?? emptyResourceSelection()) :replaySnapshot?.resourceSelection ?? session.resourceSelection ?? emptyResourceSelection();const effectiveMemoryReferences =+ exactReplay ? replaySnapshot?.memoryReferences :replaySnapshot?.memoryReferences ?? memoryReferences;const effectiveBookReferences =+ exactReplay ? replaySnapshot?.bookReferences :replaySnapshot?.bookReferences ?? options?.bookReferences;const effectiveReadingReferences =+ exactReplay ? replaySnapshot?.readingReferences :replaySnapshot?.readingReferences ?? options?.readingReferences;const effectiveAttachments =replaySnapshot?.attachments?.map((a) => ({@@ -2655,18 +2721,34 @@ export function ChatStateAdapterProvider({base64: a.base64,url: a.url,mime_type: a.mime_type,- })) ?? msgAttachments;- const effectiveConfig = config ?? replaySnapshot?.config;+ })) ?? (exactReplay ? undefined : msgAttachments);+ const effectiveConfig = exactReplay ? replaySnapshot?.config : config ?? replaySnapshot?.config;const effectiveNotebookReferences =+ exactReplay ? replaySnapshot?.notebookReferences :replaySnapshot?.notebookReferences ?? notebookReferences;const effectiveHistoryReferences =+ exactReplay ? replaySnapshot?.historyReferences :replaySnapshot?.historyReferences ?? historyReferences;const effectiveQuestionNotebookReferences =+ exactReplay ? replaySnapshot?.questionNotebookReferences :replaySnapshot?.questionNotebookReferences ??questionNotebookReferences;- const liveReadingFields = readingTurnFields(effectiveWorkspaceMode);+ const liveReadingFields = exactReplay ? {} : readingTurnFields(effectiveWorkspaceMode);const replaySelection = replaySnapshot?.readingSelection;- const effectiveReadingTurnFields = replaySnapshot?.readingMaterialId+ const effectiveReadingTurnFields = exactReplay+ ? (replaySnapshot?.readingTurnFields ?? (replaySnapshot?.readingMaterialId+ ? {+ reading_material_id: replaySnapshot.readingMaterialId,+ ...(replaySnapshot.readingMaterialRevision+ ? { reading_material_revision: replaySnapshot.readingMaterialRevision }+ : {}),+ ...(replaySelection+ ? { reading_viewport: { selection: replaySelection.quote,+ locator: replaySelection.locator } }+ : {}),+ }+ : {}))+ : replaySnapshot?.readingMaterialId? {reading_material_id: replaySnapshot.readingMaterialId,...(replaySnapshot.readingMaterialRevision@@ -2702,8 +2784,12 @@ export function ChatStateAdapterProvider({effectiveReadingTurnFields.reading_material_id;const effectiveReadingMaterialRevision =effectiveReadingTurnFields.reading_material_revision;- const liveWatchingFields = watchingTurnFields(effectiveCapability);- const effectiveWatchingTurnFields = replaySnapshot?.timedMediaId+ const liveWatchingFields = exactReplay ? {} : watchingTurnFields(effectiveCapability);+ const effectiveWatchingTurnFields = exactReplay+ ? (replaySnapshot?.watchingTurnFields ?? (replaySnapshot?.timedMediaId+ ? { timed_media_id: replaySnapshot.timedMediaId }+ : {}))+ : replaySnapshot?.timedMediaId? { timed_media_id: replaySnapshot.timedMediaId }: liveWatchingFields;const effectiveTimedMediaId =@@ -2713,6 +2799,9 @@ export function ChatStateAdapterProvider({content,capability: effectiveCapability,workspaceMode: effectiveWorkspaceMode,+ workspaceId: session.workspaceId ?? null,+ courseId: session.courseId.trim() || null,+ replyLanguageOverride: session.replyLanguageOverride ?? null,enabledTools: [...effectiveTools],knowledgeBases: [...effectiveKnowledgeBases],language: effectiveLanguage,@@ -2763,10 +2852,16 @@ export function ChatStateAdapterProvider({...(effectiveReadingSelection? { readingSelection: effectiveReadingSelection }: {}),+ ...(Object.keys(effectiveReadingTurnFields).length+ ? { readingTurnFields: effectiveReadingTurnFields }+ : {}),...(capabilityOnce ? { capabilityOnce: true } : {}),...(effectiveTimedMediaId? { timedMediaId: effectiveTimedMediaId }: {}),+ ...(Object.keys(effectiveWatchingTurnFields).length+ ? { watchingTurnFields: effectiveWatchingTurnFields }+ : {}),};// Default the new message's parent to the tip of the currently-// visible path so the local chat tree stays connected during@@ -2796,6 +2891,8 @@ export function ChatStateAdapterProvider({content.trim() !== "";const submissionId = options?.retrySubmissionId ??(trackNewSubmission ? randomUuid() : undefined);+ const persistSubmission = Boolean(submissionId) &&+ (trackNewSubmission || Boolean(options?.retrySubmissionId));if (options?.displayUserMessage !== false) {dispatch({type: "ADD_USER_MSG",@@ -2828,18 +2925,33 @@ export function ChatStateAdapterProvider({// Persist before attempting the socket, including a first turn that// has no server session yet. Replays reuse their original identity.const submissionStorageKey = session.sessionId ?? draftFailedSubmissionKey();- if (trackNewSubmission && submissionId) {- storeFailedSubmission(submissionStorageKey, {+ if (persistSubmission && submissionId) {+ const saved = storeFailedSubmission(submissionStorageKey, {content,capability: effectiveCapability,requestSnapshot,submissionId,});+ dispatch({+ type: "SET_SUBMISSION_PERSISTENCE", key, submissionId,+ saved: saved !== null,+ });+ if (!saved) {+ notify(i18n.t(+ "This unsent message could not be saved in your browser. Copy it before leaving this page.",+ ), { tone: "error", durationMs: 10_000 });+ }}if (submissionId) {pendingSubmissionIdsRef.current.set(key, {storageKey: submissionStorageKey,submissionId,+ visibleSubmissionIds: [+ ...session.messages+ .map((message) => message.failedSubmissionId)+ .filter((id): id is string => Boolean(id)),+ submissionId,+ ],});}return sendThroughRunner(@@ -2855,8 +2967,14 @@ export function ChatStateAdapterProvider({mcp: effectiveResources.mcp,sessionId: session.sessionId,// Existing sessions inherit server ownership; new drafts declare it once.- ...(!session.sessionId ? { workspaceId: session.workspaceId ?? null } : {}),- courseId: session.courseId.trim() || null,+ ...(!session.sessionId ? {+ workspaceId: exactReplay+ ? (replaySnapshot?.workspaceId ?? null)+ : (session.workspaceId ?? null),+ } : {}),+ courseId: exactReplay+ ? (replaySnapshot?.courseId ?? null)+ : (session.courseId.trim() || null),persistUserMessage,followupQuestionContext:followupQuestionContext && typeof followupQuestionContext === "object"@@ -2878,8 +2996,12 @@ export function ChatStateAdapterProvider({language: effectiveLanguage,// A draft has no session to PATCH yet. Persist its selector with the// first turn; existing sessions use their server-side preference.- ...(!session.sessionId && session.replyLanguageOverride- ? { replyLanguageOverride: session.replyLanguageOverride }+ ...(!session.sessionId && (exactReplay+ ? replaySnapshot?.replyLanguageOverride+ : session.replyLanguageOverride)+ ? { replyLanguageOverride: exactReplay+ ? replaySnapshot?.replyLanguageOverride+ : session.replyLanguageOverride }: {}),notebookReferences: effectiveNotebookReferences,historyReferences: effectiveHistoryReferences,@@ -2942,14 +3064,17 @@ export function ChatStateAdapterProvider({runnersRef.current.delete(key);}if (session.isStreaming) {- // The user aborted on purpose — do not resurrect this submission as- // "unsent" after the next reload (#1594).+ // Stop is not proof that the server accepted the user row. In+ // particular, before a turn ID exists another tab may have stored a+ // newer attempt with this same logical submission ID. Keep the record+ // until a server transcript or DONE proves acceptance.const pendingSubmission = pendingSubmissionIdsRef.current.get(key);- if (pendingSubmission) {- clearFailedSubmission(pendingSubmission.storageKey, pendingSubmission.submissionId);- pendingSubmissionIdsRef.current.delete(key);- }- dispatch({ type: "STREAM_END", key, status: "cancelled" });+ if (pendingSubmission) pendingSubmissionIdsRef.current.delete(key);+ dispatch({+ type: "STREAM_END", key,+ status: pendingSubmission && !turnId ? "failed" : "cancelled",+ submissionFailed: Boolean(pendingSubmission && !turnId),+ });}}, []);@@ -3204,6 +3329,10 @@ export function ChatStateAdapterProvider({const tail = current.messages[current.messages.length - 1];return tail?.role === "user" && tail.failedSubmissionNeedsReview === true;})(),+ submissionNotSaved: (() => {+ const tail = current.messages[current.messages.length - 1];+ return tail?.role === "user" && tail.failedSubmissionNotSaved === true;+ })(),};}, [state]);@@ -3312,6 +3441,13 @@ export function ChatStateAdapterProvider({(configuration?: SessionConfiguration) => {const key = makeDraftKey();dispatch({ type: "NEW_SESSION", key, configuration });+ // The provider stays mounted while /chat pages come and go. Restore+ // unsent first turns every time a page creates a fresh draft, too.+ dispatch({+ type: "ENSURE_DRAFT_SESSION",+ key,+ failedRecords: readFailedSubmissions(draftFailedSubmissionKey()),+ });return key;},[makeDraftKey],diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 7fd703622..b0bfa0ece 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -2697,7 +2697,9 @@ export default function ChatWorkspace({aria-hidden="true"/><span className="min-w-0 flex-1 text-[12px] leading-[1.5] text-[var(--foreground)]">- {state.submissionNeedsReview+ {state.submissionNotSaved+ ? t("This unsent message could not be saved in your browser. Copy it before leaving this page.")+ : state.submissionNeedsReview? t("Message text was saved, but its attachments or settings could not be restored. Copy it and send again."): t("Couldn't reach the server. Please check your connection and retry.")}</span>diff --git a/web/lib/chat-resend.ts b/web/lib/chat-resend.tsindex 49bb46c8f..860d505ab 100644--- a/web/lib/chat-resend.ts+++ b/web/lib/chat-resend.ts@@ -33,6 +33,7 @@ export function isFailedTurnVisible<T extends ChatBranchMessage>(interface LocalMessage {id?: MessageId;parentMessageId?: MessageId | null;+ failedSubmissionId?: string;}interface RemoteMessage {@@ -40,6 +41,7 @@ interface RemoteMessage {role: "user" | "assistant" | "system";content: string;parent_message_id?: MessageId | null;+ metadata?: { client_submission_id?: unknown };}interface RemoteSession {@@ -83,6 +85,25 @@ export function decideFailedTurnReplay(: { kind: "regenerate" };}+ if (lastUser.failedSubmissionId) {+ const rows = remote.messages ?? [];+ const ownRowIndex = rows.findIndex(+ (message) => message.role === "user" &&+ message.metadata?.client_submission_id === lastUser.failedSubmissionId,+ );+ if (ownRowIndex < 0) return { kind: "resend" };+ const ownRow = rows[ownRowIndex];+ // Regenerate operates on the server's latest user turn. Another tab may+ // have submitted a newer turn after this one's row was persisted.+ if (rows.slice(ownRowIndex + 1).some((message) => message.role === "user")) {+ return { kind: "refresh" };+ }+ return ["failed", "rejected", "cancelled"].includes(remote.status ?? "") &&+ sameParent(ownRow.parent_message_id, lastUser.parentMessageId)+ ? { kind: "reconcile_regenerate", userId: ownRow.id }+ : { kind: "refresh" };+ }+const persistedUser = [...newRows].reverse().find((message) => message.role === "user");if (persistedUser) {return ["failed", "rejected", "cancelled"].includes(remote.status ?? "") &&diff --git a/web/lib/failed-submissions.ts b/web/lib/failed-submissions.tsindex 6dddaf89c..729038592 100644--- a/web/lib/failed-submissions.ts+++ b/web/lib/failed-submissions.ts@@ -13,16 +13,46 @@ export interface FailedSubmissionRecord {savedAt: number;/** Also sent to the server and stored on its user row. */submissionId?: string;- /** Legacy records had only a same-text baseline, which is not causal proof. */+ /** Present on records written by early versions of this feature. */priorMatchingUserIds?: string[];/** The text survived, but its request context could not be stored. */retryRequiresReview?: boolean;}-const STORAGE_KEY = "deeptutor.failedSubmissions";-const FALLBACK_KEY_PREFIX = `${STORAGE_KEY}.fallback.`;+const LEGACY_KEY = "deeptutor.failedSubmissions";+const LEGACY_FALLBACK_PREFIX = LEGACY_KEY + ".fallback.";+const RECORD_PREFIX = LEGACY_KEY + ".record.";+const TOMBSTONE_PREFIX = LEGACY_KEY + ".cleared.";+const BINDING_PREFIX = LEGACY_KEY + ".binding.";const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;+function recordKey(sessionId: string, submissionId: string): string {+ return RECORD_PREFIX + encodeURIComponent(sessionId) + ":" ++ encodeURIComponent(submissionId);+}++function recordPrefix(sessionId: string): string {+ return RECORD_PREFIX + encodeURIComponent(sessionId) + ":";+}++function tombstoneKey(sessionId: string, submissionId: string): string {+ return TOMBSTONE_PREFIX + encodeURIComponent(sessionId) + ":" ++ encodeURIComponent(submissionId);+}++function tombstonePrefix(sessionId: string): string {+ return TOMBSTONE_PREFIX + encodeURIComponent(sessionId) + ":";+}++function bindingKey(sessionId: string, submissionId: string): string {+ return BINDING_PREFIX + encodeURIComponent(sessionId) + ":" ++ encodeURIComponent(submissionId);+}++function bindingPrefix(sessionId: string): string {+ return BINDING_PREFIX + encodeURIComponent(sessionId) + ":";+}+function isRecord(value: unknown): value is FailedSubmissionRecord {if (!value || typeof value !== "object") return false;const record = value as Partial<FailedSubmissionRecord>;@@ -32,45 +62,78 @@ function isRecord(value: unknown): value is FailedSubmissionRecord {typeof record.savedAt === "number";}-function asRecords(value: unknown): FailedSubmissionRecord[] {- // Accept the single-record shape used before this fix.+function asLegacyRecords(value: unknown): FailedSubmissionRecord[] {const records = isRecord(value) ? [value] :(Array.isArray(value) ? value.filter(isRecord) : []);- // A pre-ID record has no causal server identity. Preserve its text and- // require review before resend rather than matching another tab's row.+ // Records written before client_submission_id cannot be matched safely to+ // server rows. Keep their text, but require review before an automatic retry.return records.map((record) => record.submissionId? record- : { ...record, submissionId: `legacy:${record.savedAt}`, retryRequiresReview: true });+ : { ...record, submissionId: "legacy:" + record.savedAt, retryRequiresReview: true });}-function readAll(): Record<string, FailedSubmissionRecord[]> {- if (typeof window === "undefined") return {};+function legacyRecords(sessionId: string): FailedSubmissionRecord[] {try {- const raw = browserStorage.readRaw("local", STORAGE_KEY);- const parsed: unknown = raw ? JSON.parse(raw) : {};- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};- const out: Record<string, FailedSubmissionRecord[]> = {};- for (const [sessionId, value] of Object.entries(parsed)) {- const records = asRecords(value);- if (sessionId && records.length) out[sessionId] = records;+ const raw = browserStorage.readRaw("local", LEGACY_KEY);+ const parsed: unknown = raw ? JSON.parse(raw) : null;+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];+ return asLegacyRecords((parsed as Record<string, unknown>)[sessionId]);+ } catch {+ return [];+ }+}++function legacyRecordsForSession(sessionId: string): FailedSubmissionRecord[] {+ try {+ const raw = browserStorage.readRaw(+ "session", LEGACY_FALLBACK_PREFIX + encodeURIComponent(sessionId),+ );+ if (raw) {+ const parsed: unknown = JSON.parse(raw);+ // The old fallback, including an empty-array tombstone, took priority+ // over the shared map when the map could not be rewritten.+ if (isRecord(parsed) || Array.isArray(parsed)) return asLegacyRecords(parsed);}- return out;} catch {- return {};+ // A malformed or unavailable fallback cannot hide the local map.}+ return legacyRecords(sessionId);}-function fallbackKey(sessionId: string): string {- return `${FALLBACK_KEY_PREFIX}${encodeURIComponent(sessionId)}`;+function storedRecords(scope: "local" | "session", sessionId: string): FailedSubmissionRecord[] {+ return browserStorage.listRaw(scope, recordPrefix(sessionId)).flatMap(([key, raw]) => {+ try {+ const parsed: unknown = JSON.parse(raw);+ if (!isRecord(parsed) || !parsed.submissionId ||+ key !== recordKey(sessionId, parsed.submissionId)) return [];+ return [parsed];+ } catch {+ return [];+ }+ });}-function writeAll(records: Record<string, FailedSubmissionRecord[]>): boolean {- if (typeof window === "undefined") return false;- return browserStorage.writeRaw("local", STORAGE_KEY, JSON.stringify(records));+function clearedIds(sessionId: string): Map<string, number> {+ const ids = new Map<string, number>();+ for (const scope of ["local", "session"] as const) {+ for (const [key, raw] of browserStorage.listRaw(scope, tombstonePrefix(sessionId))) {+ const savedAt = Number(raw);+ if (!Number.isFinite(savedAt) || Date.now() - savedAt > MAX_AGE_MS) {+ browserStorage.removeRaw(scope, key);+ continue;+ }+ try {+ const id = decodeURIComponent(key.slice(tombstonePrefix(sessionId).length));+ ids.set(id, Math.max(ids.get(id) ?? 0, savedAt));+ } catch {+ // A malformed key cannot hide a valid submission.+ }+ }+ }+ return ids;}-/** A matching server-issued submission ID is the only proof of acceptance.- * Another tab can submit the same text after this tab's last refresh. */+/** Only a matching server-side causal ID proves this submission was accepted. */export function serverContainsFailedSubmission(messages: readonly {id?: number | string;@@ -86,7 +149,124 @@ export function serverContainsFailedSubmission();}-/** Preserve every pending message in a session, including successive failures. */+function textOnlyRecord(record: FailedSubmissionRecord): FailedSubmissionRecord {+ const snapshot = record.requestSnapshot as Record<string, unknown> | null;+ return {+ ...record,+ requestSnapshot: {+ content: record.content,+ capability: record.capability,+ language: typeof snapshot?.language === "string" ? snapshot.language : "en",+ enabledTools: [],+ knowledgeBases: [],+ },+ retryRequiresReview: true,+ };+}++type PersistedAs = "local_full" | "local_text" | "session_full" | "session_text";++function pruneExpiredEntries(): void {+ const now = Date.now();+ for (const scope of ["local", "session"] as const) {+ for (const [key, raw] of browserStorage.listRaw(scope, RECORD_PREFIX)) {+ let savedAt = Number.NaN;+ try {+ const value: unknown = JSON.parse(raw);+ if (isRecord(value)) savedAt = value.savedAt;+ } catch { /* malformed entries cannot be recovered */ }+ if (!Number.isFinite(savedAt) || now - savedAt > MAX_AGE_MS) {+ if (browserStorage.readRaw(scope, key) === raw) browserStorage.removeRaw(scope, key);+ }+ }+ for (const [key, raw] of browserStorage.listRaw(scope, TOMBSTONE_PREFIX)) {+ const savedAt = Number(raw);+ if (!Number.isFinite(savedAt) || now - savedAt > MAX_AGE_MS) {+ if (browserStorage.readRaw(scope, key) === raw) browserStorage.removeRaw(scope, key);+ }+ }+ }+}++function persistRecord(sessionId: string, record: FailedSubmissionRecord): PersistedAs | null {+ if (!record.submissionId) return null;+ const key = recordKey(sessionId, record.submissionId);+ const full = JSON.stringify(record);+ if (browserStorage.writeRaw("local", key, full)) {+ browserStorage.removeRaw("session", key);+ return "local_full";+ }+ // A week-old attachment in a different conversation can consume the entire+ // quota even though it is no longer recoverable. Free old per-record keys+ // before weakening this snapshot or giving up persistence.+ pruneExpiredEntries();+ if (browserStorage.writeRaw("local", key, full)) {+ browserStorage.removeRaw("session", key);+ return "local_full";+ }+ // Each submission has its own key. A large attachment or a concurrent tab+ // can never overwrite a different pending message's local record.+ const sessionFull = browserStorage.writeRaw("session", key, full);+ const textOnly = JSON.stringify(textOnlyRecord(record));+ if (browserStorage.writeRaw("local", key, textOnly)) {+ // Retain the full same-tab copy if it fits, so retry can keep attachments+ // while other tabs can at least recover the text and review the context.+ return "local_text";+ }+ if (sessionFull) return "session_full";+ if (browserStorage.writeRaw("session", key, textOnly)) return "session_text";+ return null;+}++interface DraftBinding {+ sourceKey: string;+ submissionId: string;+ targetSessionId: string;+ savedAt: number;+}++function readBindings(targetSessionId?: string): DraftBinding[] {+ return browserStorage.listRaw(+ "session", targetSessionId ? bindingPrefix(targetSessionId) : BINDING_PREFIX,+ ).flatMap(([key, raw]) => {+ try {+ const value = JSON.parse(raw) as Partial<DraftBinding>;+ if (!value.sourceKey || !value.submissionId || !value.targetSessionId ||+ typeof value.savedAt !== "number" ||+ key !== bindingKey(value.targetSessionId, value.submissionId)) return [];+ if (Date.now() - value.savedAt > MAX_AGE_MS) {+ browserStorage.removeRaw("session", key);+ return [];+ }+ return [value as DraftBinding];+ } catch {+ browserStorage.removeRaw("session", key);+ return [];+ }+ });+}++function directRecords(sessionId: string): FailedSubmissionRecord[] {+ const cleared = clearedIds(sessionId);+ const byId = new Map<string, FailedSubmissionRecord>();+ for (const record of [+ ...legacyRecordsForSession(sessionId),+ ...storedRecords("local", sessionId),+ ...storedRecords("session", sessionId),+ ]) {+ if (!record.submissionId ||+ record.savedAt <= (cleared.get(record.submissionId) ?? 0)) continue;+ if (Date.now() - record.savedAt > MAX_AGE_MS) continue;+ const previous = byId.get(record.submissionId);+ if (!previous || record.savedAt > previous.savedAt ||+ (record.savedAt === previous.savedAt &&+ !record.retryRequiresReview && previous.retryRequiresReview)) {+ byId.set(record.submissionId, record);+ }+ }+ return [...byId.values()];+}+export function storeFailedSubmission(sessionId: string,submission: {@@ -99,79 +279,47 @@ export function storeFailedSubmission(): string | null {if (!sessionId || submission.content.trim() === "") return null;const submissionId = submission.submissionId ?? randomUuid();- const records = readAll();- const now = Date.now();- for (const [key, entries] of Object.entries(records)) {- const fresh = entries.filter((record) => now - record.savedAt <= MAX_AGE_MS);- if (fresh.length) records[key] = fresh;- else delete records[key];- }- const current = readFailedSubmissions(sessionId);- const next = current.filter((record) => record.submissionId !== submissionId);- next.push({+ const record: FailedSubmissionRecord = {content: submission.content,capability: submission.capability ?? "",requestSnapshot: submission.requestSnapshot,- savedAt: now,+ // A stale tab can retry after another tab cleared this ID. Advance past+ // that tombstone even if both actions happen in the same clock tick.+ savedAt: Math.max(+ Date.now(), (clearedIds(sessionId).get(submissionId) ?? 0) + 1,+ ),submissionId,priorMatchingUserIds: submission.priorMatchingUserIds ?? [],- });- records[sessionId] = next;- if (writeAll(records)) {- browserStorage.removeRaw("session", fallbackKey(sessionId));- return submissionId;- }- // Large attachments may exhaust one storage area. Keep the complete- // request in the other area before dropping to text-only snapshots.- if (browserStorage.writeRaw("session", fallbackKey(sessionId), JSON.stringify(next))) {- return submissionId;- }- const textOnly = next.map((record): FailedSubmissionRecord => {- const snapshot = record.requestSnapshot as Record<string, unknown> | null;- return {- ...record,- requestSnapshot: {- content: record.content,- capability: record.capability,- language: typeof snapshot?.language === "string" ? snapshot.language : "en",- enabledTools: [],- knowledgeBases: [],- },- retryRequiresReview: true,- };- });- if (browserStorage.writeRaw("session", fallbackKey(sessionId), JSON.stringify(textOnly))) {- return submissionId;- }- // sessionStorage may be disabled even when a small localStorage write fits.- records[sessionId] = textOnly;- if (writeAll(records)) {- browserStorage.removeRaw("session", fallbackKey(sessionId));- }- return submissionId;+ };+ return persistRecord(sessionId, record) ? submissionId : null;}+/** Read the union of shared local, this tab's fallback, and old formats. */export function readFailedSubmissions(sessionId: string): FailedSubmissionRecord[] {if (!sessionId) return [];- const fallbackRaw = browserStorage.readRaw("session", fallbackKey(sessionId));- let fallback: FailedSubmissionRecord[] = [];- let fallbackValid = false;- try {- const parsed: unknown = fallbackRaw ? JSON.parse(fallbackRaw) : null;- if (isRecord(parsed) || Array.isArray(parsed)) {- fallback = asRecords(parsed);- fallbackValid = true;+ const byId = new Map<string, FailedSubmissionRecord>();+ const bindings = readBindings();+ const boundAwayIds = new Set(+ bindings.filter((binding) => binding.sourceKey === sessionId)+ .map((binding) => binding.submissionId),+ );+ for (const record of directRecords(sessionId)) {+ if (record.submissionId && !boundAwayIds.has(record.submissionId)) {+ byId.set(record.submissionId, record);}- } catch {- // An invalid fallback cannot suppress valid local records.}- const records = fallbackValid ? fallback : (readAll()[sessionId] ?? []);- const fresh = records.filter((record) => Date.now() - record.savedAt <= MAX_AGE_MS);- if (fresh.length !== records.length) {- if (!fresh.length) clearFailedSubmission(sessionId);- else writeSessionRecords(sessionId, fresh);+ for (const binding of bindings.filter((item) => item.targetSessionId === sessionId)) {+ const record = directRecords(binding.sourceKey)+ .find((item) => item.submissionId === binding.submissionId);+ if (!record?.submissionId) continue;+ const previous = byId.get(record.submissionId);+ if (!previous || record.savedAt > previous.savedAt ||+ (record.savedAt === previous.savedAt &&+ !record.retryRequiresReview && previous.retryRequiresReview)) {+ byId.set(record.submissionId, record);+ }}- return fresh;+ return [...byId.values()].sort((left, right) => left.savedAt - right.savedAt);}/** Kept for callers interested in the most recent pending submission. */@@ -179,26 +327,63 @@ export function readFailedSubmission(sessionId: string): FailedSubmissionRecordreturn readFailedSubmissions(sessionId).at(-1) ?? null;}-function writeSessionRecords(sessionId: string, entries: FailedSubmissionRecord[]): void {- const records = readAll();- if (entries.length) records[sessionId] = entries;- else delete records[sessionId];- if (writeAll(records)) {- browserStorage.removeRaw("session", fallbackKey(sessionId));- } else {- // An empty array is a tombstone when a localStorage write cannot clear- // its old record; the fallback must take precedence over that old data.- browserStorage.writeRaw("session", fallbackKey(sessionId), JSON.stringify(entries));+/** A same-tab binding keeps the old durable draft visible in its server+ * session when a second full localStorage copy cannot fit. */+export function moveFailedSubmissions(+ sourceKey: string,+ sessionId: string,+ submissionIds: readonly string[],+): string[] {+ if (!sourceKey || !sessionId || sourceKey === sessionId || !submissionIds.length) return [];+ const ids = new Set(submissionIds);+ const visible: string[] = [];+ for (const record of readFailedSubmissions(sourceKey)) {+ if (!record.submissionId || !ids.has(record.submissionId)) continue;+ const persisted = persistRecord(sessionId, record);+ if (persisted === "local_full") {+ clearFailedSubmission(sourceKey, record.submissionId);+ } else {+ // Keep the source when the target is tab-scoped or text-only. A full+ // local source must survive closing this tab, and the binding lets this+ // tab recover it under the new server ID after refresh.+ const binding: DraftBinding = {+ sourceKey, submissionId: record.submissionId,+ targetSessionId: sessionId, savedAt: record.savedAt,+ };+ const bound = browserStorage.writeRaw(+ "session", bindingKey(sessionId, record.submissionId), JSON.stringify(binding),+ );+ if (!persisted && !bound) continue;+ }+ visible.push(record.submissionId);}+ return visible;}-/** Clear only the submission the server acknowledged; older failures remain. */+/** Remove one causal record without rewriting any other tab's pending data. */export function clearFailedSubmission(sessionId: string, submissionId?: string): void {if (!sessionId) return;if (!submissionId) {- writeSessionRecords(sessionId, []);+ for (const record of readFailedSubmissions(sessionId)) {+ if (record.submissionId) clearFailedSubmission(sessionId, record.submissionId);+ }return;}- const current = readFailedSubmissions(sessionId);- writeSessionRecords(sessionId, current.filter((record) => record.submissionId !== submissionId));+ const binding = readBindings(sessionId)+ .find((item) => item.submissionId === submissionId);+ if (binding && binding.sourceKey !== sessionId) {+ clearFailedSubmission(binding.sourceKey, submissionId);+ browserStorage.removeRaw("session", bindingKey(sessionId, submissionId));+ }+ const key = recordKey(sessionId, submissionId);+ const marker = tombstoneKey(sessionId, submissionId);+ const recordAt = directRecords(sessionId)+ .find((record) => record.submissionId === submissionId)?.savedAt ?? 0;+ const clearedAt = clearedIds(sessionId).get(submissionId) ?? 0;+ const markerAt = Math.max(Date.now(), recordAt + 1, clearedAt + 1);+ let marked = browserStorage.writeRaw("local", marker, String(markerAt));+ browserStorage.removeRaw("local", key);+ browserStorage.removeRaw("session", key);+ if (!marked) marked = browserStorage.writeRaw("local", marker, String(markerAt));+ if (!marked) browserStorage.writeRaw("session", marker, String(markerAt));}diff --git a/web/locales/de/app.json b/web/locales/de/app.jsonindex 076d575a6..dc13a3d61 100644--- a/web/locales/de/app.json+++ b/web/locales/de/app.json@@ -5232,5 +5232,7 @@"kanban.showArchived": "Archivierte anzeigen","kanban.showActive": "Aktive anzeigen","kanban.restore": "Wiederherstellen",- "kanban.emptyArchive": "Keine archivierten Aufgaben"+ "kanban.emptyArchive": "Keine archivierten Aufgaben",+ "This unsent message could not be saved in your browser. Copy it before leaving this page.": "Diese nicht gesendete Nachricht konnte nicht im Browser gespeichert werden. Kopiere sie, bevor du diese Seite verlässt.",+ "Some unsent messages could not be moved into this conversation. Open a new chat to recover them.": "Einige nicht gesendete Nachrichten konnten nicht in diese Unterhaltung übernommen werden. Öffne einen neuen Chat, um sie wiederherzustellen."}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 079229aae..b5fdcd656 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -5232,5 +5232,7 @@"kanban.showArchived": "Show archived","kanban.showActive": "Show active","kanban.restore": "Restore",- "kanban.emptyArchive": "No archived tasks"+ "kanban.emptyArchive": "No archived tasks",+ "This unsent message could not be saved in your browser. Copy it before leaving this page.": "This unsent message could not be saved in your browser. Copy it before leaving this page.",+ "Some unsent messages could not be moved into this conversation. Open a new chat to recover them.": "Some unsent messages could not be moved into this conversation. Open a new chat to recover them."}diff --git a/web/locales/fr/app.json b/web/locales/fr/app.jsonindex c36762ce3..98b3730aa 100644--- a/web/locales/fr/app.json+++ b/web/locales/fr/app.json@@ -5676,5 +5676,7 @@"kanban.showArchived": "Afficher les archives","kanban.showActive": "Afficher les tâches actives","kanban.restore": "Restaurer",- "kanban.emptyArchive": "Aucune tâche archivée"+ "kanban.emptyArchive": "Aucune tâche archivée",+ "This unsent message could not be saved in your browser. Copy it before leaving this page.": "Ce message non envoyé n’a pas pu être enregistré dans votre navigateur. Copiez-le avant de quitter cette page.",+ "Some unsent messages could not be moved into this conversation. Open a new chat to recover them.": "Certains messages non envoyés n’ont pas pu être transférés dans cette conversation. Ouvrez une nouvelle discussion pour les récupérer."}diff --git a/web/locales/uk/app.json b/web/locales/uk/app.jsonindex d013f20b2..7633102b2 100644--- a/web/locales/uk/app.json+++ b/web/locales/uk/app.json@@ -5248,5 +5248,7 @@"kanban.showArchived": "Показати архівні","kanban.showActive": "Показати активні","kanban.restore": "Відновити",- "kanban.emptyArchive": "Немає архівних завдань"+ "kanban.emptyArchive": "Немає архівних завдань",+ "This unsent message could not be saved in your browser. Copy it before leaving this page.": "Не вдалося зберегти це ненадіслане повідомлення у браузері. Скопіюйте його, перш ніж залишити цю сторінку.",+ "Some unsent messages could not be moved into this conversation. Open a new chat to recover them.": "Деякі ненадіслані повідомлення не вдалося перенести до цієї розмови. Відкрийте новий чат, щоб відновити їх."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex e2afd29ea..aee79cd7c 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -5232,5 +5232,7 @@"kanban.showArchived": "显示已归档","kanban.showActive": "显示未归档","kanban.restore": "恢复",- "kanban.emptyArchive": "没有已归档任务"+ "kanban.emptyArchive": "没有已归档任务",+ "This unsent message could not be saved in your browser. Copy it before leaving this page.": "这条未发送的消息无法保存到浏览器。离开此页面前请先复制。",+ "Some unsent messages could not be moved into this conversation. Open a new chat to recover them.": "部分未发送的消息无法转入此对话。请打开新对话找回。"}diff --git a/web/shared/storage/store.ts b/web/shared/storage/store.tsindex bcd3904c2..a3ab09436 100644--- a/web/shared/storage/store.ts+++ b/web/shared/storage/store.ts@@ -86,6 +86,25 @@ export class StorageStore {}}+ /** Snapshot raw entries by prefix without exposing Storage APIs to callers. */+ listRaw(scope: StorageScope, prefix: string): Array<[string, string]> {+ const storage = this.provider(scope);+ if (!storage) return [];+ try {+ const names: string[] = [];+ for (let index = 0; index < storage.length; index += 1) {+ const name = storage.key(index);+ if (name?.startsWith(prefix)) names.push(name);+ }+ return names.flatMap((name) => {+ const value = storage.getItem(name);+ return value === null ? [] : [[name, value] as [string, string]];+ });+ } catch {+ return [];+ }+ }+writeRaw(scope: StorageScope, name: string, value: string): boolean {try {const storage = this.provider(scope);@@ -147,8 +166,14 @@ export class StorageStore {export function createBrowserStorageStore(): StorageStore {if (typeof window === "undefined") return new StorageStore({});+ let local: StorageLike | undefined;+ let session: StorageLike | undefined;+ // A browser can deny one storage area at the property getter (for example+ // in a restricted iframe) while still allowing the other.+ try { local = window.localStorage; } catch { /* unavailable */ }+ try { session = window.sessionStorage; } catch { /* unavailable */ }return new StorageStore(- { local: window.localStorage, session: window.sessionStorage },+ { local, session },window as unknown as StorageEventTargetLike,);}@@ -174,6 +199,10 @@ class BrowserStorageStore extends StorageStore {return createBrowserStorageStore().readRaw(scope, name);}+ override listRaw(scope: StorageScope, prefix: string): Array<[string, string]> {+ return createBrowserStorageStore().listRaw(scope, prefix);+ }+override writeRaw(scope: StorageScope, name: string, value: string): boolean {return createBrowserStorageStore().writeRaw(scope, name, value);}diff --git a/web/tests/chat-failed-submission-recovery.spec.tsx b/web/tests/chat-failed-submission-recovery.spec.tsxindex 114b27711..fd6828c6a 100644--- a/web/tests/chat-failed-submission-recovery.spec.tsx+++ b/web/tests/chat-failed-submission-recovery.spec.tsx@@ -1,4 +1,5 @@import { act, fireEvent, render, screen } from "@testing-library/react";+import { StrictMode, useEffect, useState } from "react";import { afterEach, beforeEach, expect, it, vi } from "vitest";import {ChatStateAdapterProvider,@@ -6,6 +7,15 @@ import {} from "@/features/chat/ChatStateAdapter";import { initI18n } from "@/i18n/init";import {+ resetReadingTurnState, setReadingMaterial, setReadingViewport,+ setReadingWorkspace,+} from "@/lib/reading-turn-state";+import {+ resetWatchingTurnState, setWatchingMaterial, setWatchingViewport,+} from "@/lib/watching-turn-state";+import {+ clearFailedSubmission,+ moveFailedSubmissions,readFailedSubmission,readFailedSubmissions,storeFailedSubmission,@@ -117,19 +127,46 @@ function seedUnsentSubmission(content = "Hello offline") {}function Harness() {- const { state, sendMessage, resendLastMessage, loadSession } =+ const { state, sendMessage, resendLastMessage, loadSession, cancelStreamingTurn,+ configureSession, setPersonaSelection, setLLMSelection,+ setReplyLanguageOverride } =useChatStateAdapter();return (<><button onClick={() => void loadSession("s1")}>Load</button>+ <button onClick={() => void loadSession("new-session")}>Load new</button><button onClick={() => sendMessage("Hello offline")}>Send</button><button onClick={() => sendMessage("Second offline")}>Send another</button><button onClick={() => void resendLastMessage()}>Resend</button>+ <button onClick={cancelStreamingTurn}>Stop</button>+ <button onClick={() => {+ configureSession({+ capability: "deep_research", workspaceMode: "immersive_reading",+ workspaceId: "other-workspace", courseId: "other-course",+ masteryPathId: "other-path", masterySessionMode: "study",+ });+ setPersonaSelection("other-persona");+ setLLMSelection({ model_id: "other-model", profile_id: "other-profile" });+ void setReplyLanguageOverride("zh");+ }}>Change live settings</button>+ <button onClick={() => {+ configureSession({ workspaceMode: "immersive_reading", workspaceId: "ws-reading" });+ setReadingWorkspace("ws-reading");+ setReadingMaterial("deadbeef", 2);+ setReadingViewport({ locator: 7, selection: "old passage", timeSeconds: 12 });+ }}>Prepare reading</button>+ <button onClick={() => {+ configureSession({ capability: "immersive_watching", workspaceMode: "immersive_watching" });+ setWatchingMaterial("video-a");+ setWatchingViewport(42);+ }}>Prepare watching</button><div data-testid="submissionFailed">{String(state.submissionFailed)}</div><div data-testid="lastTurnFailed">{String(state.lastTurnFailed)}</div>+ <div data-testid="capability">{state.activeCapability}</div><div data-testid="submissionNeedsReview">{String(state.submissionNeedsReview)}</div>+ <div data-testid="submissionNotSaved">{String(state.submissionNotSaved)}</div><div data-testid="messages">{JSON.stringify(state.messages.map((message) => ({@@ -140,12 +177,31 @@ function Harness() {)}</div><div data-testid="stored">- {localStorage.getItem("deeptutor.failedSubmissions") ?? ""}+ {JSON.stringify(readFailedSubmissions("s1"))}</div></>);}+function BootstrapDraft() {+ const { newSession } = useChatStateAdapter();+ useEffect(() => {+ newSession({ capability: "deep_research" });+ }, [newSession]);+ return null;+}++function PersistentProviderRoutes() {+ const [onChat, setOnChat] = useState(true);+ return (+ <ChatStateAdapterProvider>+ <button onClick={() => setOnChat((value) => !value)}>Toggle chat route</button>+ {onChat ? <BootstrapDraft /> : null}+ <Harness />+ </ChatStateAdapterProvider>+ );+}+function readMessages() {return JSON.parse(screen.getByTestId("messages").textContent ?? "[]",@@ -153,14 +209,14 @@ function readMessages() {}function readStoredKeys() {- return Object.keys(- JSON.parse(screen.getByTestId("stored").textContent || "{}"),- );+ return readFailedSubmissions("s1").length ? ["s1"] : [];}beforeEach(() => {localStorage.clear();sessionStorage.clear();+ resetReadingTurnState();+ resetWatchingTurnState();fixture.connected = false;fixture.sent = [];fixture.emit = undefined;@@ -197,8 +253,8 @@ it("marks a submission the server never received as unsent, not a failed reply",expect(screen.getByTestId("submissionFailed").textContent).toBe("true");expect(screen.getByTestId("lastTurnFailed").textContent).toBe("true");// The text survives in local storage for reload recovery.- expect(JSON.parse(screen.getByTestId("stored").textContent ?? "{}"))- .toMatchObject({ s1: [{ content: "Hello offline" }] });+ expect(JSON.parse(screen.getByTestId("stored").textContent ?? "[]"))+ .toMatchObject([{ content: "Hello offline" }]);} finally {vi.useRealTimers();}@@ -450,6 +506,138 @@ it("restores a failed first message in a draft and can retry after reload", asyn}});+it("retries a failed draft with its original settings after live settings change", async () => {+ vi.useFakeTimers();+ try {+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ fireEvent.click(screen.getByText("Send"));+ await act(async () => { await vi.advanceTimersByTimeAsync(2_400); });+ fireEvent.click(screen.getByText("Change live settings"));+ fixture.connected = true;+ await act(async () => { fireEvent.click(screen.getByText("Resend")); });+ expect(fixture.sent.at(-1)).toMatchObject({+ type: "start_turn", content: "Hello offline", capability: null,+ workspace_mode: "", workspace_id: null, course_id: null,+ mastery_path_id: null, mastery_session_mode: null, persona: "",+ llm_selection: null, language: "en", reading_workspace_id: null,+ reading_material_id: null, timed_media_id: null,+ });+ expect(fixture.sent.at(-1)).not.toHaveProperty("reply_language_override");+ } finally {+ vi.useRealTimers();+ }+});++it("retries the original reading viewport after the live document changes", async () => {+ vi.useFakeTimers();+ try {+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ fireEvent.click(screen.getByText("Prepare reading"));+ fireEvent.click(screen.getByText("Send"));+ await act(async () => { await vi.advanceTimersByTimeAsync(2_400); });+ setReadingWorkspace("ws-other");+ setReadingMaterial("feedface", 3);+ setReadingViewport({ locator: 99, selection: "new passage", timeSeconds: 33 });+ fixture.connected = true;+ await act(async () => { fireEvent.click(screen.getByText("Resend")); });+ expect(fixture.sent.at(-1)).toMatchObject({+ type: "start_turn", workspace_id: "ws-reading",+ reading_workspace_id: "ws-reading", reading_material_id: "deadbeef",+ reading_material_revision: 2,+ reading_viewport: { locator: 7, selection: "old passage", time_seconds: 12 },+ });+ } finally {+ vi.useRealTimers();+ }+});++it("retries the original watching position after the live video changes", async () => {+ vi.useFakeTimers();+ try {+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ fireEvent.click(screen.getByText("Prepare watching"));+ fireEvent.click(screen.getByText("Send"));+ await act(async () => { await vi.advanceTimersByTimeAsync(2_400); });+ setWatchingMaterial("video-b");+ setWatchingViewport(99);+ fixture.connected = true;+ await act(async () => { fireEvent.click(screen.getByText("Resend")); });+ expect(fixture.sent.at(-1)).toMatchObject({+ type: "start_turn", timed_media_id: "video-a",+ timed_media_viewport: { time_seconds: 42 },+ });+ } finally {+ vi.useRealTimers();+ }+});++it("Stop before admission cannot erase another tab's newer same-ID retry", async () => {+ vi.useFakeTimers();+ try {+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ fireEvent.click(screen.getByText("Send"));+ const original = readFailedSubmission("draft:general");+ expect(original?.submissionId).toBeTruthy();+ await vi.advanceTimersByTimeAsync(1);+ // Tab A still has the failed logical submission and rewrites it while+ // this tab's socket has no turn ID. The Stop action must not delete A's+ // newer durable record.+ storeFailedSubmission("draft:general", {+ submissionId: original?.submissionId,+ content: original?.content ?? "",+ capability: original?.capability,+ requestSnapshot: original?.requestSnapshot,+ });+ fireEvent.click(screen.getByText("Stop"));+ expect(readFailedSubmission("draft:general")?.submissionId)+ .toBe(original?.submissionId);+ expect(screen.getByTestId("submissionFailed").textContent).toBe("true");+ } finally {+ vi.useRealTimers();+ }+});++it("hydrates an already selected empty draft after the chat page's child effect", () => {+ storeFailedSubmission("draft:general", {+ content: "First message offline",+ requestSnapshot: {+ content: "First message offline", capability: "chat",+ enabledTools: [], knowledgeBases: [], language: "en",+ },+ });+ render(+ <StrictMode>+ <ChatStateAdapterProvider>+ <BootstrapDraft />+ <Harness />+ </ChatStateAdapterProvider>+ </StrictMode>,+ );+ expect(readMessages()).toEqual([+ { role: "user", content: "First message offline", failed: true },+ ]);+ expect(screen.getByTestId("capability").textContent).toBe("deep_research");+ expect(screen.getByTestId("lastTurnFailed").textContent).toBe("true");+});++it("restores the failed draft when /chat remounts under the same provider", () => {+ storeFailedSubmission("draft:general", {+ content: "First message offline",+ requestSnapshot: {+ content: "First message offline", capability: "chat",+ enabledTools: [], knowledgeBases: [], language: "en",+ },+ });+ render(<PersistentProviderRoutes />);+ expect(readMessages().at(-1)?.content).toBe("First message offline");+ fireEvent.click(screen.getByText("Toggle chat route"));+ fireEvent.click(screen.getByText("Toggle chat route"));+ expect(readMessages().at(-1)).toEqual({+ role: "user", content: "First message offline", failed: true,+ });+ expect(screen.getByTestId("capability").textContent).toBe("deep_research");+});+it("keeps a start_turn_rejected submission as an unsent user row across reload", async () => {fixture.connected = true;fixture.session = completedServerSession();@@ -528,6 +716,56 @@ it("a later successful send clears only its own record", async () => {}});+it("moves an older failed draft message into the server session after a later send succeeds", async () => {+ vi.useFakeTimers();+ try {+ const firstView = render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ fireEvent.click(screen.getByText("Send"));+ await act(async () => { await vi.advanceTimersByTimeAsync(2_400); });+ fixture.connected = true;+ fireEvent.click(screen.getByText("Send another"));+ const secondId = readFailedSubmissions("draft:general").at(-1)?.submissionId;+ await act(async () => {+ fixture.emit?.({+ type: "session", source: "chat", stage: "", content: "",+ turn_id: "second-draft-turn", seq: 0, timestamp: Date.now() / 1000,+ metadata: { session_id: "new-session", turn_id: "second-draft-turn" },+ });+ });+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ expect(readFailedSubmissions("new-session")).toHaveLength(2);+ await act(async () => {+ fixture.emit?.({+ type: "done", source: "chat", stage: "responding", content: "",+ turn_id: "second-draft-turn", seq: 1, timestamp: Date.now() / 1000,+ metadata: { status: "completed", user_message_id: 3, assistant_message_id: 4 },+ });+ });+ expect(readFailedSubmissions("new-session").map((record) => record.content)).toEqual([+ "Hello offline",+ ]);+ firstView.unmount();+ fixture.session = {+ ...completedServerSession(),+ messages: [+ ...completedServerSession().messages,+ {+ id: 3, session_id: "new-session", role: "user", content: "Second offline",+ metadata: { client_submission_id: secondId },+ events: [], attachments: [], created_at: 3, parent_message_id: 2,+ },+ ],+ };+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load new")); });+ expect(readMessages().at(-1)).toEqual({+ role: "user", content: "Hello offline", failed: true,+ });+ } finally {+ vi.useRealTimers();+ }+});+it("does not mistake another tab's identical text for this submission", async () => {const ownId = seedUnsentSubmission();fixture.session = {@@ -547,6 +785,12 @@ it("does not mistake another tab's identical text for this submission", async ()role: "user", content: "Hello offline", failed: true,});expect(readFailedSubmissions("s1")).toHaveLength(1);+ fixture.connected = true;+ await act(async () => { fireEvent.click(screen.getByText("Resend")); });+ expect(fixture.sent.at(-1)).toMatchObject({+ type: "start_turn", content: "Hello offline", client_submission_id: ownId,+ });+ expect(fixture.sent.some((command) => command.type === "regenerate")).toBe(false);firstView.unmount();(fixture.session.messages as Array<Record<string, unknown>>)[2].metadata = {client_submission_id: ownId,@@ -578,5 +822,276 @@ it("falls back to localStorage text when sessionStorage is unavailable", () => {const record = readFailedSubmission("s1");expect(record?.content).toBe("Keep this text");expect(record?.retryRequiresReview).toBe(true);- expect(localStorage.getItem("deeptutor.failedSubmissions")).toContain("Keep this text");+ expect(localStorage.getItem(+ "deeptutor.failedSubmissions.record.s1:" + record?.submissionId,+ )).toContain("Keep this text");+});++it("keeps the old session fallback's precedence, including an empty tombstone", () => {+ const old = {+ submissionId: "old-map", content: "Stale map text", capability: "chat",+ requestSnapshot: { content: "Stale map text" }, savedAt: Date.now(),+ };+ localStorage.setItem("deeptutor.failedSubmissions", JSON.stringify({ s1: [old] }));+ sessionStorage.setItem("deeptutor.failedSubmissions.fallback.s1", "[]");+ expect(readFailedSubmissions("s1")).toEqual([]);+ sessionStorage.setItem("deeptutor.failedSubmissions.fallback.s1", JSON.stringify([{+ ...old, submissionId: "fallback", content: "Fallback text",+ }]));+ expect(readFailedSubmissions("s1").map((record) => record.content)).toEqual([+ "Fallback text",+ ]);+});++it("saves to localStorage when the sessionStorage getter itself throws", () => {+ vi.spyOn(window, "sessionStorage", "get").mockImplementation(() => {+ throw new DOMException("Unavailable", "SecurityError");+ });+ expect(storeFailedSubmission("s1", {+ content: "Local survives", requestSnapshot: { content: "Local survives" },+ })).not.toBeNull();+ expect(readFailedSubmission("s1")?.content).toBe("Local survives");+});++it("prunes expired records across sessions before falling back on quota", () => {+ const staleKey = "deeptutor.failedSubmissions.record.old:stale";+ localStorage.setItem(staleKey, JSON.stringify({+ submissionId: "stale", content: "Old attachment", capability: "chat",+ requestSnapshot: { content: "Old attachment", attachment: "A".repeat(10_000) },+ savedAt: Date.now() - 8 * 24 * 60 * 60 * 1000,+ }));+ const localSetItem = localStorage.setItem.bind(localStorage);+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (key.startsWith("deeptutor.failedSubmissions.record.") &&+ localStorage.getItem(staleKey)) {+ throw new DOMException("Quota", "QuotaExceededError");+ }+ localSetItem(key, value);+ });+ expect(storeFailedSubmission("s1", {+ content: "New text", requestSnapshot: { content: "New text" },+ })).not.toBeNull();+ expect(localStorage.getItem(staleKey)).toBeNull();+ expect(readFailedSubmission("s1")?.content).toBe("New text");+});++it("prefers a newer full local snapshot when stale session removal fails", () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date("2026-09-27T04:00:00Z"));+ const localSetItem = localStorage.setItem.bind(localStorage);+ let fullFits = false;+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (!fullFits && value.length > 500) {+ throw new DOMException("Quota", "QuotaExceededError");+ }+ localSetItem(key, value);+ });+ storeFailedSubmission("s1", {+ submissionId: "same-id", content: "Old text", capability: "chat",+ requestSnapshot: { content: "Old text", attachment: "A".repeat(10_000) },+ });+ fullFits = true;+ vi.spyOn(sessionStorage, "removeItem").mockImplementation(() => {+ throw new DOMException("Unavailable", "SecurityError");+ });+ storeFailedSubmission("s1", {+ submissionId: "same-id", content: "New text", capability: "chat",+ requestSnapshot: { content: "New text", attachment: "B".repeat(10_000) },+ });+ expect(readFailedSubmission("s1")?.content).toBe("New text");+ expect(readFailedSubmission("s1")?.requestSnapshot).toMatchObject({+ attachment: "B".repeat(10_000),+ });+ } finally {+ vi.useRealTimers();+ }+});++it("binds a failed draft to its server session when no destination copy fits", () => {+ storeFailedSubmission("draft:general", {+ submissionId: "draft-a", content: "Full draft", capability: "chat",+ requestSnapshot: { content: "Full draft", attachment: "A".repeat(10_000) },+ });+ const sourceKey = "deeptutor.failedSubmissions.record.draft%3Ageneral:draft-a";+ const localSetItem = localStorage.setItem.bind(localStorage);+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (key.startsWith("deeptutor.failedSubmissions.record.s2:")) {+ throw new DOMException("Quota", "QuotaExceededError");+ }+ localSetItem(key, value);+ });+ const sessionSetItem = sessionStorage.setItem.bind(sessionStorage);+ vi.spyOn(sessionStorage, "setItem").mockImplementation((key, value) => {+ if (key.startsWith("deeptutor.failedSubmissions.record.s2:")) {+ throw new DOMException("Quota", "QuotaExceededError");+ }+ sessionSetItem(key, value);+ });+ expect(moveFailedSubmissions("draft:general", "s2", ["draft-a"])).toEqual(["draft-a"]);+ expect(localStorage.getItem(sourceKey)).toContain("Full draft");+ expect(readFailedSubmissions("s2").map((record) => record.content)).toEqual(["Full draft"]);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ sessionStorage.clear(); // Closing the tab removes the binding, not the durable source.+ expect(readFailedSubmissions("draft:general").map((record) => record.content)).toEqual([+ "Full draft",+ ]);+});++it("keeps the durable draft source when its destination only fits in sessionStorage", () => {+ storeFailedSubmission("draft:general", {+ submissionId: "draft-a", content: "Full draft", capability: "chat",+ requestSnapshot: { content: "Full draft", attachment: "A".repeat(10_000) },+ });+ const localSetItem = localStorage.setItem.bind(localStorage);+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (key.startsWith("deeptutor.failedSubmissions.record.s2:")) {+ throw new DOMException("Quota", "QuotaExceededError");+ }+ localSetItem(key, value);+ });+ expect(moveFailedSubmissions("draft:general", "s2", ["draft-a"])).toEqual(["draft-a"]);+ expect(readFailedSubmission("s2")?.requestSnapshot).toMatchObject({+ attachment: expect.any(String),+ });+ sessionStorage.clear();+ expect(readFailedSubmission("draft:general")?.content).toBe("Full draft");+});++it("clears the bound draft source once the server accepts its submission", () => {+ storeFailedSubmission("draft:general", {+ submissionId: "draft-a", content: "Full draft", capability: "chat",+ requestSnapshot: { content: "Full draft" },+ });+ const localSetItem = localStorage.setItem.bind(localStorage);+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (key.startsWith("deeptutor.failedSubmissions.record.s2:")) {+ throw new DOMException("Quota", "QuotaExceededError");+ }+ localSetItem(key, value);+ });+ moveFailedSubmissions("draft:general", "s2", ["draft-a"]);+ clearFailedSubmission("s2", "draft-a");+ expect(readFailedSubmissions("s2")).toEqual([]);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ expect(localStorage.getItem(+ "deeptutor.failedSubmissions.record.draft%3Ageneral:draft-a",+ )).toBeNull();+});++it("warns when browser storage cannot save even the unsent text", async () => {+ vi.useFakeTimers();+ try {+ vi.spyOn(localStorage, "setItem").mockImplementation(() => {+ throw new DOMException("Quota", "QuotaExceededError");+ });+ vi.spyOn(sessionStorage, "setItem").mockImplementation(() => {+ throw new DOMException("Unavailable", "SecurityError");+ });+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ fireEvent.click(screen.getByText("Send"));+ await act(async () => { await vi.advanceTimersByTimeAsync(2_400); });+ expect(screen.getByTestId("submissionNotSaved").textContent).toBe("true");+ expect(screen.getByTestId("submissionFailed").textContent).toBe("true");+ expect(readMessages().at(-1)?.content).toBe("Hello offline");+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+});++it("unions one tab's session fallback with another tab's local record", () => {+ const localSetItem = localStorage.setItem.bind(localStorage);+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (value.length > 500) throw new DOMException("Quota", "QuotaExceededError");+ localSetItem(key, value);+ });+ storeFailedSubmission("s1", {+ submissionId: "large-tab-a", content: "Tab A attachment", capability: "chat",+ requestSnapshot: {+ content: "Tab A attachment", language: "en",+ attachments: [{ filename: "large.png", base64: "A".repeat(10_000) }],+ },+ });+ expect(sessionStorage.getItem(+ "deeptutor.failedSubmissions.record.s1:large-tab-a",+ )).toContain("Tab A attachment");+ storeFailedSubmission("s1", {+ submissionId: "small-tab-b", content: "Tab B text", capability: "chat",+ requestSnapshot: { content: "Tab B text", language: "en" },+ });+ expect(readFailedSubmissions("s1").map((record) => record.content).sort()).toEqual([+ "Tab A attachment", "Tab B text",+ ]);+ clearFailedSubmission("s1", "large-tab-a");+ expect(readFailedSubmissions("s1").map((record) => record.content)).toEqual([+ "Tab B text",+ ]);+});++it("preserves an interleaved write from another tab while storing and clearing", () => {+ const localSetItem = localStorage.setItem.bind(localStorage);+ let interleaved = false;+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (!interleaved && key === "deeptutor.failedSubmissions.record.s1:tab-a") {+ interleaved = true;+ // Tab B writes after A has prepared its value but before A commits.+ localSetItem("deeptutor.failedSubmissions.record.s2:tab-b", JSON.stringify({+ submissionId: "tab-b", content: "Tab B pending", capability: "chat",+ requestSnapshot: { content: "Tab B pending", language: "en" },+ savedAt: Date.now(),+ }));+ }+ localSetItem(key, value);+ });+ storeFailedSubmission("s1", {+ submissionId: "tab-a", content: "Tab A pending", capability: "chat",+ requestSnapshot: { content: "Tab A pending", language: "en" },+ });+ expect(interleaved).toBe(true);+ expect(readFailedSubmissions("s1").map((record) => record.content)).toEqual(["Tab A pending"]);+ expect(readFailedSubmissions("s2").map((record) => record.content)).toEqual(["Tab B pending"]);+ const localRemoveItem = localStorage.removeItem.bind(localStorage);+ let interleavedClear = false;+ vi.spyOn(localStorage, "removeItem").mockImplementation((key) => {+ if (!interleavedClear && key === "deeptutor.failedSubmissions.record.s1:tab-a") {+ interleavedClear = true;+ localSetItem("deeptutor.failedSubmissions.record.s2:tab-c", JSON.stringify({+ submissionId: "tab-c", content: "Tab C pending", capability: "chat",+ requestSnapshot: { content: "Tab C pending", language: "en" },+ savedAt: Date.now(),+ }));+ }+ localRemoveItem(key);+ });+ clearFailedSubmission("s1", "tab-a");+ expect(interleavedClear).toBe(true);+ expect(readFailedSubmissions("s2").map((record) => record.content)).toEqual([+ "Tab B pending", "Tab C pending",+ ]);+});++it("keeps a stale tab's retry after another tab cleared the same submission ID", () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date("2026-09-27T04:00:00Z"));+ storeFailedSubmission("s1", {+ submissionId: "shared-id", content: "First try", capability: "chat",+ requestSnapshot: { content: "First try" },+ });+ // Tab B receives the server acknowledgment while tab A still has its+ // optimistic failed row and retries that same causal ID offline.+ clearFailedSubmission("s1", "shared-id");+ storeFailedSubmission("s1", {+ submissionId: "shared-id", content: "First try", capability: "chat",+ requestSnapshot: { content: "First try" },+ });+ expect(readFailedSubmissions("s1").map((record) => record.content)).toEqual([+ "First try",+ ]);+ clearFailedSubmission("s1", "shared-id");+ expect(readFailedSubmissions("s1")).toEqual([]);+ } finally {+ vi.useRealTimers();+ }});diff --git a/web/tests/chat-resend-decision.test.ts b/web/tests/chat-resend-decision.test.tsindex f43561ac4..e9e28dc67 100644--- a/web/tests/chat-resend-decision.test.ts+++ b/web/tests/chat-resend-decision.test.ts@@ -49,6 +49,52 @@ test("a failed user persisted during socket loss is reconciled before regenerate);});+test("an identical user row from another tab cannot claim an unsent submission", () => {+ const lastUser = {+ id: -3,+ parentMessageId: 2,+ failedSubmissionId: "my-submission",+ requestSnapshot: { content: "same text" },+ };+ const remote = {+ status: "failed",+ messages: [+ { id: 1, role: "user" as const, content: "old" },+ { id: 2, role: "assistant" as const, content: "done" },+ {+ id: 3, role: "user" as const, content: "same text",+ parent_message_id: 2,+ metadata: { client_submission_id: "other-tab" },+ },+ ],+ };+ assert.deepEqual(decideFailedTurnReplay(+ [{ id: 1 }, { id: 2 }, lastUser], lastUser, remote,+ ), { kind: "resend" });+ assert.deepEqual(decideFailedTurnReplay(+ [{ id: 1 }, { id: 2 }, lastUser], lastUser,+ { ...remote, messages: [...remote.messages.slice(0, 2), {+ ...remote.messages[2], metadata: { client_submission_id: "my-submission" },+ }] },+ ), { kind: "reconcile_regenerate", userId: 3 });+});++test("a newer user turn prevents regenerating the wrong persisted submission", () => {+ const lastUser = {+ id: -3, parentMessageId: 2, failedSubmissionId: "my-submission",+ requestSnapshot: { content: "my text" },+ };+ assert.deepEqual(decideFailedTurnReplay(+ [{ id: 1 }, { id: 2 }, lastUser], lastUser,+ { status: "failed", messages: [+ { id: 3, role: "user", content: "my text", parent_message_id: 2,+ metadata: { client_submission_id: "my-submission" } },+ { id: 4, role: "user", content: "later turn", parent_message_id: 3,+ metadata: { client_submission_id: "other-tab" } },+ ] },+ ), { kind: "refresh" });+});+test("resend is unavailable when the failed tail is hidden by branch selection", () => {const root = { id: 1, role: "user" as const, parentMessageId: null };const older = { id: 2, role: "assistant" as const, parentMessageId: 1 };diff --git a/web/tests/chat-submission-clock.spec.tsx b/web/tests/chat-submission-clock.spec.tsxindex 86f7e03fa..4d78c7863 100644--- a/web/tests/chat-submission-clock.spec.tsx+++ b/web/tests/chat-submission-clock.spec.tsx@@ -36,6 +36,11 @@ function Harness() {<button onClick={() => regenerateLastMessage()}>Retry</button><button onClick={cancelStreamingTurn}>Stop</button><div data-testid="events">{JSON.stringify(message?.events ?? [])}</div>+ <div data-testid="last-turn-failed">{String(state.lastTurnFailed)}</div>+ <div data-testid="last-message">{JSON.stringify({+ role: message?.role, content: message?.content,+ failedSubmission: message?.failedSubmission,+ })}</div>{message?.role === "assistant" && (<StreamingStatusevents={message.events ?? []}@@ -105,11 +110,14 @@ it("counts submission latency before the first frame, preserves it on completionexpect(screen.getByRole("status")).toHaveTextContent("0s");});-it("keeps a stopped marker when cancelled before the first server event", () => {+it("keeps an unsent retryable message when stopped before server admission", () => {render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);fireEvent.click(screen.getByText("Send"));fireEvent.click(screen.getByText("Stop"));- expect(screen.getByTestId("events")).toHaveTextContent('"status":"cancelled"');+ expect(screen.getByTestId("last-turn-failed")).toHaveTextContent("true");+ expect(screen.getByTestId("last-message")).toHaveTextContent(+ '"role":"user","content":"Hello","failedSubmission":true',+ );});it("retains the connection error in the reply after transport closes", () => {