DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): resolve browser-local unsent submission recovery
Mrmo072adcf7dfa2553
diff --git a/web/components/reading/workspace/ReadingCompanion.tsx b/web/components/reading/workspace/ReadingCompanion.tsxindex 75494b5e1..71c75faf6 100644--- a/web/components/reading/workspace/ReadingCompanion.tsx+++ b/web/components/reading/workspace/ReadingCompanion.tsx@@ -104,7 +104,9 @@ export function ReadingCompanion({state,submitUserReply,regenerateLastMessage,+ resendLastMessage,deleteTurn,+ discardFailedSubmission,editMessage,switchBranch,loadMessageTrace,@@ -443,7 +445,10 @@ export function ReadingCompanion({language={state.language}onCopyAssistantMessage={copyAssistantMessage}onRegenerateMessage={regenerateLastMessage}+ canResendLastTurn={state.lastTurnFailed}+ onResendLastTurn={resendLastMessage}onDeleteTurn={deleteTurn}+ onDiscardFailedSubmission={discardFailedSubmission}selectedBranches={state.selectedBranches}onEditMessage={editMessage}onSwitchBranch={switchBranch}diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsxindex ffdb96c57..eb9ac5c0e 100644--- a/web/components/space/learning/MasteryStudy.tsx+++ b/web/components/space/learning/MasteryStudy.tsx@@ -180,6 +180,7 @@ export function MasteryStudy({regenerateLastMessage,resendLastMessage,deleteTurn,+ discardFailedSubmission,editMessage,switchBranch,loadMessageTrace,@@ -803,6 +804,7 @@ export function MasteryStudy({canResendLastTurn={state.lastTurnFailed}onResendLastTurn={resendLastMessage}onDeleteTurn={deleteTurn}+ onDiscardFailedSubmission={discardFailedSubmission}selectedBranches={state.selectedBranches}onEditMessage={editMessage}onSwitchBranch={switchBranch}diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex caf787c02..2fb66f280 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -338,6 +338,8 @@ export interface MessageItem {interface SessionEntry extends Omit<ChatState, "sessionKey"> {key: string;status: SessionRuntimeStatus;+ /** Runtime status underneath locally restored unsent messages. */+ submissionBaseStatus: SessionRuntimeStatus;activeTurnId: string | null;lastSeq: number;updatedAt: number;@@ -362,6 +364,7 @@ interface SessionSnapshot {messages: MessageItem[];activeTurnId?: string | null;status?: SessionRuntimeStatus;+ serverStatus?: SessionRuntimeStatus;tools?: string[];capability?: string | null;workspaceMode?: WorkspaceMode | null;@@ -404,6 +407,7 @@ type Action =failedSubmissionId?: string;}| { type: "SET_SUBMISSION_PERSISTENCE"; key: string; submissionId: string; saved: boolean }+ | { type: "DISCARD_FAILED_SUBMISSION"; key: string; messageId: number }| { type: "POP_LAST_ASSISTANT"; key: string }| { type: "RESTORE_ASSISTANT"; key: string; message: MessageItem }| { type: "STREAM_START"; key: string; startedAt: number }@@ -500,6 +504,7 @@ function createSessionEntry(typeof window === "undefined" ? "en" : readStoredResponseLanguage(),replyLanguageOverride: null,status: "idle",+ submissionBaseStatus: "idle",activeTurnId: null,lastSeq: 0,updatedAt: Date.now(),@@ -746,6 +751,9 @@ function reducer(state: ProviderState, action: Action): ProviderState {...state.sessions,[action.key]: {...session,+ submissionBaseStatus: session.messages.some(message => message.failedSubmission)+ ? session.submissionBaseStatus+ : session.status,messages: [...session.messages,{@@ -792,6 +800,41 @@ function reducer(state: ProviderState, action: Action): ProviderState {},};}+ case "DISCARD_FAILED_SUBMISSION": {+ const session = state.sessions[action.key];+ if (!session || session.isStreaming) return state;+ const target = session.messages.find(message =>+ message.id === action.messageId && message.role === "user" &&+ message.failedSubmission && action.messageId < 0);+ if (!target) return state;+ // Pending rows form a chain after server history. Removing an earlier+ // one must leave later recoverable submissions on the visible branch.+ const messages = session.messages+ .filter(message => message !== target)+ .map(message => message.parentMessageId === target.id+ ? { ...message, parentMessageId: target.parentMessageId ?? null }+ : message);+ const selectedBranches = { ...session.selectedBranches };+ const parentKey = String(target.parentMessageId ?? "null");+ if (selectedBranches[parentKey] === target.id) {+ const child = selectedBranches[String(target.id)];+ if (child !== undefined) selectedBranches[parentKey] = child;+ else delete selectedBranches[parentKey];+ }+ delete selectedBranches[String(target.id)];+ return {+ ...state,+ sessions: {+ ...state.sessions,+ [action.key]: {+ ...session, messages, selectedBranches,+ status: messages.some(message => message.failedSubmission)+ ? session.status : session.submissionBaseStatus,+ updatedAt: Date.now(),+ },+ },+ };+ }case "POP_LAST_ASSISTANT": {const session = state.sessions[action.key];if (!session || session.messages.length === 0) return state;@@ -1077,6 +1120,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {isStreaming: false,currentStage: "",status: action.status ?? "completed",+ submissionBaseStatus: action.status ?? "completed",activeTurnId:action.status === "running" || pendingAskUser? action.turnId ||@@ -1195,6 +1239,7 @@ function reducer(state: ProviderState, action: Action): ProviderState {// turn from the start rather than trusting a cached cursor.lastSeq: 0,status: action.status || "idle",+ submissionBaseStatus: action.serverStatus ?? action.status ?? "idle",language: action.language ?? existing.language,replyLanguageOverride:action.replyLanguageOverride !== undefined@@ -1531,6 +1576,8 @@ interface ChatContextValue {* original request snapshot (attachments, capability, tools, KB, etc.)* so the new turn runs with the same context as the failed one. */resendLastMessage: () => void;+ /** Discard a local unsent row without mutating server history. */+ discardFailedSubmission: (messageId: number) => void;deleteTurn: (messageId: number) => Promise<void>;/** Re-send a user message under a new branch (sibling of the original).* Uses the composer's current capability / refs — only the text is@@ -2462,23 +2509,42 @@ export function ChatStateAdapterProvider({// was accepted; equal text from another tab is not enough.let restoredMessages = messages;let restoredStatus = loadedStatus;- if (!options?.revalidate && loadedStatus !== "running") {- for (const failedRecord of readFailedSubmissions(key)) {- if (serverContainsFailedSubmission(session.messages ?? [], failedRecord)) {- clearFailedSubmission(key, failedRecord.submissionId);- } else {- restoredMessages = [- ...restoredMessages,- restoredFailedMessage(- failedRecord,- tipMessageId(buildVisiblePath(- restoredMessages,- normalizeSelectedBranches(session.preferences?.selected_branches),- ).messages),- ),- ];- restoredStatus = "failed";- }+ const pendingRecords = readFailedSubmissions(key).filter(record => {+ if (!serverContainsFailedSubmission(session.messages ?? [], record)) return true;+ clearFailedSubmission(key, record.submissionId);+ return false;+ });+ // A background refresh must reconcile pending records exactly like a+ // foreground load; otherwise they vanish until the next full reload.+ if (loadedStatus !== "running") {+ for (const failedRecord of pendingRecords) {+ restoredMessages = [+ ...restoredMessages,+ restoredFailedMessage(+ failedRecord,+ tipMessageId(buildVisiblePath(+ restoredMessages,+ normalizeSelectedBranches(session.preferences?.selected_branches),+ ).messages),+ ),+ ];+ restoredStatus = "failed";+ }+ }+ if (loadedStatus !== "running") {+ for (const local of stateRef.current.sessions[key]?.messages ?? []) {+ if (!local.failedSubmission || !local.failedSubmissionNotSaved ||+ !local.failedSubmissionId ||+ serverContainsFailedSubmission(session.messages ?? [], { submissionId: local.failedSubmissionId }) ||+ restoredMessages.some(message => message.failedSubmissionId === local.failedSubmissionId)) continue;+ restoredMessages = [...restoredMessages, {+ ...local,+ parentMessageId: tipMessageId(buildVisiblePath(+ restoredMessages,+ normalizeSelectedBranches(session.preferences?.selected_branches),+ ).messages),+ }];+ restoredStatus = "failed";}}dispatch({@@ -2489,6 +2555,7 @@ export function ChatStateAdapterProvider({messages: restoredMessages,activeTurnId: activeTurn?.turn_id || activeTurn?.id || null,status: restoredStatus,+ serverStatus: loadedStatus,tools: Array.isArray(session.preferences?.tools)? session.preferences.tools: [],@@ -3582,6 +3649,20 @@ export function ChatStateAdapterProvider({[],);+ const discardFailedSubmission = useCallback((messageId: number) => {+ const current = stateRef.current;+ const key = current.selectedKey;+ if (!key) return;+ const session = current.sessions[key];+ const message = session?.messages.find(item => item.id === messageId);+ if (!session || session.isStreaming || message?.role !== "user" ||+ !message.failedSubmission || messageId >= 0) return;+ if (message.failedSubmissionId) {+ clearFailedSubmission(session.sessionId ?? draftFailedSubmissionKey(), message.failedSubmissionId);+ }+ dispatch({ type: "DISCARD_FAILED_SUBMISSION", key, messageId });+ }, []);+const deleteTurn = useCallback(async (messageId: number) => {const generation = runtimeGeneration.current;@@ -3646,6 +3727,7 @@ export function ChatStateAdapterProvider({submitUserReply,regenerateLastMessage,resendLastMessage,+ discardFailedSubmission,deleteTurn,editMessage,switchBranch,@@ -3678,6 +3760,7 @@ export function ChatStateAdapterProvider({submitUserReply,regenerateLastMessage,resendLastMessage,+ discardFailedSubmission,deleteTurn,editMessage,switchBranch,diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 9cae05f61..d63e91ef6 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -281,6 +281,7 @@ export default function ChatWorkspace() {regenerateLastMessage,resendLastMessage,deleteTurn,+ discardFailedSubmission,editMessage,switchBranch,newSession,@@ -2579,6 +2580,7 @@ export default function ChatWorkspace() {);}}onDeleteTurn={deleteTurn}+ onDiscardFailedSubmission={discardFailedSubmission}selectedBranches={state.selectedBranches}onEditMessage={editMessage}onSwitchBranch={switchBranch}diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex 8972cb2cf..afca9513d 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -151,6 +151,7 @@ interface ChatMessageItem {/** The server never accepted this submission (#1594) — rendered as an* unsent message, not an ordinary sent one. */failedSubmission?: boolean;+ failedSubmissionNeedsReview?: boolean;orphanedFailedTurn?: OrphanedFailedTurn;}@@ -1577,6 +1578,8 @@ export const UserMessage = memo(function UserMessage({kbDisplayNames,showModeBadge,onOpenConsultation,+ onDiscardFailedSubmission,+ onRetryFailedSubmission,}: {msg: ChatMessageItem;index: number;@@ -1595,6 +1598,8 @@ export const UserMessage = memo(function UserMessage({* already names the mode in its own chrome. */showModeBadge?: boolean;onOpenConsultation?: () => void;+ onDiscardFailedSubmission?: (messageId: number) => void;+ onRetryFailedSubmission?: () => void;}) {const { t } = useTranslation();const [editing, setEditing] = useState(false);@@ -1613,7 +1618,7 @@ export const UserMessage = memo(function UserMessage({// the optimistic case by triggering a session reload to resolve the// real id before submitting the branch.const canEdit =- Boolean(onEdit) && typeof msg.id === "number" && !editDisabled;+ Boolean(onEdit) && typeof msg.id === "number" && !editDisabled && !msg.failedSubmission;const startEdit = () => {if (!canEdit) return;setDraft(msg.content);@@ -1834,16 +1839,29 @@ 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. */}+ {/* Recovery records are local to this browser. Keep their actions+ visible so an old pending submission can be resolved in place. */}{!editing && msg.failedSubmission ? (<divdata-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")}+ <span>{t("Not sent")}</span>+ {onRetryFailedSubmission && !msg.failedSubmissionNeedsReview && (+ <button type="button" onClick={onRetryFailedSubmission}+ disabled={editDisabled}+ className="ml-1 rounded-md px-1.5 py-0.5 hover:bg-[var(--muted)] disabled:opacity-35">+ {t("Retry")}+ </button>+ )}+ {onDiscardFailedSubmission && typeof msg.id === "number" && msg.id < 0 && (+ <button type="button" onClick={() => onDiscardFailedSubmission(msg.id!)}+ disabled={editDisabled}+ className="rounded-md px-1.5 py-0.5 hover:bg-[var(--muted)] disabled:opacity-35">+ {t("Discard")}+ </button>+ )}</div>) : null}{!editing && refTreeItems.length > 0 && (@@ -1926,6 +1944,7 @@ export const ChatMessageList = memo(function ChatMessageList({onRegenerateMessage,canResendLastTurn = false,onResendLastTurn,+ onDiscardFailedSubmission,onConfirmOutline,onPreviewAttachment,onOpenConsultation,@@ -1953,6 +1972,7 @@ export const ChatMessageList = memo(function ChatMessageList({* stopped. Drives the Resend affordance on the trailing assistant. */canResendLastTurn?: boolean;onResendLastTurn?: () => void;+ onDiscardFailedSubmission?: (messageId: number) => void;onConfirmOutline?: (outline: Array<{ title: string; overview: string }>,topic: string,@@ -2233,6 +2253,9 @@ export const ChatMessageList = memo(function ChatMessageList({onCopy={onCopyAssistantMessage}onEdit={onEditMessage}editDisabled={isStreaming}+ onDiscardFailedSubmission={onDiscardFailedSubmission}+ onRetryFailedSubmission={!isStreaming && canResendLastTurn &&+ rowIndex === messageRows.length - 1 ? onResendLastTurn : undefined}siblingInfo={sib}onSwitchBranch={onSwitchBranch}availableKbNames={availableKbNames}diff --git a/web/lib/failed-submissions.ts b/web/lib/failed-submissions.tsindex 712eacf7b..8e4d0eb22 100644--- a/web/lib/failed-submissions.ts+++ b/web/lib/failed-submissions.ts@@ -148,7 +148,7 @@ export function serverContainsFailedSubmission(content: string;metadata?: Record<string, unknown>;}[],- record: FailedSubmissionRecord,+ record: Pick<FailedSubmissionRecord, "submissionId">,): boolean {return Boolean(record.submissionId) && messages.some((message) => message.role === "user" &&diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 7708cd778..24d7a764f 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -1,3 +1,4 @@+import { clearFailedSubmission } from "@/lib/failed-submissions";import { scopedUrl } from "@/lib/workspace-scope";import { notifySessionsChanged } from "@/lib/session-events";import { apiFetch, apiUrl } from "@/lib/api";@@ -416,7 +417,9 @@ export async function deleteSession(sessionId: string, workspaceId?: string): Prconst response = await apiFetch(apiUrl(scopedUrl(`/api/sessions/${sessionId}`, workspaceId)), {method: "DELETE",});- await expectJson<{ deleted: boolean }>(response);+ const data = await expectJson<{ deleted: boolean }>(response);+ if (!data.deleted) throw new Error("Session was not deleted");+ clearFailedSubmission(sessionId);invalidateClientCache("sessions:");notifySessionsChanged();}diff --git a/web/tests/chat-failed-submission-recovery.spec.tsx b/web/tests/chat-failed-submission-recovery.spec.tsxindex 54ebfd18d..55c703a61 100644--- a/web/tests/chat-failed-submission-recovery.spec.tsx+++ b/web/tests/chat-failed-submission-recovery.spec.tsx@@ -5,6 +5,7 @@ import {ChatStateAdapterProvider,useChatStateAdapter,} from "@/features/chat/ChatStateAdapter";+import { buildVisiblePath } from "@/lib/message-branches";import { initI18n } from "@/i18n/init";import {resetReadingTurnState, setReadingMaterial, setReadingViewport,@@ -131,7 +132,7 @@ function seedUnsentSubmission(content = "Hello offline") {}function Harness() {- const { state, sendMessage, resendLastMessage, loadSession, cancelStreamingTurn,+ const { state, sendMessage, resendLastMessage, loadSession, cancelStreamingTurn, discardFailedSubmission,configureSession, setPersonaSelection, setLLMSelection,setReplyLanguageOverride } =useChatStateAdapter();@@ -139,6 +140,19 @@ function Harness() {<><button onClick={() => void loadSession("s1")}>Load</button><button onClick={() => void loadSession("new-session")}>Load new</button>+ <button onClick={() => void loadSession("s1", { revalidate: true })}>Revalidate</button>+ <button onClick={() => {+ const first = state.messages.find(message => message.failedSubmission);+ if (first?.id !== undefined) discardFailedSubmission(first.id);+ }}>Discard first</button>+ <button onClick={() => {+ const last = state.messages.at(-1);+ if (last?.id !== undefined) discardFailedSubmission(last.id);+ }}>Discard last</button>+ <button onClick={() => discardFailedSubmission(1)}>Discard saved</button>+ <div data-testid="visible">{JSON.stringify(buildVisiblePath(+ state.messages, state.selectedBranches,+ ).messages.map(message => message.content))}</div><button onClick={() => sendMessage("Hello offline")}>Send</button><button onClick={() => sendMessage("Second offline")}>Send another</button><button onClick={() => sendMessage("", [{ type: "image", filename: "figure.png", base64: "YWJj" }])}>Send image only</button>@@ -1180,3 +1194,152 @@ it("resubscribes a parked ask_user turn on load so its card survives a reload",fixture.sent.filter((message) => message.type === "subscribe_turn").length,).toBe(subscribed);});+++it("discards only the chosen identical pending message and keeps its successor visible after reload", async () => {+ const firstId = seedUnsentSubmission("hi");+ const secondId = seedUnsentSubmission("hi");+ storeFailedSubmission("other-session", {+ content: "hi", submissionId: firstId!, requestSnapshot: {},+ });+ fixture.session = completedServerSession();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ expect(readMessages().filter(message => message.failed)).toHaveLength(2);+ await act(async () => { fireEvent.click(screen.getByText("Discard first")); });+ expect(readFailedSubmissions("s1").map(record => record.submissionId)).toEqual([secondId]);+ expect(readFailedSubmissions("other-session")).toHaveLength(1);+ expect(JSON.parse(screen.getByTestId("visible").textContent!)).toEqual(["hi", "hello", "hi"]);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ expect(readMessages().filter(message => message.failed)).toHaveLength(1);+ await act(async () => { fireEvent.click(screen.getByText("Discard last")); });+ expect(readMessages().map(message => message.content)).toEqual(["hi", "hello"]);+ expect(screen.getByTestId("lastTurnFailed")).toHaveTextContent("false");+ expect(screen.getByTestId("submissionFailed")).toHaveTextContent("false");+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ expect(readFailedSubmissions("s1")).toEqual([]);+ expect(readMessages().filter(message => message.failed)).toEqual([]);+ expect(fixture.sent).toEqual([]);+});++it("never discards a saved server message through the local recovery action", async () => {+ seedUnsentSubmission();+ fixture.session = completedServerSession();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ const before = readMessages();+ fireEvent.click(screen.getByText("Discard saved"));+ expect(readMessages()).toEqual(before);+ expect(readFailedSubmissions("s1")).toHaveLength(1);+});++it("discards a legacy pending record without resurrecting it from the legacy map", async () => {+ localStorage.setItem("deeptutor.failedSubmissions", JSON.stringify({+ s1: { content: "legacy unsent", capability: "chat", requestSnapshot: {}, savedAt: Date.now() },+ }));+ fixture.session = completedServerSession();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ expect(readMessages().at(-1)?.content).toBe("legacy unsent");+ fireEvent.click(screen.getByText("Discard last"));+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ expect(readFailedSubmissions("s1")).toEqual([]);+ expect(readMessages().map(message => message.content)).toEqual(["hi", "hello"]);+});++it("preserves unsent messages on background refresh and clears only causally accepted records", async () => {+ const ownId = seedUnsentSubmission("hi");+ const otherId = seedUnsentSubmission("hi");+ fixture.session = completedServerSession();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ await act(async () => { fireEvent.click(screen.getByText("Revalidate")); });+ expect(readMessages().filter(message => message.failed)).toHaveLength(2);+ (fixture.session.messages as Array<Record<string, unknown>>)[0].metadata = {+ client_submission_id: ownId,+ };+ await act(async () => { fireEvent.click(screen.getByText("Revalidate")); });+ expect(readFailedSubmissions("s1").map(record => record.submissionId)).toEqual([otherId]);+ expect(readMessages().filter(message => message.failed)).toHaveLength(1);+ (fixture.session.messages as Array<Record<string, unknown>>)[0].metadata = {+ client_submission_id: otherId,+ };+ await act(async () => { fireEvent.click(screen.getByText("Revalidate")); });+ expect(readFailedSubmissions("s1")).toEqual([]);+ expect(readMessages().filter(message => message.failed)).toEqual([]);+ expect(screen.getByTestId("lastTurnFailed")).toHaveTextContent("false");+});++it("discards a failed first draft message durably without a server session", async () => {+ storeFailedSubmission("draft:general", {+ content: "offline draft", requestSnapshot: {}, submissionId: "draft-to-discard",+ });+ const view = render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ expect(readMessages().at(-1)?.content).toBe("offline draft");+ fireEvent.click(screen.getByText("Discard last"));+ expect(readMessages()).toEqual([]);+ view.unmount();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ expect(readMessages()).toEqual([]);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+});+++it("keeps pending messages that could not be saved in any browser storage during revalidation", async () => {+ vi.useFakeTimers();+ try {+ fixture.session = completedServerSession();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ for (const storage of [localStorage, sessionStorage]) {+ vi.spyOn(storage, "setItem").mockImplementation(() => {+ throw new DOMException("Unavailable", "SecurityError");+ });+ }+ fireEvent.click(screen.getByText("Send"));+ await act(async () => { await vi.advanceTimersByTimeAsync(GIVE_UP_MS); });+ expect(screen.getByTestId("submissionNotSaved")).toHaveTextContent("true");+ await act(async () => { fireEvent.click(screen.getByText("Revalidate")); });+ expect(readMessages().at(-1)).toEqual({ role: "user", content: "Hello offline", failed: true });+ expect(readFailedSubmissions("s1")).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+});++it("clears a causally accepted recovery record even when the remote turn is still running", async () => {+ const ownId = seedUnsentSubmission("hi");+ fixture.connected = true;+ fixture.session = {+ ...completedServerSession(), status: "running", active_turns: [{ turn_id: "active-turn" }],+ };+ (fixture.session.messages as Array<Record<string, unknown>>)[0].metadata = {+ client_submission_id: ownId,+ };+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ expect(readFailedSubmissions("s1")).toEqual([]);+});++it("does not discard an earlier pending record while another turn is streaming", async () => {+ seedUnsentSubmission();+ fixture.session = completedServerSession();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ fixture.connected = true;+ fireEvent.click(screen.getByText("Send another"));+ const before = readMessages();+ fireEvent.click(screen.getByText("Discard first"));+ expect(readMessages()).toEqual(before);+ expect(readFailedSubmissions("s1")).toHaveLength(2);+});++it("retains a genuine server turn failure after the last local pending record is discarded", async () => {+ seedUnsentSubmission();+ fixture.session = { ...completedServerSession(), status: "failed" };+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ fireEvent.click(screen.getByText("Discard last"));+ expect(screen.getByTestId("submissionFailed")).toHaveTextContent("false");+ expect(screen.getByTestId("lastTurnFailed")).toHaveTextContent("true");+});diff --git a/web/tests/integration/chat-messages.spec.tsx b/web/tests/integration/chat-messages.spec.tsxindex a7539e52f..be7ac451a 100644--- a/web/tests/integration/chat-messages.spec.tsx+++ b/web/tests/integration/chat-messages.spec.tsx@@ -251,3 +251,43 @@ describe('empty reply outcomes', () => {if (status === 'cancelled') expect(screen.queryByRole('alert')).toBeNull();});});+++describe('unsent message recovery actions', () => {+ const pending = [+ { id: -1, role: 'user' as const, content: 'same outline request', parentMessageId: null, failedSubmission: true },+ { id: -2, role: 'user' as const, content: 'same outline request', parentMessageId: -1, failedSubmission: true },+ ];++ it('offers discard for each pending record and retries only the visible tail', async () => {+ const discard = vi.fn();+ const retry = vi.fn();+ const edit = vi.fn();+ render(<ChatMessageList messages={pending} isStreaming={false}+ onCopyAssistantMessage={vi.fn()} onRegenerateMessage={vi.fn()}+ canResendLastTurn onResendLastTurn={retry}+ onDiscardFailedSubmission={discard} onEditMessage={edit} />);+ expect(screen.getAllByText('Not sent')).toHaveLength(2);+ expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();+ const user = userEvent.setup();+ await user.click(screen.getAllByRole('button', { name: 'Discard' })[0]);+ expect(discard).toHaveBeenCalledWith(-1);+ await user.click(screen.getByRole('button', { name: 'Retry' }));+ expect(retry).toHaveBeenCalledOnce();+ });++ it('blocks recovery mutations while streaming and unsafe retries of incomplete snapshots', () => {+ const { rerender } = render(<ChatMessageList messages={pending} isStreaming+ onCopyAssistantMessage={vi.fn()} onRegenerateMessage={vi.fn()}+ canResendLastTurn onResendLastTurn={vi.fn()} onDiscardFailedSubmission={vi.fn()} />);+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();+ for (const button of screen.getAllByRole('button', { name: 'Discard' })) {+ expect(button).toBeDisabled();+ }+ rerender(<ChatMessageList messages={[{ ...pending[0], failedSubmissionNeedsReview: true }]}+ isStreaming={false} onCopyAssistantMessage={vi.fn()} onRegenerateMessage={vi.fn()}+ canResendLastTurn onResendLastTurn={vi.fn()} onDiscardFailedSubmission={vi.fn()} />);+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Discard' })).toBeEnabled();+ });+});diff --git a/web/tests/session-failed-submission-cleanup.spec.ts b/web/tests/session-failed-submission-cleanup.spec.tsnew file mode 100644index 000000000..5223d5305--- /dev/null+++ b/web/tests/session-failed-submission-cleanup.spec.ts@@ -0,0 +1,67 @@+import { beforeEach, expect, it, vi } from "vitest";+import { deleteSession } from "@/lib/session-api";+import { moveFailedSubmissions, readFailedSubmissions, storeFailedSubmission } from "@/lib/failed-submissions";++const fixture = vi.hoisted(() => ({ fetch: vi.fn() }));+vi.mock("@/lib/api", () => ({+ apiUrl: (path: string) => path,+ apiFetch: (...args: unknown[]) => fixture.fetch(...args),+}));++beforeEach(() => {+ localStorage.clear();+ sessionStorage.clear();+ fixture.fetch.mockReset();+});++it("clears only the deleted session after the server confirms deletion", async () => {+ for (const session of ["A", "B"]) {+ storeFailedSubmission(session, { content: "same text", requestSnapshot: {}, submissionId: "same-id" });+ }+ fixture.fetch.mockResolvedValue(new Response(JSON.stringify({ deleted: true }), { status: 200 }));+ await deleteSession("A", "workspace-A");+ expect(fixture.fetch).toHaveBeenCalledWith("/api/sessions/A?dt_workspace=workspace-A", { method: "DELETE" });+ expect(readFailedSubmissions("A")).toEqual([]);+ expect(readFailedSubmissions("B")).toHaveLength(1);+});++it("preserves recovery data if the deletion request fails", async () => {+ storeFailedSubmission("A", { content: "unsent", requestSnapshot: {}, submissionId: "pending" });+ fixture.fetch.mockResolvedValue(new Response("error", { status: 500 }));+ await expect(deleteSession("A")).rejects.toThrow("Request failed: 500");+ expect(readFailedSubmissions("A")).toHaveLength(1);+});++it("does not resurrect old-format records after deletion", async () => {+ localStorage.setItem("deeptutor.failedSubmissions", JSON.stringify({+ A: { content: "legacy", capability: "chat", requestSnapshot: {}, savedAt: Date.now() },+ B: { content: "other", capability: "chat", requestSnapshot: {}, savedAt: Date.now() },+ }));+ fixture.fetch.mockResolvedValue(new Response(JSON.stringify({ deleted: true }), { status: 200 }));+ await deleteSession("A");+ expect(readFailedSubmissions("A")).toEqual([]);+ expect(readFailedSubmissions("B")).toHaveLength(1);+});++it("also clears the draft source of a tab-scoped session binding", async () => {+ storeFailedSubmission("draft:general", { content: "pending draft", requestSnapshot: {}, submissionId: "draft-id" });+ const set = localStorage.setItem.bind(localStorage);+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (key.includes(".record.A:")) throw new DOMException("Quota", "QuotaExceededError");+ set(key, value);+ });+ moveFailedSubmissions("draft:general", "A", ["draft-id"]);+ expect(readFailedSubmissions("A")).toHaveLength(1);+ fixture.fetch.mockResolvedValue(new Response(JSON.stringify({ deleted: true }), { status: 200 }));+ await deleteSession("A");+ expect(readFailedSubmissions("A")).toEqual([]);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+});+++it("keeps recovery data when a successful HTTP response does not confirm deletion", async () => {+ storeFailedSubmission("A", { content: "unsent", requestSnapshot: {}, submissionId: "pending" });+ fixture.fetch.mockResolvedValue(new Response(JSON.stringify({ deleted: false }), { status: 200 }));+ await expect(deleteSession("A")).rejects.toThrow("Session was not deleted");+ expect(readFailedSubmissions("A")).toHaveLength(1);+});