DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(web): keep failed chat submissions recoverable and retryable (#1594)
XZHae0daa9a48af
diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex 31b3ee1f8..99bd377d5 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -1,6 +1,11 @@"use client";import { activeWorkspaceId } from "@/lib/workspace-scope";+import {+ clearFailedSubmission,+ readFailedSubmission,+ storeFailedSubmission,+} from "@/lib/failed-submissions";import React, {createContext,@@ -196,6 +201,10 @@ export interface ChatState {/** True when the last turn ended in a failure (not a user cancel) and* the session is no longer streaming. Drives the Resend affordance. */lastTurnFailed: boolean;+ /** True when the tail of the transcript is a user row the server never+ * accepted (#1594). Drives the composer-adjacent error banner; the+ * error must not render as an assistant reply. */+ submissionFailed: boolean;}export interface SessionConfiguration {@@ -295,6 +304,9 @@ export interface MessageItem {trace?: MessageTraceMetadata;/** Edit-branching: id of the message this row continues. */parentMessageId?: number | null;+ /** This submission never reached the server (#1594). Rendered with an+ * "unsent" marker; its requestSnapshot drives the retry. */+ failedSubmission?: boolean;}interface SessionEntry extends Omit<ChatState, "sessionKey"> {@@ -376,6 +388,9 @@ type Action =status?: SessionRuntimeStatus;errorMessage?: string;turnId?: string | null;+ /** The turn never left this tab: the WebSocket could not connect, so+ * the server never saw the user's message (#1594). */+ submissionFailed?: boolean;}| {type: "BIND_SERVER_SESSION";@@ -464,6 +479,7 @@ function createSessionEntry(updatedAt: Date.now(),selectedBranches: {},lastTurnFailed: false,+ submissionFailed: false,};}@@ -750,10 +766,21 @@ function reducer(state: ProviderState, action: Action): ProviderState {const session =state.sessions[action.key] ?? createSessionEntry(action.key);const existing = session.messages ?? [];+ // A retry (or the next message) is underway, so the trailing user row+ // is being submitted again — drop the unsent marker for the attempt+ // in flight; a failing attempt re-flags it on STREAM_END (#1594).+ const flaggedTail = existing[existing.length - 1];+ const unflagged =+ flaggedTail?.role === "user" && flaggedTail.failedSubmission+ ? [+ ...existing.slice(0, -1),+ { ...flaggedTail, failedSubmission: false },+ ]+ : existing;// Chain the placeholder assistant onto whatever message currently// sits at the tip — this is normally the user row just added by// ADD_USER_MSG (possibly an optimistic negative id during an edit).- const tip = existing.length > 0 ? existing[existing.length - 1] : null;+ const tip = unflagged.length > 0 ? unflagged[unflagged.length - 1] : null;return {...state,sessions: {@@ -768,7 +795,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {activeTurnId: null,lastSeq: 0,messages: [- ...existing,+ ...unflagged,{id: nextOptimisticId(),role: "assistant",@@ -879,6 +906,51 @@ function reducer(state: ProviderState, action: Action): ProviderState {}case "STREAM_END": {const ending = state.sessions[action.key];+ // A submission the server never received (#1594): drop the empty+ // STREAM_START placeholder so the failure cannot read as an assistant+ // reply that errored, and flag the optimistic user row as unsent+ // instead. The connection error surfaces next to the composer, retry+ // rides on the flagged row's request snapshot. Only this submission's+ // own optimistic row qualifies — a regenerate or ask_user reply that+ // cannot connect falls through to the standard failed handling below,+ // where its user row is a row the server already holds.+ if (action.submissionFailed && ending) {+ const messages = [...ending.messages];+ const placeholder = messages[messages.length - 1];+ const candidate =+ placeholder?.role === "assistant" &&+ !placeholder.content &&+ !(placeholder.events ?? []).length+ ? messages[messages.length - 2]+ : undefined;+ if (+ candidate?.role === "user" &&+ typeof candidate.id === "number" &&+ candidate.id < 0+ ) {+ messages.pop();+ messages[messages.length - 1] = {+ ...candidate,+ failedSubmission: true,+ };+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [action.key]: {+ ...ending,+ messages,+ isStreaming: false,+ currentStage: "",+ status: action.status ?? "failed",+ activeTurnId: null,+ updatedAt: Date.now(),+ },+ },+ sidebarRefreshToken: state.sidebarRefreshToken + 1,+ };+ }+ }// Settle the trailing line: during streaming the emphasis repair runs// only when a newline completes a line, so the last one is still raw.const settled = (() => {@@ -1808,6 +1880,9 @@ export function ChatStateAdapterProvider({(event.metadata as { status?: string } | undefined)?.status ||"completed",);+ // The server finished this turn, so it owns the transcript from+ // here — any locally stored "unproven submission" for it is stale.+ clearFailedSubmission(effectiveKey);dispatch({type: "STREAM_END",key: effectiveKey,@@ -1915,6 +1990,10 @@ export function ChatStateAdapterProvider({}pendingRegenerateRef.current.delete(effectiveKey);pendingResendRef.current.delete(effectiveKey);+ // A terminal error is server-generated: the turn was accepted, so+ // the stored submission record (if any) must not resurrect the text+ // as "unsent" after a reload (#1594).+ clearFailedSubmission(effectiveKey);const status = String((event.metadata as { status?: string } | undefined)?.status ||"failed",@@ -2003,7 +2082,18 @@ export function ChatStateAdapterProvider({if (!runner.client.connected) {if (attempt >= 10) {console.error("WebSocket failed to connect after retries");- dispatch({ type: "STREAM_END", key, status: "failed", errorMessage: i18n.t("Couldn't reach the server. Please check your connection and retry.") });+ dispatch({+ type: "STREAM_END",+ key,+ status: "failed",+ errorMessage: i18n.t(+ "Couldn't reach the server. Please check your connection and retry.",+ ),+ // The start_turn command never left this tab — mark the turn+ // as an unsent submission rather than a failed assistant+ // reply (#1594).+ submissionFailed: true,+ });// Surfaces the dead-after-N-retries case (different code path// from the close-while-streaming handler above). Same user// mental model, so same toast copy.@@ -2200,14 +2290,76 @@ export function ChatStateAdapterProvider({Date.now(),readStoredChatResponseTimeout() * 1000,);+ // Restore a submission the server never accepted (#1594). The record+ // only survives when no terminal evidence ever arrived, so its text+ // is missing from the server transcript — reattach it as a clearly+ // unsent row with a working retry. If the transcript's last user row+ // already carries this text, the server (or another tab) accepted a+ // retry and its view wins: drop the record instead.+ let restoredMessages = messages;+ let restoredStatus = loadedStatus;+ if (!options?.revalidate && loadedStatus !== "running") {+ const failedRecord = readFailedSubmission(key);+ if (failedRecord) {+ const tailUser = [...messages]+ .reverse()+ .find((message) => message.role === "user");+ if (tailUser && tailUser.content === failedRecord.content) {+ clearFailedSubmission(key);+ } else {+ const stored = failedRecord.requestSnapshot;+ const base: Record<string, unknown> =+ typeof stored === "object" && stored !== null+ ? (stored as Record<string, unknown>)+ : {};+ // The resend path replays this snapshot verbatim, so restore+ // the fields it requires even if the stored record predates+ // them; ``content`` is authoritative from the record itself.+ const snapshot = {+ ...base,+ content: failedRecord.content,+ enabledTools: Array.isArray(base.enabledTools)+ ? base.enabledTools+ : [],+ knowledgeBases: Array.isArray(base.knowledgeBases)+ ? base.knowledgeBases+ : [],+ language: typeof base.language === "string" ? base.language : "en",+ } as MessageRequestSnapshot;+ restoredMessages = [+ ...messages,+ {+ id: nextOptimisticId(),+ role: "user" as const,+ content: failedRecord.content,+ capability: failedRecord.capability,+ parentMessageId: tipMessageId(+ buildVisiblePath(+ messages,+ normalizeSelectedBranches(+ session.preferences?.selected_branches,+ ),+ ).messages,+ ),+ ...(snapshot.attachments?.length+ ? { attachments: snapshot.attachments }+ : {}),+ requestSnapshot: snapshot,+ failedSubmission: true,+ },+ ];+ restoredStatus = "failed";+ }+ }+ }dispatch({type: options?.revalidate ? "REVALIDATE_SESSION" : "LOAD_SESSION",key,sessionId: key,title: session.title || "",- messages,+ messages: restoredMessages,activeTurnId: activeTurn?.turn_id || activeTurn?.id || null,- status: loadedStatus,+ status: restoredStatus,tools: Array.isArray(session.preferences?.tools)? session.preferences.tools: [],@@ -2612,6 +2764,25 @@ export function ChatStateAdapterProvider({legacyPersistUserMessage === false? false: undefined;+ // Pessimistic record (#1594): remember this submission locally until+ // evidence arrives that the server took the turn over (``done``, a+ // terminal error, or a cancel). If none ever does — the socket never+ // connected — a reload can restore the text as clearly unsent.+ // Replays/resends (``displayUserMessage: false``) and card answers+ // keep the record of the row they replay rather than adding one.+ if (+ session.sessionId &&+ options?.displayUserMessage !== false &&+ !options?.masteryAnswer &&+ !options?.masterySkip &&+ content.trim() !== ""+ ) {+ storeFailedSubmission(session.sessionId, {+ content,+ capability: effectiveCapability,+ requestSnapshot,+ });+ }return sendThroughRunner(key,buildStartTurnInput({@@ -2711,6 +2882,9 @@ 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).+ if (session.sessionId) clearFailedSubmission(session.sessionId);dispatch({ type: "STREAM_END", key, status: "cancelled" });}}, []);@@ -2790,7 +2964,7 @@ export function ChatStateAdapterProvider({const key = currentState.selectedKey;if (!key) return;const session = currentState.sessions[key];- if (!session || !session.sessionId) return;+ if (!session) return;if (!isFailedTurnVisible(session.messages,session.selectedBranches,@@ -2801,6 +2975,67 @@ export function ChatStateAdapterProvider({.reverse().find((m) => m.role === "user" && m.requestSnapshot);if (!lastUser?.requestSnapshot) return;+ // Retry the failed tail as a new turn, keeping the existing optimistic+ // user row visible (its snapshot is replayed verbatim).+ const retryUnsavedTail = () => {+ const live = stateRef.current;+ const liveSession = live.sessions[key];+ if (+ live.selectedKey !== key ||+ !liveSession ||+ !isFailedTurnVisible(+ liveSession.messages,+ liveSession.selectedBranches,+ liveSession.status,+ liveSession.isStreaming,+ )+ ) return;+ const liveLastUser = [...liveSession.messages]+ .reverse()+ .find((message) => message.role === "user" && message.requestSnapshot);+ if (!liveLastUser?.requestSnapshot) return;+ const lastMessage =+ liveSession.messages[liveSession.messages.length - 1];+ if (lastMessage?.role === "assistant") {+ pendingResendRef.current.set(key, { ...lastMessage });+ }+ // Remove the trailing failed assistant bubble so the new turn's+ // STREAM_START placeholder replaces it rather than stacking below.+ dispatch({ type: "POP_LAST_ASSISTANT", key });+ const snapshot = liveLastUser.requestSnapshot;+ void sendMessage(+ snapshot.content,+ undefined,+ undefined,+ undefined,+ undefined,+ {+ displayUserMessage: false,+ requestSnapshotOverride: snapshot,+ parentMessageId:+ typeof liveLastUser.parentMessageId === "number" &&+ liveLastUser.parentMessageId <= 0+ ? undefined+ : liveLastUser.parentMessageId,+ },+ ).then((sent) => {+ if (sent) return;+ const stash = pendingResendRef.current.get(key);+ pendingResendRef.current.delete(key);+ // A submission failure settles the tail itself (pops the+ // placeholder, flags the user row) — restoring the stash then+ // would resurrect an empty assistant bubble (#1594).+ const tail = stateRef.current.sessions[key]?.messages.at(-1);+ if (!stash || tail?.role === "user") return;+ dispatch({ type: "RESTORE_ASSISTANT", key, message: stash });+ });+ };+ // A draft has no server session to reconcile against — nothing was+ // persisted, so retry directly (#1594).+ if (!session.sessionId) {+ retryUnsavedTail();+ return;+ }// A dropped socket can hide a successfully persisted user row before its// DONE ids reach this tab. Query the server before deciding whether this// is a regenerate or a genuinely unsaved first attempt.@@ -2857,37 +3092,8 @@ export function ChatStateAdapterProvider({regenerateLastMessage(true);return;}- // The first attempt failed before the user row reached storage. Retry it- // as a new turn, keeping the existing optimistic row visible.- const lastMessage = liveSession.messages[liveSession.messages.length - 1];- if (lastMessage?.role === "assistant") {- pendingResendRef.current.set(key, { ...lastMessage });- }- // Remove the trailing failed assistant bubble so the new turn's- // STREAM_START placeholder replaces it rather than stacking below.- dispatch({ type: "POP_LAST_ASSISTANT", key });- const snapshot = liveLastUser.requestSnapshot;- void sendMessage(- snapshot.content,- undefined,- undefined,- undefined,- undefined,- {- displayUserMessage: false,- requestSnapshotOverride: snapshot,- parentMessageId:- typeof liveLastUser.parentMessageId === "number" &&- liveLastUser.parentMessageId <= 0- ? undefined- : liveLastUser.parentMessageId,- },- ).then((sent) => {- if (sent) return;- const stash = pendingResendRef.current.get(key);- pendingResendRef.current.delete(key);- if (stash) dispatch({ type: "RESTORE_ASSISTANT", key, message: stash });- });+ // The first attempt failed before the user row reached storage.+ retryUnsavedTail();}, [regenerateLastMessage, sendMessage]);const derivedState = useMemo<ChatState>(() => {@@ -2920,6 +3126,15 @@ export function ChatStateAdapterProvider({current.status,current.isStreaming,),+ submissionFailed: (() => {+ if (current.isStreaming) return false;+ const tail = current.messages[current.messages.length - 1];+ return (+ (current.status === "failed" || current.status === "rejected") &&+ tail?.role === "user" &&+ tail.failedSubmission === true+ );+ })(),};}, [state]);diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 7f6a9b3e8..25df19741 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -28,6 +28,7 @@ import { useChatRouteSession } from "@/features/chat/controllers/useChatRouteSesimport { waitForReplyLanguageSave } from "@/features/chat/controllers/reply-language-save";import {+ AlertCircle,GraduationCap,NotebookPen,PenLine,@@ -2680,6 +2681,36 @@ export default function ChatWorkspace({</div>)}+ {/* Submission failure banner (#1594): the server never received+ the message, so the error belongs next to the composer — not+ rendered as an assistant reply — with the message's text kept+ above, marked unsent, and retryable. */}+ {state.submissionFailed ? (+ <div+ role="alert"+ data-submission-error="true"+ className="mx-auto w-full max-w-[960px] px-6 pb-1"+ >+ <div className="flex w-full items-center gap-2 rounded-xl border border-[var(--destructive)]/30 bg-[var(--destructive)]/5 px-3 py-2">+ <AlertCircle+ className="h-4 w-4 shrink-0 text-[var(--destructive)]"+ aria-hidden="true"+ />+ <span className="min-w-0 flex-1 text-[12px] leading-[1.5] text-[var(--foreground)]">+ {t(+ "Couldn't reach the server. Please check your connection and retry.",+ )}+ </span>+ <button+ type="button"+ onClick={handleResendMessage}+ className="shrink-0 rounded-md px-2 py-1 text-[11.5px] font-medium text-[var(--foreground)] hover:bg-[var(--muted)]"+ >+ {t("Resend")}+ </button>+ </div>+ </div>+ ) : null}<ChatComposercomposerRef={composerRef}capMenuRef={capMenuRef}diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex d733ba96c..9ee46396f 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -142,6 +142,9 @@ interface ChatMessageItem {attachments?: MessageAttachment[];requestSnapshot?: MessageRequestSnapshot;parentMessageId?: number | null;+ /** The server never accepted this submission (#1594) — rendered as an+ * unsent message, not an ordinary sent one. */+ failedSubmission?: boolean;}interface NotebookReferenceGroup {@@ -1784,6 +1787,18 @@ export const UserMessage = memo(function UserMessage({<div className="whitespace-pre-wrap">{msg.content}</div></div>)}+ {/* Unsent marker (#1594): this text never reached the server, so the+ bubble must not read as an ordinary sent message. The error and+ retry live next to the composer, not on an assistant bubble. */}+ {!editing && msg.failedSubmission ? (+ <div+ data-unsent="true"+ className="flex items-center gap-1 pr-1 text-[11px] font-medium text-[var(--destructive)]"+ >+ <AlertCircle className="h-3.5 w-3.5" aria-hidden="true" />+ {t("Not sent")}+ </div>+ ) : null}{!editing && refTreeItems.length > 0 && (<div className="pr-1"><ContextReferenceTreediff --git a/web/lib/chat-resend.ts b/web/lib/chat-resend.tsindex ea548211d..3eb981ed8 100644--- a/web/lib/chat-resend.ts+++ b/web/lib/chat-resend.ts@@ -4,9 +4,13 @@ type MessageId = number | string;interface ChatBranchMessage extends BranchMessage {role: "user" | "assistant" | "system";+ /** Set when this submission never reached the server (#1594): the turn+ * left no assistant row, so the unsent user row is the retry handle. */+ failedSubmission?: boolean;}-/** A failed turn can be retried only while its assistant is on the visible branch. */+/** A failed turn can be retried only while its tail is on the visible branch:+ * either the failed assistant reply, or a user row flagged as never sent. */export function isFailedTurnVisible<T extends ChatBranchMessage>(messages: T[],selectedBranches: Record<string, number>,@@ -15,8 +19,13 @@ export function isFailedTurnVisible<T extends ChatBranchMessage>(): boolean {if (isStreaming || (status !== "failed" && status !== "rejected")) return false;const tail = messages[messages.length - 1];- if (tail?.role !== "assistant") return false;- return buildVisiblePath(messages, selectedBranches).messages.at(-1) === tail;+ if (tail?.role === "assistant") {+ return buildVisiblePath(messages, selectedBranches).messages.at(-1) === tail;+ }+ if (tail?.role === "user" && tail.failedSubmission) {+ return buildVisiblePath(messages, selectedBranches).messages.at(-1) === tail;+ }+ return false;}interface LocalMessage {diff --git a/web/lib/failed-submissions.ts b/web/lib/failed-submissions.tsnew file mode 100644index 000000000..6966a9d07--- /dev/null+++ b/web/lib/failed-submissions.ts@@ -0,0 +1,119 @@+/**+ * Locally persisted failed chat submissions (issue #1594).+ *+ * When a submission never reaches the server (the WebSocket could not+ * connect), the optimistic user row exists only in memory — a reload wiped+ * both the text and any sign it failed. These helpers keep the last failed+ * submission of each session in local storage so the transcript can be+ * reopened with the text recoverable and marked unsent.+ *+ * A record is written pessimistically when a fresh turn is submitted, and+ * removed by any evidence the server took the turn over (a terminal event,+ * ``done``, or a user cancel). Whatever survives is therefore a submission+ * the client cannot prove the server ever accepted.+ */++import { browserStorage } from "@/shared/storage";++/** The request snapshot replayed by the resend path. Opaque here on+ * purpose: at runtime it is a full ``MessageRequestSnapshot``, but typing+ * it would point ``lib/`` at ``features/``. The chat adapter casts it+ * back on the way out. */+export type FailedSubmissionSnapshot = unknown;++export interface FailedSubmissionRecord {+ content: string;+ capability: string;+ requestSnapshot: FailedSubmissionSnapshot;+ savedAt: number;+}++const STORAGE_KEY = "deeptutor.failedSubmissions";+/** Records older than this are stale transcript history, not a pending retry. */+const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;++function isRecord(value: unknown): value is FailedSubmissionRecord {+ if (!value || typeof value !== "object") return false;+ const record = value as Partial<FailedSubmissionRecord>;+ return (+ typeof record.content === "string" &&+ record.content.trim() !== "" &&+ Boolean(record.requestSnapshot) &&+ typeof record.savedAt === "number"+ );+}++function readAll(): Record<string, FailedSubmissionRecord> {+ if (typeof window === "undefined") return {};+ try {+ const raw = browserStorage.readRaw("local", STORAGE_KEY);+ if (!raw) return {};+ const parsed: unknown = 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 as Record<string, unknown>,+ )) {+ if (sessionId && isRecord(value)) out[sessionId] = value;+ }+ return out;+ } catch {+ return {};+ }+}++function writeAll(records: Record<string, FailedSubmissionRecord>): void {+ if (typeof window === "undefined") return;+ // A full or unavailable store just means no recovery after reload;+ // the in-session retry still works.+ browserStorage.writeRaw("local", STORAGE_KEY, JSON.stringify(records));+}++/** Remember ``submission`` as the latest unproven submission of a session. */+export function storeFailedSubmission(+ sessionId: string,+ submission: {+ content: string;+ capability?: string | null;+ requestSnapshot: FailedSubmissionSnapshot;+ },+): void {+ if (!sessionId || submission.content.trim() === "") return;+ const records = readAll();+ const now = Date.now();+ for (const [key, record] of Object.entries(records)) {+ if (now - record.savedAt > MAX_AGE_MS) delete records[key];+ }+ records[sessionId] = {+ content: submission.content,+ capability: submission.capability ?? "",+ requestSnapshot: submission.requestSnapshot,+ savedAt: now,+ };+ writeAll(records);+}++/** The session's unproven submission, if one survived. */+export function readFailedSubmission(+ sessionId: string,+): FailedSubmissionRecord | null {+ if (!sessionId) return null;+ const record = readAll()[sessionId];+ if (!record) return null;+ if (Date.now() - record.savedAt > MAX_AGE_MS) {+ clearFailedSubmission(sessionId);+ return null;+ }+ return record;+}++/** Drop the session's record — used once the server is known to own the turn. */+export function clearFailedSubmission(sessionId: string): void {+ if (!sessionId) return;+ const records = readAll();+ if (!(sessionId in records)) return;+ delete records[sessionId];+ writeAll(records);+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 1b3332c44..3c747c1f1 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -880,6 +880,7 @@"No deleted chats": "No deleted chats","Permanently delete this session?": "Permanently delete this session?","Resend": "Resend",+ "Not sent": "Not sent","Up to date": "Up to date","Update available": "Update available","Run Tour": "Run Tour",diff --git a/web/locales/fr/app.json b/web/locales/fr/app.jsonindex d07fd97f1..5d4cde189 100644--- a/web/locales/fr/app.json+++ b/web/locales/fr/app.json@@ -4283,6 +4283,7 @@"Interrupted": "Interrompu","Cancelling…": "Annulation…","Resend": "Renvoyer",+ "Not sent": "Non envoyé","Or upload a folder (one-time import)": "Ou importer un dossier (importation unique)","Choosing a folder here is a one-time import. For a folder that stays in sync, use Linked folders.": "Choisir un dossier ici lance une importation unique. Pour garder un dossier synchronisé, utilisez les dossiers liés.","Linked folders": "Dossiers liés",diff --git a/web/locales/uk/app.json b/web/locales/uk/app.jsonindex d9991009c..a72f2efed 100644--- a/web/locales/uk/app.json+++ b/web/locales/uk/app.json@@ -4060,6 +4060,7 @@"No deleted chats": "Немає видалених чатів","Permanently delete this session?": "Назавжди видалити цей сеанс?","Resend": "Надіслати повторно",+ "Not sent": "Не надіслано","Ready · {{count}} doc": "Готово · {{count}} документ","Ready · {{count}} docs": "Готово · {{count}} документів","MCP": "MCP",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 0f38bb2e4..14362a1bf 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -909,6 +909,7 @@"No deleted chats": "没有已删除的对话","Permanently delete this session?": "确定要彻底删除此对话吗?","Resend": "重新发送",+ "Not sent": "未发送","Up to date": "已最新","Update available": "有新版本","Run Tour": "运行引导",diff --git a/web/tests/chat-failed-submission-recovery.spec.tsx b/web/tests/chat-failed-submission-recovery.spec.tsxnew file mode 100644index 000000000..33bf00331--- /dev/null+++ b/web/tests/chat-failed-submission-recovery.spec.tsx@@ -0,0 +1,294 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import {+ ChatStateAdapterProvider,+ useChatStateAdapter,+} from "@/features/chat/ChatStateAdapter";+import { initI18n } from "@/i18n/init";+import { storeFailedSubmission } from "@/lib/failed-submissions";++initI18n("en");++const fixture = vi.hoisted(() => ({+ connected: false,+ sent: [] as Array<Record<string, unknown>>,+ emit: undefined as undefined | ((event: Record<string, unknown>) => void),+ close: undefined as undefined | (() => void),+ session: undefined as undefined | Record<string, unknown>,+}));++vi.mock("@/features/chat/transport/UnifiedTurnClient", () => ({+ UnifiedTurnClient: class {+ constructor(+ emit: (event: Record<string, unknown>) => void,+ close: () => void,+ ) {+ fixture.emit = emit;+ fixture.close = close;+ }+ get connected() {+ return fixture.connected;+ }+ connect() {}+ disconnect() {}+ send(message: Record<string, unknown>) {+ fixture.sent.push(message);+ }+ sendAwaitingAck(message: Record<string, unknown>) {+ fixture.sent.push(message);+ return Promise.resolve(true);+ }+ setResumeState() {}+ },+}));++vi.mock("@/lib/session-api", () => ({+ getSession: async (sessionId: string) => {+ if (!fixture.session) throw new Error("no fixture session configured");+ return {+ ...JSON.parse(JSON.stringify(fixture.session)),+ session_id: sessionId,+ id: sessionId,+ };+ },+ getMessageTrace: async () => ({+ session_id: "",+ message_id: 0,+ events: [],+ total: 0,+ }),+ deleteMessage: async () => ({}),+ updateBranchSelection: async () => ({}),+ updateSessionTitle: async () => fixture.session ?? {},+ updateSessionReplyLanguage: async () => fixture.session ?? {},+}));++/** A server transcript: one completed user/assistant exchange. */+function completedServerSession() {+ return {+ id: "s1",+ session_id: "s1",+ title: "Chat",+ created_at: 1,+ updated_at: Date.now() / 1000,+ status: "completed",+ messages: [+ {+ id: 1,+ session_id: "s1",+ role: "user",+ content: "hi",+ events: [],+ attachments: [],+ created_at: 1,+ parent_message_id: null,+ },+ {+ id: 2,+ session_id: "s1",+ role: "assistant",+ content: "hello",+ events: [],+ attachments: [],+ created_at: 2,+ parent_message_id: 1,+ },+ ],+ preferences: {},+ };+}++function seedUnsentSubmission(content = "Hello offline") {+ storeFailedSubmission("s1", {+ content,+ capability: "chat",+ requestSnapshot: {+ content,+ capability: "chat",+ enabledTools: [],+ knowledgeBases: [],+ language: "en",+ },+ });+}++function Harness() {+ const { state, sendMessage, resendLastMessage, loadSession } =+ useChatStateAdapter();+ return (+ <>+ <button onClick={() => void loadSession("s1")}>Load</button>+ <button onClick={() => sendMessage("Hello offline")}>Send</button>+ <button onClick={() => void resendLastMessage()}>Resend</button>+ <div data-testid="submissionFailed">+ {String(state.submissionFailed)}+ </div>+ <div data-testid="lastTurnFailed">{String(state.lastTurnFailed)}</div>+ <div data-testid="messages">+ {JSON.stringify(+ state.messages.map((message) => ({+ role: message.role,+ content: message.content,+ failed: message.failedSubmission === true,+ })),+ )}+ </div>+ <div data-testid="stored">+ {localStorage.getItem("deeptutor.failedSubmissions") ?? ""}+ </div>+ </>+ );+}++function readMessages() {+ return JSON.parse(+ screen.getByTestId("messages").textContent ?? "[]",+ ) as Array<{ role: string; content: string; failed: boolean }>;+}++function readStoredKeys() {+ return Object.keys(+ JSON.parse(screen.getByTestId("stored").textContent || "{}"),+ );+}++beforeEach(() => {+ fixture.connected = false;+ fixture.sent = [];+ fixture.emit = undefined;+ fixture.close = undefined;+});++it("marks a submission the server never received as unsent, not a failed reply", async () => {+ vi.useFakeTimers();+ try {+ fixture.session = completedServerSession();+ render(+ <ChatStateAdapterProvider>+ <Harness />+ </ChatStateAdapterProvider>,+ );+ await act(async () => {+ fireEvent.click(screen.getByText("Load"));+ });+ // Submit while the transport cannot connect. The retry schedule gives+ // up after ~2s of failed connection attempts.+ fireEvent.click(screen.getByText("Send"));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_400);+ });+ // The optimistic user row is flagged unsent and NO assistant row was+ // left behind to masquerade as an errored reply.+ expect(readMessages()).toEqual([+ { role: "user", content: "hi", failed: false },+ { role: "assistant", content: "hello", failed: false },+ { role: "user", content: "Hello offline", failed: true },+ ]);+ 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" } });+ } finally {+ vi.useRealTimers();+ }+});++it("restores the unsent submission after a reload and resends it on retry", async () => {+ fixture.session = completedServerSession();+ seedUnsentSubmission();+ fixture.connected = true;+ render(+ <ChatStateAdapterProvider>+ <Harness />+ </ChatStateAdapterProvider>,+ );+ await act(async () => {+ fireEvent.click(screen.getByText("Load"));+ });+ // The reloaded transcript reattaches the submission as clearly unsent.+ expect(readMessages()).toEqual([+ { role: "user", content: "hi", failed: false },+ { role: "assistant", content: "hello", failed: false },+ { role: "user", content: "Hello offline", failed: true },+ ]);+ expect(screen.getByTestId("submissionFailed").textContent).toBe("true");++ // Retry: the server transcript lacks the row, so it is resent as a new+ // turn from the stored snapshot (no duplicate user bubble).+ await act(async () => {+ fireEvent.click(screen.getByText("Resend"));+ });+ await vi.waitFor(() => {+ const start = fixture.sent.find(+ (message) => message.type === "start_turn",+ );+ expect(start).toMatchObject({ content: "Hello offline" });+ });+ // The turn completes: the server owns the transcript again and the+ // stored record is dropped.+ await act(async () => {+ fixture.emit?.({+ type: "done",+ source: "chat",+ stage: "responding",+ content: "",+ turn_id: "turn-retry",+ seq: 2,+ timestamp: Date.now() / 1000,+ metadata: {+ status: "completed",+ user_message_id: 3,+ assistant_message_id: 4,+ },+ });+ });+ expect(readStoredKeys()).toEqual([]);+ expect(screen.getByTestId("submissionFailed").textContent).toBe("false");+ const messages = readMessages();+ expect(messages[messages.length - 1]).toEqual({+ role: "assistant",+ content: "",+ failed: false,+ });+});++it("drops the record when the server transcript already holds the submission", async () => {+ const serverHoldsIt = {+ ...completedServerSession(),+ status: "failed",+ messages: [+ ...completedServerSession().messages,+ {+ id: 3,+ session_id: "s1",+ role: "user",+ content: "Hello offline",+ events: [],+ attachments: [],+ created_at: 3,+ parent_message_id: 2,+ },+ ],+ };+ fixture.session = serverHoldsIt;+ seedUnsentSubmission();+ render(+ <ChatStateAdapterProvider>+ <Harness />+ </ChatStateAdapterProvider>,+ );+ await act(async () => {+ fireEvent.click(screen.getByText("Load"));+ });+ // The server persisted the user row before the stream broke, so its+ // transcript wins: no unsent duplicate is restored…+ expect(readMessages()).toEqual([+ { role: "user", content: "hi", failed: false },+ { role: "assistant", content: "hello", failed: false },+ { role: "user", content: "Hello offline", failed: false },+ ]);+ expect(screen.getByTestId("submissionFailed").textContent).toBe("false");+ // …and the local record is cleared.+ expect(readStoredKeys()).toEqual([]);+});diff --git a/web/tests/chat-idle-recovery.test.ts b/web/tests/chat-idle-recovery.test.tsindex 1cf1d9d06..08502b5ff 100644--- a/web/tests/chat-idle-recovery.test.ts+++ b/web/tests/chat-idle-recovery.test.ts@@ -106,9 +106,11 @@ test("the loader vets the stored status and skips subscribing to a stale turn",// The verdict has to reach both the state and the subscribe: opening a// socket for a turn we just judged dead would wait for events that can- // never arrive.+ // never arrive. The dispatched status starts from the verdict (it is+ // only overridden when an unsent submission is restored, #1594).assert.match(adapter, /const loadedStatus = resolveLoadedRunStatus\(/);- assert.match(adapter, /status: loadedStatus,/);+ assert.match(adapter, /let restoredStatus = loadedStatus;/);+ assert.match(adapter, /status: restoredStatus,/);assert.match(adapter,/if \(loadedStatus === "running" && \(activeTurn\?\.turn_id \|\| activeTurn\?\.id\)\)/,diff --git a/web/tests/chat-resend-decision.test.ts b/web/tests/chat-resend-decision.test.tsindex 72d126a1e..f43561ac4 100644--- a/web/tests/chat-resend-decision.test.ts+++ b/web/tests/chat-resend-decision.test.ts@@ -56,3 +56,19 @@ test("resend is unavailable when the failed tail is hidden by branch selection",assert.equal(isFailedTurnVisible([root, older, newer], { "1": 2 }, "failed", false), false);assert.equal(isFailedTurnVisible([root, older, newer], { "1": 3 }, "failed", false), true);});++test("an unsent submission tail is retryable without an assistant row (#1594)", () => {+ const root = { id: 1, role: "user" as const, parentMessageId: null };+ const reply = { id: 2, role: "assistant" as const, parentMessageId: 1 };+ const unsent = { id: -3, role: "user" as const, parentMessageId: 2, failedSubmission: true };+ // A submission the server never received leaves the flagged user row as+ // the tail — that row is the retry handle.+ assert.equal(isFailedTurnVisible([root, reply, unsent], {}, "failed", false), true);+ // Without the flag (ordinary optimistic row mid-submit) or while streaming,+ // no retry affordance is derived from it.+ assert.equal(+ isFailedTurnVisible([root, reply, { ...unsent, failedSubmission: false }], {}, "failed", false),+ false,+ );+ assert.equal(isFailedTurnVisible([root, reply, unsent], {}, "failed", true), false);+});diff --git a/web/tests/chat-resend-failed-turn.test.ts b/web/tests/chat-resend-failed-turn.test.tsindex eac1d4b5f..a62f953c7 100644--- a/web/tests/chat-resend-failed-turn.test.ts+++ b/web/tests/chat-resend-failed-turn.test.ts@@ -35,3 +35,22 @@ test("Resend translations exist in en and zh", () => {assert.equal(en.Resend, "Resend");assert.equal(zh.Resend, "重新发送");});++test("failed submissions stay visibly unsent and recoverable (#1594)", () => {+ const adapter = source("features/chat/ChatStateAdapter.tsx");+ assert.match(adapter, /storeFailedSubmission/);+ assert.match(adapter, /readFailedSubmission/);+ assert.match(adapter, /clearFailedSubmission/);+ assert.match(adapter, /submissionFailed: true/);+ const list = source("features/chat/messages/ChatMessageList.tsx");+ assert.match(list, /failedSubmission/);+ assert.match(list, /data-unsent="true"/);+ assert.match(list, /Not sent/);+ const workspace = source("features/chat/components/ChatWorkspace.tsx");+ assert.match(workspace, /state\.submissionFailed/);+ assert.match(workspace, /data-submission-error="true"/);+ const en = JSON.parse(source("locales/en/app.json"));+ const zh = JSON.parse(source("locales/zh/app.json"));+ assert.equal(en["Not sent"], "Not sent");+ assert.equal(zh["Not sent"], "未发送");+});