DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(web): preserve unsent repeated text and quota fallback
Bingxi Zhao (Frank)0a116bce22a4
diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex 99bd377d5..9a9c5fc79 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -4,6 +4,7 @@ import { activeWorkspaceId } from "@/lib/workspace-scope";import {clearFailedSubmission,readFailedSubmission,+ serverContainsFailedSubmission,storeFailedSubmission,} from "@/lib/failed-submissions";@@ -205,6 +206,8 @@ export interface ChatState {* accepted (#1594). Drives the composer-adjacent error banner; the* error must not render as an assistant reply. */submissionFailed: boolean;+ /** The text was recovered without its attachments or other request context. */+ submissionNeedsReview: boolean;}export interface SessionConfiguration {@@ -307,6 +310,7 @@ export interface MessageItem {/** This submission never reached the server (#1594). Rendered with an* "unsent" marker; its requestSnapshot drives the retry. */failedSubmission?: boolean;+ failedSubmissionNeedsReview?: boolean;}interface SessionEntry extends Omit<ChatState, "sessionKey"> {@@ -480,6 +484,7 @@ function createSessionEntry(selectedBranches: {},lastTurnFailed: false,submissionFailed: false,+ submissionNeedsReview: false,};}@@ -2291,20 +2296,15 @@ export function ChatStateAdapterProvider({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.+ // only survives when no terminal evidence ever arrived. Compare server+ // row identities recorded before submission: a previous turn may have+ // identical text, and must not erase this new unsent message.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) {+ if (serverContainsFailedSubmission(messages, failedRecord)) {clearFailedSubmission(key);} else {const stored = failedRecord.requestSnapshot;@@ -2346,6 +2346,7 @@ export function ChatStateAdapterProvider({: {}),requestSnapshot: snapshot,failedSubmission: true,+ failedSubmissionNeedsReview: failedRecord.retryRequiresReview,},];restoredStatus = "failed";@@ -2781,6 +2782,15 @@ export function ChatStateAdapterProvider({content,capability: effectiveCapability,requestSnapshot,+ priorMatchingUserIds: session.messages+ .filter(+ (message) =>+ message.role === "user" &&+ message.content === content &&+ message.id != null &&+ (typeof message.id === "string" || message.id > 0),+ )+ .map((message) => String(message.id)),});}return sendThroughRunner(@@ -3135,6 +3145,10 @@ export function ChatStateAdapterProvider({tail.failedSubmission === true);})(),+ submissionNeedsReview: (() => {+ const tail = current.messages[current.messages.length - 1];+ return tail?.role === "user" && tail.failedSubmissionNeedsReview === true;+ })(),};}, [state]);diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 25df19741..7fd703622 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -2697,17 +2697,19 @@ export default function ChatWorkspace({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.",- )}+ {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>- <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>+ {!state.submissionNeedsReview ? (+ <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>+ ) : null}</div></div>) : null}diff --git a/web/lib/chat-resend.ts b/web/lib/chat-resend.tsindex 3eb981ed8..49bb46c8f 100644--- a/web/lib/chat-resend.ts+++ b/web/lib/chat-resend.ts@@ -7,6 +7,8 @@ interface ChatBranchMessage extends BranchMessage {/** 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 quota fallback kept the text but not enough context for safe resend. */+ failedSubmissionNeedsReview?: boolean;}/** A failed turn can be retried only while its tail is on the visible branch:@@ -22,7 +24,7 @@ export function isFailedTurnVisible<T extends ChatBranchMessage>(if (tail?.role === "assistant") {return buildVisiblePath(messages, selectedBranches).messages.at(-1) === tail;}- if (tail?.role === "user" && tail.failedSubmission) {+ if (tail?.role === "user" && tail.failedSubmission && !tail.failedSubmissionNeedsReview) {return buildVisiblePath(messages, selectedBranches).messages.at(-1) === tail;}return false;diff --git a/web/lib/failed-submissions.ts b/web/lib/failed-submissions.tsindex 6966a9d07..691022201 100644--- a/web/lib/failed-submissions.ts+++ b/web/lib/failed-submissions.ts@@ -26,9 +26,14 @@ export interface FailedSubmissionRecord {capability: string;requestSnapshot: FailedSubmissionSnapshot;savedAt: number;+ /** Server user rows with this text before this submission was attempted. */+ 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.`;/** Records older than this are stale transcript history, not a pending retry. */const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;@@ -64,11 +69,30 @@ function readAll(): Record<string, FailedSubmissionRecord> {}}-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));+function fallbackKey(sessionId: string): string {+ return `${FALLBACK_KEY_PREFIX}${encodeURIComponent(sessionId)}`;+}++function writeAll(records: Record<string, FailedSubmissionRecord>): boolean {+ if (typeof window === "undefined") return false;+ return browserStorage.writeRaw("local", STORAGE_KEY, JSON.stringify(records));+}++/** Only a *new* server row proves this submission was accepted. Earlier turns+ * can have identical text, so comparing the last user's content is unsafe. */+export function serverContainsFailedSubmission(+ messages: readonly { id?: number | string; role: string; content: string }[],+ record: FailedSubmissionRecord,+): boolean {+ if (!record.priorMatchingUserIds) return false;+ const prior = new Set(record.priorMatchingUserIds);+ return messages.some(+ (message) =>+ message.role === "user" &&+ message.content === record.content &&+ message.id != null &&+ !prior.has(String(message.id)),+ );}/** Remember ``submission`` as the latest unproven submission of a session. */@@ -78,6 +102,7 @@ export function storeFailedSubmission(content: string;capability?: string | null;requestSnapshot: FailedSubmissionSnapshot;+ priorMatchingUserIds?: string[];},): void {if (!sessionId || submission.content.trim() === "") return;@@ -91,8 +116,32 @@ export function storeFailedSubmission(capability: submission.capability ?? "",requestSnapshot: submission.requestSnapshot,savedAt: now,+ priorMatchingUserIds: submission.priorMatchingUserIds ?? [],};- writeAll(records);+ if (writeAll(records)) {+ browserStorage.removeRaw("session", fallbackKey(sessionId));+ return;+ }+ // A base64 attachment can exceed localStorage's quota. sessionStorage is+ // independent and survives a reload in this tab, so try the full request+ // there before falling back to the text alone.+ const fullRecord = records[sessionId];+ if (browserStorage.writeRaw("session", fallbackKey(sessionId), JSON.stringify(fullRecord))) {+ return;+ }+ const snapshot = fullRecord.requestSnapshot as Record<string, unknown> | null;+ const textOnly: FailedSubmissionRecord = {+ ...fullRecord,+ requestSnapshot: {+ content: fullRecord.content,+ capability: fullRecord.capability,+ language: typeof snapshot?.language === "string" ? snapshot.language : "en",+ enabledTools: [],+ knowledgeBases: [],+ },+ retryRequiresReview: true,+ };+ browserStorage.writeRaw("session", fallbackKey(sessionId), JSON.stringify(textOnly));}/** The session's unproven submission, if one survived. */@@ -100,7 +149,15 @@ export function readFailedSubmission(sessionId: string,): FailedSubmissionRecord | null {if (!sessionId) return null;- const record = readAll()[sessionId];+ const fallbackRaw = browserStorage.readRaw("session", fallbackKey(sessionId));+ let fallback: FailedSubmissionRecord | null = null;+ try {+ const parsed: unknown = fallbackRaw ? JSON.parse(fallbackRaw) : null;+ if (isRecord(parsed)) fallback = parsed;+ } catch {+ // An invalid fallback cannot suppress a valid local record.+ }+ const record = fallback ?? readAll()[sessionId];if (!record) return null;if (Date.now() - record.savedAt > MAX_AGE_MS) {clearFailedSubmission(sessionId);@@ -112,8 +169,9 @@ export function readFailedSubmission(/** Drop the session's record — used once the server is known to own the turn. */export function clearFailedSubmission(sessionId: string): void {if (!sessionId) return;+ browserStorage.removeRaw("session", fallbackKey(sessionId));const records = readAll();if (!(sessionId in records)) return;delete records[sessionId];- writeAll(records);+ if (!writeAll(records)) browserStorage.removeRaw("local", STORAGE_KEY);}diff --git a/web/locales/de/app.json b/web/locales/de/app.jsonindex 41478138a..be36590c9 100644--- a/web/locales/de/app.json+++ b/web/locales/de/app.json@@ -348,6 +348,7 @@"Reference space": "Referenzbereich","Connection lost while generating. Please retry your message.": "Verbindung während der Erstellung verloren. Bitte sende deine Nachricht erneut.","Couldn't reach the server. Please check your connection and retry.": "Der Server war nicht erreichbar. Prüf deine Verbindung und versuch es noch einmal.",+ "Message text was saved, but its attachments or settings could not be restored. Copy it and send again.": "Der Nachrichtentext wurde gespeichert, aber Anhänge oder Einstellungen konnten nicht wiederhergestellt werden. Kopiere den Text und sende ihn erneut.","Today": "Heute","Yesterday": "Gestern","Last 7 days": "Letzte 7 Tage",@@ -881,6 +882,7 @@"No deleted chats": "Keine gelöschten Chats","Permanently delete this session?": "Diese Session endgültig löschen?","Resend": "Erneut senden",+ "Not sent": "Nicht gesendet","Up to date": "Auf dem neuesten Stand","Update available": "Update verfügbar","Run Tour": "Tour starten",diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex d2c819106..a2d6a094c 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -348,6 +348,7 @@"Reference space": "Reference space","Connection lost while generating. Please retry your message.": "Connection lost while generating. Please retry your message.","Couldn't reach the server. Please check your connection and retry.": "Couldn't reach the server. Please check your connection and retry.",+ "Message text was saved, but its attachments or settings could not be restored. Copy it and send again.": "Message text was saved, but its attachments or settings could not be restored. Copy it and send again.","Today": "Today","Yesterday": "Yesterday","Last 7 days": "Last 7 days",diff --git a/web/locales/fr/app.json b/web/locales/fr/app.jsonindex 73a616a32..02c72c010 100644--- a/web/locales/fr/app.json+++ b/web/locales/fr/app.json@@ -458,6 +458,7 @@"Reference space": "Espace de référence","Connection lost while generating. Please retry your message.": "Connexion perdue pendant la génération. Veuillez renvoyer votre message.","Couldn't reach the server. Please check your connection and retry.": "Impossible de joindre le serveur. Vérifiez votre connexion et réessayez.",+ "Message text was saved, but its attachments or settings could not be restored. Copy it and send again.": "Le texte du message a été enregistré, mais les pièces jointes ou les paramètres n’ont pas pu être restaurés. Copiez le texte et renvoyez-le.","Today": "Aujourd'hui","Yesterday": "Hier","Last 7 days": "7 derniers jours",diff --git a/web/locales/uk/app.json b/web/locales/uk/app.jsonindex 22d68912a..950086e4a 100644--- a/web/locales/uk/app.json+++ b/web/locales/uk/app.json@@ -334,6 +334,7 @@"Reference space": "Простір посилань","Connection lost while generating. Please retry your message.": "З'єднання втрачено під час генерації. Будь ласка, повторіть повідомлення.","Couldn't reach the server. Please check your connection and retry.": "Не вдалося з'єднатися з сервером. Перевірте підключення та повторіть спробу.",+ "Message text was saved, but its attachments or settings could not be restored. Copy it and send again.": "Текст повідомлення збережено, але вкладення або налаштування не вдалося відновити. Скопіюйте текст і надішліть його знову.","Today": "Сьогодні","Yesterday": "Вчора","Last 7 days": "Останні 7 днів",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex f497b3d2d..eba543543 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -348,6 +348,7 @@"Reference space": "引用空间","Connection lost while generating. Please retry your message.": "生成过程中连接已断开,请重新发送消息。","Couldn't reach the server. Please check your connection and retry.": "无法连接到服务器,请检查网络后重试。",+ "Message text was saved, but its attachments or settings could not be restored. Copy it and send again.": "消息文字已保存,但附件或设置无法恢复。请复制文字并重新发送。","Today": "今天","Yesterday": "昨天","Last 7 days": "最近 7 天",diff --git a/web/tests/chat-failed-submission-recovery.spec.tsx b/web/tests/chat-failed-submission-recovery.spec.tsxindex 33bf00331..af8bcbf35 100644--- a/web/tests/chat-failed-submission-recovery.spec.tsx+++ b/web/tests/chat-failed-submission-recovery.spec.tsx@@ -5,7 +5,7 @@ import {useChatStateAdapter,} from "@/features/chat/ChatStateAdapter";import { initI18n } from "@/i18n/init";-import { storeFailedSubmission } from "@/lib/failed-submissions";+import { readFailedSubmission, storeFailedSubmission } from "@/lib/failed-submissions";initI18n("en");@@ -98,10 +98,11 @@ function completedServerSession() {};}-function seedUnsentSubmission(content = "Hello offline") {+function seedUnsentSubmission(content = "Hello offline", priorMatchingUserIds: string[] = []) {storeFailedSubmission("s1", {content,capability: "chat",+ priorMatchingUserIds,requestSnapshot: {content,capability: "chat",@@ -124,6 +125,7 @@ function Harness() {{String(state.submissionFailed)}</div><div data-testid="lastTurnFailed">{String(state.lastTurnFailed)}</div>+ <div data-testid="submissionNeedsReview">{String(state.submissionNeedsReview)}</div><div data-testid="messages">{JSON.stringify(state.messages.map((message) => ({@@ -292,3 +294,100 @@ it("drops the record when the server transcript already holds the submission", a// …and the local record is cleared.expect(readStoredKeys()).toEqual([]);});++it("keeps a new unsent submission when an older server turn has identical text", async () => {+ vi.useFakeTimers();+ try {+ fixture.session = {+ ...completedServerSession(),+ messages: [+ ...completedServerSession().messages,+ {+ id: 3,+ session_id: "s1",+ role: "user",+ content: "Hello offline",+ events: [],+ attachments: [],+ created_at: 3,+ parent_message_id: 2,+ },+ ],+ };+ const firstView = render(+ <ChatStateAdapterProvider>+ <Harness />+ </ChatStateAdapterProvider>,+ );+ await act(async () => {+ fireEvent.click(screen.getByText("Load"));+ });+ fireEvent.click(screen.getByText("Send"));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_400);+ });+ const saved = readFailedSubmission("s1");+ expect(saved?.priorMatchingUserIds).toEqual(["3"]);+ firstView.unmount();+ render(+ <ChatStateAdapterProvider>+ <Harness />+ </ChatStateAdapterProvider>,+ );+ await act(async () => {+ fireEvent.click(screen.getByText("Load"));+ });+ expect(readMessages().slice(-2)).toEqual([+ { role: "user", content: "Hello offline", failed: false },+ { role: "user", content: "Hello offline", failed: true },+ ]);+ expect(readStoredKeys()).toEqual(["s1"]);+ } finally {+ vi.useRealTimers();+ }+});++it("preserves text after storage quota errors without offering an incomplete resend", async () => {+ const localSetItem = vi.spyOn(localStorage, "setItem").mockImplementation(() => {+ throw new DOMException("Storage quota exceeded", "QuotaExceededError");+ });+ const sessionSetItem = sessionStorage.setItem.bind(sessionStorage);+ vi.spyOn(sessionStorage, "setItem").mockImplementation((key, value) => {+ if (value.length > 500) {+ throw new DOMException("Storage quota exceeded", "QuotaExceededError");+ }+ sessionSetItem(key, value);+ });+ fixture.session = completedServerSession();+ storeFailedSubmission("s1", {+ content: "Text with attachment",+ capability: "chat",+ priorMatchingUserIds: [],+ requestSnapshot: {+ content: "Text with attachment",+ capability: "chat",+ language: "en",+ attachments: [{ filename: "large.png", base64: "A".repeat(10_000) }],+ },+ });+ const saved = readFailedSubmission("s1");+ expect(saved?.content).toBe("Text with attachment");+ expect(saved?.retryRequiresReview).toBe(true);+ expect(JSON.stringify(saved?.requestSnapshot)).not.toContain("large.png");+ expect(localSetItem).toHaveBeenCalled();+ render(+ <ChatStateAdapterProvider>+ <Harness />+ </ChatStateAdapterProvider>,+ );+ await act(async () => {+ fireEvent.click(screen.getByText("Load"));+ });+ expect(readMessages().at(-1)).toEqual({+ role: "user",+ content: "Text with attachment",+ failed: true,+ });+ expect(screen.getByTestId("submissionNeedsReview").textContent).toBe("true");+ expect(screen.getByTestId("lastTurnFailed").textContent).toBe("false");+});