DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Merge PR #1945: fence edited submissions and isolate recovery by account and backend support
Bingxi Zhao (Frank)583bdfc714e2
diff --cc deeptutor/api/routers/sessions.pyindex 2f88caff8,7c3cdbda1..ed886df9c--- a/deeptutor/api/routers/sessions.py+++ b/deeptutor/api/routers/sessions.py@@@ -38,6 -39,29 +39,43 @@@ def _turn_application_service()return get_application_container().turns++class SessionStoreCapabilities(BaseModel):++ submission_replacement: bool++++[email protected]("/capabilities", response_model=SessionStoreCapabilities)++async def session_store_capabilities():++ """Expose operations the configured store can perform atomically."""++ return SessionStoreCapabilities(++ submission_replacement=callable(getattr(get_session_store(), "replace_submission", None))++ )+++++ class SubmissionReplacementRequest(BaseModel):+ original_submission_id: str = Field(min_length=1, max_length=100)+ request: TurnRequest+++ class SubmissionReplacementResponse(BaseModel):+ status: Literal["started"]+ session_id: str+ submission_id: str+ turn: dict[str, Any]+++ @router.post("/submission-replacement", response_model=SubmissionReplacementResponse)+ async def replace_submission(body: SubmissionReplacementRequest):+ """Resolve admission atomically before an edited retry is sent."""+ try:+ return await _turn_application_service().replace_submission(+ body.original_submission_id, body.request, start=True+ )++ except NotImplementedError as exc:++ raise HTTPException(status_code=501, detail=str(exc)) from exc+ except RuntimeError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc++class SessionRenameRequest(BaseModel):title: str = Field(..., min_length=1, max_length=100)diff --cc deeptutor/app/service.pyindex b81fb02cf,8acec1c7b..268537cbf--- a/deeptutor/app/service.py+++ b/deeptutor/app/service.py@@@ -19,6 -19,82 +19,82 @@@ from .contracts import TurnRequesclass TurnApplicationService:+ @staticmethod+ def _submission_digest(payload: dict[str, Any]) -> str:+ identity = {+ key: value+ for key, value in payload.items()+ if key not in {"session_id", "workspace_id"}+ }+ return hashlib.sha256(+ json.dumps(identity, sort_keys=True, default=str).encode()+ ).hexdigest()++ @workspace_writer+ async def replace_submission(+ self, original_id: str, payload: TurnRequest | dict[str, Any], *, start: bool = False+ ) -> dict[str, Any]:+ request = (+ payload if isinstance(payload, TurnRequest) else TurnRequest.model_validate(payload)+ )+ if (+ not request.client_submission_id+ or not request.persist_user_message+ or request.regenerate+ ):+ raise RuntimeError("An edited submission requires a new user message identity.")+ from deeptutor.services.workspace.context import get_workspace_scope, workspace_context++ wire = request.to_payload()+ if get_workspace_scope() is None and "workspace_id" in wire:+ with workspace_context(wire.get("workspace_id")):+ return await self.replace_submission(original_id, request, start=start)+ store, _ = self._resolve()+ replace = getattr(store, "replace_submission", None)+ if not callable(replace):- raise RuntimeError("This session store does not support submission replacement.")++ raise NotImplementedError("This session store does not support submission replacement.")+ receipt = await replace(+ original_id,+ request.client_submission_id,+ self._submission_digest(wire),+ request.session_id,+ )+ if (+ receipt["status"] == "admitted"+ and receipt["turn"]["status"] in self._ACTIVE_TURN_STATUSES+ ):+ if not await self.cancel_turn_and_wait(receipt["turn"]["id"]):+ raise RuntimeError("The original turn has not stopped yet. Please retry the edit.")+ # Re-read only after the owner finishes: user persistence and+ # cancellation can overlap before the original row exists.+ receipt = await replace(+ original_id,+ request.client_submission_id,+ self._submission_digest(wire),+ receipt["session_id"],+ )+ if not start:+ return receipt+ wire["session_id"] = receipt["session_id"]+ if receipt["status"] == "admitted":+ if receipt["user_message_id"] is not None:+ messages = await store.get_messages(receipt["session_id"])+ original = next(+ (row for row in messages if row["id"] == receipt["user_message_id"]), None+ )+ if original is None:+ raise RuntimeError("The original message changed. Refresh before editing it.")+ wire["parent_message_id"] = original.get("parent_message_id")+ elif receipt["turn"]["status"] not in {"failed", "cancelled"}:+ raise RuntimeError("The admitted message is not yet available for editing.")+ session, turn = await self.start_turn(wire)+ return {+ "status": "started",+ "session_id": session["id"],+ "submission_id": request.client_submission_id,+ "turn": turn,+ }+def __init__(self,store_provider: Any,diff --cc tests/app/test_turn_application_service.pyindex 147fd5e16,737494ff0..60bf74db0--- a/tests/app/test_turn_application_service.py+++ b/tests/app/test_turn_application_service.py@@@ -324,3 -393,3 +393,30 @@@ async def test_second_worker_cancel_is_fencing_token=lease.fencing_token,)await coordinator.release_turn(lease)++++++async def test_replacement_availability_matches_configured_store_before_mutation(++ submission_service, monkeypatch++):++ from fastapi import HTTPException++++ from deeptutor.api.routers import sessions++ from deeptutor.core.turn_request import TurnRequest++++ service, store, _, _, calls = submission_service++ monkeypatch.setattr(sessions, "get_session_store", lambda: store)++ assert (await sessions.session_store_capabilities()).submission_replacement++ unsupported = SimpleNamespace()++ monkeypatch.setattr(sessions, "get_session_store", lambda: unsupported)++ monkeypatch.setattr(service, "_resolve", lambda: (unsupported, None))++ monkeypatch.setattr(sessions, "_turn_application_service", lambda: service)++ assert not (await sessions.session_store_capabilities()).submission_replacement++ body = sessions.SubmissionReplacementRequest(++ original_submission_id="original",++ request=TurnRequest(content="Edited", client_submission_id="edited"),++ )++ with pytest.raises(HTTPException) as error:++ await sessions.replace_submission(body)++ assert error.value.status_code == 501++ assert calls["count"] == 0diff --cc web/components/reading/workspace/ReadingCompanion.tsxindex 71c75faf6,bb4f210a9..721507c06--- a/web/components/reading/workspace/ReadingCompanion.tsx+++ b/web/components/reading/workspace/ReadingCompanion.tsx@@@ -104,10 -105,10 +104,11 @@@ export function ReadingCompanion(state,submitUserReply,regenerateLastMessage,+ resendLastMessage,deleteTurn,- discardFailedSubmission,editMessage,+ discardFailedSubmission,+ retryFailedSubmission,switchBranch,loadMessageTrace,releaseMessageTrace,@@@ -445,12 -445,11 +446,13 @@@language={state.language}onCopyAssistantMessage={copyAssistantMessage}onRegenerateMessage={regenerateLastMessage}+ canResendLastTurn={state.lastTurnFailed}+ onResendLastTurn={resendLastMessage}onDeleteTurn={deleteTurn}- onDiscardFailedSubmission={discardFailedSubmission}selectedBranches={state.selectedBranches}onEditMessage={editMessage}+ onDiscardFailedSubmission={discardFailedSubmission}+ onRetryFailedSubmission={retryFailedSubmission}onSwitchBranch={switchBranch}onSubmitUserReply={submitUserReply}onConfirmOutline={confirmResearchOutline}diff --cc web/components/space/learning/MasteryStudy.tsxindex 79da6ff6b,eb9ac5c0e..2c4c2bdf9--- a/web/components/space/learning/MasteryStudy.tsx+++ b/web/components/space/learning/MasteryStudy.tsx@@@ -181,6 -181,6 +181,7 @@@ export function MasteryStudy(resendLastMessage,deleteTurn,discardFailedSubmission,++ retryFailedSubmission,editMessage,switchBranch,loadMessageTrace,@@@ -809,6 -805,6 +810,7 @@@onResendLastTurn={resendLastMessage}onDeleteTurn={deleteTurn}onDiscardFailedSubmission={discardFailedSubmission}++ onRetryFailedSubmission={retryFailedSubmission}selectedBranches={state.selectedBranches}onEditMessage={editMessage}onSwitchBranch={switchBranch}diff --cc web/contracts/generated/api.tsindex 293db482e,c3b90c648..379d0d7e5--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@@ -7644,6 -7644,6 +7644,26 @@@ export interface pathsreadonly patch?: never;readonly trace?: never;};++ readonly "/api/sessions/capabilities": {++ readonly parameters: {++ readonly query?: never;++ readonly header?: never;++ readonly path?: never;++ readonly cookie?: never;++ };++ /**++ * Session Store Capabilities++ * @description Expose operations the configured store can perform atomically.++ */++ readonly get: operations["session_store_capabilities_api_sessions_capabilities_get"];++ readonly put?: never;++ readonly post?: never;++ readonly delete?: never;++ readonly options?: never;++ readonly head?: never;++ readonly patch?: never;++ readonly trace?: never;++ };readonly "/api/sessions/recycle-bin": {readonly parameters: {readonly query?: never;@@@ -15469,6 -15452,6 +15484,11 @@@ export interface components/** Language */readonly language: string | null;};++ /** SessionStoreCapabilities */++ readonly SessionStoreCapabilities: {++ /** Submission Replacement */++ readonly submission_replacement: boolean;++ };/** SessionSummary */readonly SessionSummary: {/** @default null */@@@ -17616,6 -17621,6 +17658,8 @@@ export type SchemaSessionRenameRequestcomponents["schemas"]["SessionRenameRequest"];export type SchemaSessionReplyLanguageRequest =components["schemas"]["SessionReplyLanguageRequest"];++export type SchemaSessionStoreCapabilities =++ components["schemas"]["SessionStoreCapabilities"];export type SchemaSessionSummary = components["schemas"]["SessionSummary"];export type SchemaSessionTaskLinks = components["schemas"]["SessionTaskLinks"];export type SchemaSetRoleRequest = components["schemas"]["SetRoleRequest"];@@@ -34830,6 -34839,6 +34878,39 @@@ export interface operations};};};++ readonly session_store_capabilities_api_sessions_capabilities_get: {++ readonly parameters: {++ readonly query?: never;++ readonly header?: {++ readonly Authorization?: string | null;++ };++ readonly path?: never;++ readonly cookie?: {++ readonly dt_token?: string | null;++ };++ };++ readonly requestBody?: never;++ readonly responses: {++ /** @description Successful Response */++ readonly 200: {++ headers: {++ readonly [name: string]: unknown;++ };++ content: {++ readonly "application/json": components["schemas"]["SessionStoreCapabilities"];++ };++ };++ /** @description Validation Error */++ readonly 422: {++ headers: {++ readonly [name: string]: unknown;++ };++ content: {++ readonly "application/json": components["schemas"]["HTTPValidationError"];++ };++ };++ };++ };readonly list_recycle_bin_api_sessions_recycle_bin_get: {readonly parameters: {readonly query?: {diff --cc web/contracts/schema/openapi.jsonindex 6e09ca83e,0bdae2815..70cf579a4--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@@ -5958,23 -5958,6 +5958,23 @@@"additionalProperties": false,"description": "An answer submitted from a mastery question card.\n\nThe card outlives the turn that posed it — posing a question ends that\nturn — so the answer arrives as the next turn's message. This says which\nquestion the message is answering, letting the runtime commit it to the\nengine before the tutor's first token instead of asking the model to\nrecover the pairing from prose.","properties": {+ "answers": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "maxProperties": 4,- "minProperties": 2,++ "minProperties": 1,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Answers"+ },"question_id": {"minLength": 1,"title": "Question Id",@@@ -9357,6 -9327,6 +9357,19 @@@"title": "SessionReplyLanguageRequest","type": "object"},++ "SessionStoreCapabilities": {++ "properties": {++ "submission_replacement": {++ "title": "Submission Replacement",++ "type": "boolean"++ }++ },++ "required": [++ "submission_replacement"++ ],++ "title": "SessionStoreCapabilities",++ "type": "object"++ },"SessionSummary": {"additionalProperties": false,"properties": {@@@ -47980,6 -47999,6 +48042,72 @@@]}},++ "/api/sessions/capabilities": {++ "get": {++ "description": "Expose operations the configured store can perform atomically.",++ "operationId": "session_store_capabilities_api_sessions_capabilities_get",++ "parameters": [++ {++ "in": "header",++ "name": "Authorization",++ "required": false,++ "schema": {++ "anyOf": [++ {++ "type": "string"++ },++ {++ "type": "null"++ }++ ],++ "title": "Authorization"++ }++ },++ {++ "in": "cookie",++ "name": "dt_token",++ "required": false,++ "schema": {++ "anyOf": [++ {++ "type": "string"++ },++ {++ "type": "null"++ }++ ],++ "title": "Dt Token"++ }++ }++ ],++ "responses": {++ "200": {++ "content": {++ "application/json": {++ "schema": {++ "$ref": "#/components/schemas/SessionStoreCapabilities"++ }++ }++ },++ "description": "Successful Response"++ },++ "422": {++ "content": {++ "application/json": {++ "schema": {++ "$ref": "#/components/schemas/HTTPValidationError"++ }++ }++ },++ "description": "Validation Error"++ }++ },++ "summary": "Session Store Capabilities",++ "tags": [++ "sessions"++ ]++ }++ },"/api/sessions/recycle-bin": {"get": {"operationId": "list_recycle_bin_api_sessions_recycle_bin_get",diff --cc web/contracts/schema/turn-protocol.jsonindex 9b441492d,540b7abbf..ec6901069--- a/web/contracts/schema/turn-protocol.json+++ b/web/contracts/schema/turn-protocol.json@@@ -239,23 -239,6 +239,23 @@@"additionalProperties": false,"description": "An answer submitted from a mastery question card.\n\nThe card outlives the turn that posed it — posing a question ends that\nturn — so the answer arrives as the next turn's message. This says which\nquestion the message is answering, letting the runtime commit it to the\nengine before the tutor's first token instead of asking the model to\nrecover the pairing from prose.","properties": {+ "answers": {+ "anyOf": [+ {+ "additionalProperties": {+ "type": "string"+ },+ "maxProperties": 4,- "minProperties": 2,++ "minProperties": 1,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Answers"+ },"question_id": {"minLength": 1,"title": "Question Id",diff --cc web/features/chat/ChatStateAdapter.tsxindex 446773fe7,adcd156d5..44d56c09f--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@@ -1,5 -1,5 +1,7 @@@"use client";++import { supportsSubmissionReplacement } from "@/lib/session-api";++import { activeWorkspaceId } from "@/lib/workspace-scope";import {clearFailedSubmission,@@@ -800,41 -804,6 +813,44 @@@ function reducer(state: 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);++ message.failedSubmission && message.failedSubmissionId === action.submissionId && 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)];++ for (const [key, id] of Object.entries(selectedBranches)) {++ if (id === target.id) delete selectedBranches[key];++ }+ 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;@@@ -2993,7 -3018,9 +3052,11 @@@ export function ChatStateAdapterProvide(trackNewSubmission ? randomUuid() : undefined);const persistSubmission = Boolean(submissionId) &&(trackNewSubmission || Boolean(options?.retrySubmissionId));- if (options?.displayUserMessage !== false) {+ const replacesSubmissionId = options?.replacesSubmissionId ?? replaySnapshot?.replacesSubmissionId;++ if (replacesSubmissionId && !(await supportsSubmissionReplacement())) return false;++ if (generation !== runtimeGeneration.current) return false;+ const showSubmission = () => {+ if (options?.displayUserMessage !== false) {dispatch({type: "ADD_USER_MSG",key,@@@ -3573,20 -3648,75 +3684,76 @@@[],);+ const discardFailedSubmission = useCallback((messageId: number): boolean => {+ const currentState = stateRef.current;+ const key = currentState.selectedKey;+ const session = key ? currentState.sessions[key] : undefined;+ if (!key || !session || session.isStreaming) return false;+ const message = session.messages.find((item) => item.id === messageId);+ if (message?.role !== "user" || !message.failedSubmission || messageId >= 0 || !message.failedSubmissionId) return false;+ const storageKey = session.sessionId ?? draftFailedSubmissionKey();+ const rootId = message.requestSnapshot?.replacementRootSubmissionId ?? message.failedSubmissionId;+ const pendingEdits = readFailedSubmissions(storageKey, true).filter((record) => {+ const snapshot = record.requestSnapshot as MessageRequestSnapshot;+ return (snapshot?.replacementRootSubmissionId ?? snapshot?.replacesSubmissionId) === rootId;+ });+ for (const pendingEdit of pendingEdits) {+ if (pendingEdit.submissionId && !clearFailedSubmission(storageKey, pendingEdit.submissionId)) return false;+ }+ if (rootId !== message.failedSubmissionId && !clearFailedSubmission(storageKey, rootId)) return false;- if (!clearFailedSubmission(storageKey, message.failedSubmissionId)) return false;++ if (!clearFailedSubmission(storageKey, message.failedSubmissionId) && !message.failedSubmissionNotSaved) return false;+ dispatch({ type: "DISCARD_FAILED_SUBMISSION", key, messageId, submissionId: message.failedSubmissionId });+ return true;+ }, []);+const editMessage = useCallback(- async (messageId: number, newContent: string) => {+ async (messageId: number, newContent: string): Promise<boolean> => {const generation = runtimeGeneration.current;const trimmed = newContent.trim();- if (!trimmed) return;+ if (!trimmed) return false;const currentState = stateRef.current;const key = currentState.selectedKey;- if (!key) return;+ if (!key) return false;const session = currentState.sessions[key];- if (!session) return;+ if (!session) return false;// Edits create a new branch via a fresh turn — block while one is// already running so we don't queue against an in-flight stream// (matches the delete-turn guard).- if (session.isStreaming) return;+ if (session.isStreaming) return false;+ const local = session.messages.find((message) => message.id === messageId && message.role === "user");+ if (local?.failedSubmission && local.failedSubmissionId && local.requestSnapshot && !local.failedSubmissionNeedsReview) {++ if (!(await supportsSubmissionReplacement()) || generation !== runtimeGeneration.current) return false;+ const rootId = local.requestSnapshot.replacementRootSubmissionId ?? local.failedSubmissionId;+ const pending = readFailedSubmissions(session.sessionId ?? draftFailedSubmissionKey()).find((record) => {+ const snapshot = record.requestSnapshot as MessageRequestSnapshot;+ return (snapshot?.replacementRootSubmissionId ?? snapshot?.replacesSubmissionId) === rootId;+ });+ const sameEdit = pending?.content === trimmed;+ if (pending && !sameEdit) {+ const priorEdit = pending.requestSnapshot as MessageRequestSnapshot;+ if (!priorEdit.replacesSubmissionId || !priorEdit.replacementRequest) return false;+ try {+ // Before chaining another edit, resolve the uncertain predecessor.+ // It might never have reached the server, so replacing its ID alone+ // would leave the original delayed request free to be admitted.+ await replaceSubmission(priorEdit.replacesSubmissionId, priorEdit.replacementRequest);+ if (generation !== runtimeGeneration.current) return false;+ } catch { return false; }+ }+ const snapshot = { ...(sameEdit ? pending.requestSnapshot as MessageRequestSnapshot : local.requestSnapshot), content: trimmed };+ if (!sameEdit) {+ delete snapshot.replacementRequest;+ delete snapshot.replacesSubmissionId;+ }+ return sendMessage(trimmed, undefined, undefined, undefined, undefined, {+ requestSnapshotOverride: snapshot,+ retrySubmissionId: sameEdit ? pending.submissionId : undefined,+ replacesSubmissionId: sameEdit ? (pending.requestSnapshot as MessageRequestSnapshot).replacesSubmissionId : pending?.submissionId ?? local.failedSubmissionId,+ replacementRootSubmissionId: rootId,+ replacedMessageId: messageId,+ parentMessageId: local.parentMessageId != null && local.parentMessageId > 0 ? local.parentMessageId : null,+ });+ }let original: MessageItem | undefined;try {original = await resolvePersistedMessage(@@@ -3618,6 -3751,28 +3788,29 @@@[loadSession, sendMessage],);+ const retryFailedSubmission = useCallback(async (messageId: number): Promise<boolean> => {+ const current = stateRef.current;+ const key = current.selectedKey;+ const session = key ? current.sessions[key] : undefined;+ const message = session?.messages.find((item) => item.id === messageId);+ if (!key || !session || session.isStreaming || !message?.failedSubmission ||+ !message.failedSubmissionId || !message.requestSnapshot || message.failedSubmissionNeedsReview) return false;++ if (message.requestSnapshot.replacesSubmissionId && !(await supportsSubmissionReplacement())) return false;+ const rootId = message.requestSnapshot.replacementRootSubmissionId ?? message.failedSubmissionId;+ const pending = readFailedSubmissions(session.sessionId ?? draftFailedSubmissionKey()).find((record) => {+ const snapshot = record.requestSnapshot as MessageRequestSnapshot;+ return (snapshot?.replacementRootSubmissionId ?? snapshot?.replacesSubmissionId) === rootId;+ });+ if (pending && pending.submissionId !== message.failedSubmissionId) return editMessage(messageId, pending.content);+ // Move this exact local row to the active tail while retaining its causal+ // ID; retrying an older draft must never resend the newest row instead.+ dispatch({ type: "DISCARD_FAILED_SUBMISSION", key, messageId, submissionId: message.failedSubmissionId });+ return sendMessage(message.content, undefined, undefined, undefined, undefined, {+ requestSnapshotOverride: message.requestSnapshot, retrySubmissionId: message.failedSubmissionId,+ parentMessageId: message.parentMessageId != null && message.parentMessageId > 0 ? message.parentMessageId : null,+ });+ }, [sendMessage, editMessage]);+const switchBranch = useCallback((parentMessageId: number | null, childId: number) => {const currentState = stateRef.current;diff --cc web/features/chat/messages/ChatMessageList.tsxindex c1bae7902,9c3a8a6fc..c8e93ef37--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@@ -113,7 -110,7 +113,7 @@@ import} from "@/features/chat/trace/TracePresentation";import { hasSettledFinalRound } from "@/features/chat/trace/selectors";import type { MessageTraceMetadata } from "@/features/chat/trace/memory";--import type { OrphanedFailedTurn } from "@/lib/session-api";++import { supportsSubmissionReplacement, type OrphanedFailedTurn } from "@/lib/session-api";import { agentGlyph } from "@/components/agents/agent-icons";import { useConsultationReference } from "@/hooks/useConsultationReference";import { useConnectedAgentKinds } from "@/hooks/useConnectedAgentKinds";@@@ -1621,14 -1604,26 +1626,36 @@@ export const UserMessage = memo(functio// reference chip can badge it with the agent's brand icon.const agentKinds = useConnectedAgentKinds();const consultation = useConsultationReference(msg.requestSnapshot?.config);-- if (msg.content.startsWith("[Quiz Performance]")) return null;// ``msg.id`` can be a negative client-side sentinel for optimistic// (just-sent, not yet reconciled with the server) rows. We still allow// the Edit button to surface — ``editMessage`` in the context handles// the optimistic case by triggering a session reload to resolve the// real id before submitting the branch.++ const [replacementAvailable, setReplacementAvailable] = useState(false);++ const needsReplacement = Boolean(msg.failedSubmission && onEdit);++ useEffect(() => {++ if (!needsReplacement) return;++ let active = true;++ void supportsSubmissionReplacement().then(value => {++ if (active) setReplacementAvailable(value);++ });++ return () => { active = false; };++ }, [needsReplacement]);++ if (msg.content.startsWith("[Quiz Performance]")) return null;const canEdit =- Boolean(onEdit) && typeof msg.id === "number" && !editDisabled && !msg.failedSubmission;- Boolean(onEdit) && typeof msg.id === "number" && !editDisabled;++ Boolean(onEdit) && typeof msg.id === "number" && !editDisabled && (!msg.failedSubmission || replacementAvailable);+ const discardDraft = async () => {+ if (!onDiscardFailedSubmission || typeof msg.id !== "number" || editDisabled || discarding) return;+ setDiscarding(true);+ setDiscardFailed(false);+ try {+ if (!await onDiscardFailedSubmission(msg.id)) setDiscardFailed(true);+ } catch {+ setDiscardFailed(true);+ } finally {+ setDiscarding(false);+ }+ };const startEdit = () => {if (!canEdit) return;setDraft(msg.content);@@@ -1857,19 -1865,18 +1896,18 @@@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" />- <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>+ {t("Not sent")}- {onRetryFailedSubmission && typeof msg.id === "number" && (++ {onRetryFailedSubmission && !msg.failedSubmissionNeedsReview && typeof msg.id === "number" && (+ <button type="button" disabled={editDisabled || retrying} onClick={async () => {+ if (retrying || typeof msg.id !== "number") return;+ setRetrying(true);+ try { await onRetryFailedSubmission(msg.id); } finally { setRetrying(false); }+ }} className="ml-2 rounded-md px-2 py-1 disabled:opacity-40">{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 type="button" onClick={() => void discardDraft()} disabled={editDisabled || discarding}+ className="ml-2 rounded-md px-2 py-1 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)]/50 disabled:cursor-not-allowed disabled:opacity-40">+ {discarding ? t("Discarding…") : t("Discard unsent draft")}</button>)}</div>diff --cc web/lib/auth.tsindex e12194021,d548cfb3e..1e1b83761--- a/web/lib/auth.ts+++ b/web/lib/auth.ts@@@ -1,4 -1,5 +1,6 @@@++import { browserStorage } from "@/shared/storage";import { apiFetch, apiUrl, setRuntimeAuthEnabled } from "@/lib/api";+ import { updateRecoveryPrincipal } from "@/lib/recovery-principal";// Auth state is resolved at runtime from the backend (`/api/auth/status`),// not from a build-time/env constant: the browser bundle never sees@@@ -38,8 -42,28 +43,28 @@@ let cachedAuthStatus: { value: AuthStatnull;export function invalidateAuthStatusCache(): void {+ authGeneration += 1;authStatusRequest = null;cachedAuthStatus = null;+ updateRecoveryPrincipal(null);+ }++ function broadcastAuthBoundary(): void {+ // Notify other tabs to re-check the server, never convey/trust a principal+ // through shared browser storage. No private recovery records are deleted.+ if (typeof window === "undefined") return;- try { window.localStorage.setItem(AUTH_BOUNDARY_KEY, `${Date.now()}:${Math.random()}`); }++ try { browserStorage.writeRaw("local", AUTH_BOUNDARY_KEY, `${Date.now()}:${Math.random()}`); }+ catch { /* Storage may be unavailable; this tab still fails closed. */ }+ }++ function listenForAuthBoundary(): void {+ if (boundaryListenerInstalled || typeof window === "undefined") return;+ boundaryListenerInstalled = true;+ window.addEventListener("storage", (event) => {+ if (event.key !== AUTH_BOUNDARY_KEY) return;+ invalidateAuthStatusCache();+ void fetchAuthStatus();+ });}/**diff --cc web/lib/session-api.tsindex 49090b946,d31c9d8aa..f3659e4cd--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@@ -6,6 -5,6 +6,19 @@@ import { invalidateClientCache, withCliimport type { LLMSelection, StreamEvent } from "@/features/chat/model/protocol";import { browserReturnPath, loginHref } from "@/shared/auth/return-url";++/** Fail closed when the configured backend cannot fence an uncertain send. */++export async function supportsSubmissionReplacement(): Promise<boolean> {++ try {++ return await withClientCache("session-store-capabilities", async () => {++ const response = await apiFetch(apiUrl(scopedUrl("/api/sessions/capabilities")));++ if (!response.ok) throw new Error("Session capabilities unavailable");++ const capabilities: unknown = await response.json();++ return typeof capabilities === "object" && capabilities !== null &&++ "submission_replacement" in capabilities && capabilities.submission_replacement === true;++ });++ } catch { return false; }++}++export interface SessionMessage {id: number;session_id: string;diff --cc web/locales/de/app.jsonindex a1d77b2bb,60ad77103..62d0c9b30--- a/web/locales/de/app.json+++ b/web/locales/de/app.json@@@ -1,6 -1,8 +1,10 @@@{+ "Partially correct": "Teilweise richtig",+ "These answers could not be submitted. Please review or retry.": "Diese Antworten konnten nicht übermittelt werden. Bitte prüfen und erneut versuchen.",+ "The edit could not be sent. Your draft is still here; please retry.": "Die Änderung konnte nicht gesendet werden. Dein Entwurf ist noch hier; bitte versuche es erneut.",+ "Discard unsent draft": "Nicht gesendeten Entwurf verwerfen",+ "Discarding…": "Wird verworfen…",+ "This draft could not be discarded. Please retry or copy it before leaving.": "Dieser Entwurf konnte nicht verworfen werden. Bitte versuche es erneut oder kopiere ihn, bevor du die Seite verlässt.","Review rebuild": "Neuaufbau überprüfen","language.english": "Englisch","language.chinese": "Chinesisch",diff --cc web/locales/en/app.jsonindex bec657d88,466ce83ab..7b2f05434--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -1,6 -1,8 +1,10 @@@{+ "Partially correct": "Partially correct",+ "These answers could not be submitted. Please review or retry.": "These answers could not be submitted. Please review or retry.",+ "The edit could not be sent. Your draft is still here; please retry.": "The edit could not be sent. Your draft is still here; please retry.",+ "Discard unsent draft": "Discard unsent draft",+ "Discarding…": "Discarding…",+ "This draft could not be discarded. Please retry or copy it before leaving.": "This draft could not be discarded. Please retry or copy it before leaving.","Review rebuild": "Review rebuild","language.english": "English","language.chinese": "中文",diff --cc web/locales/fr/app.jsonindex 5443907c4,3afbf9e82..e0f5eb00a--- a/web/locales/fr/app.json+++ b/web/locales/fr/app.json@@@ -1,6 -1,8 +1,10 @@@{+ "Partially correct": "Partiellement correct",+ "These answers could not be submitted. Please review or retry.": "Ces réponses n’ont pas pu être envoyées. Veuillez les vérifier ou réessayer.",+ "The edit could not be sent. Your draft is still here; please retry.": "La modification n’a pas pu être envoyée. Votre brouillon est conservé ; réessayez.",+ "Discard unsent draft": "Supprimer le brouillon non envoyé",+ "Discarding…": "Suppression…",+ "This draft could not be discarded. Please retry or copy it before leaving.": "Ce brouillon n’a pas pu être supprimé. Réessayez ou copiez-le avant de quitter cette page.","language.english": "English","language.chinese": "中文","language.french": "Français",diff --cc web/locales/pl/app.jsonindex e3e00b578,ab05e69ab..7b7b81c31--- a/web/locales/pl/app.json+++ b/web/locales/pl/app.json@@@ -1,6 -1,8 +1,10 @@@{+ "Partially correct": "Częściowo poprawna odpowiedź",+ "These answers could not be submitted. Please review or retry.": "Nie udało się przesłać tych odpowiedzi. Sprawdź je lub spróbuj ponownie.",+ "The edit could not be sent. Your draft is still here; please retry.": "Nie udało się wysłać zmiany. Szkic został zachowany; spróbuj ponownie.",+ "Discard unsent draft": "Usuń niewysłany szkic",+ "Discarding…": "Usuwanie…",+ "This draft could not be discarded. Please retry or copy it before leaving.": "Nie udało się usunąć tego szkicu. Spróbuj ponownie lub skopiuj go przed opuszczeniem strony.","Review rebuild": "Przegląd przebudowy","language.english": "Angielski","language.chinese": "中文",diff --cc web/locales/uk/app.jsonindex 0989832e8,4de06ee49..87c30d86c--- a/web/locales/uk/app.json+++ b/web/locales/uk/app.json@@@ -1,6 -1,8 +1,10 @@@{+ "Partially correct": "Частково правильно",+ "These answers could not be submitted. Please review or retry.": "Не вдалося надіслати ці відповіді. Перевірте їх або спробуйте ще раз.",+ "The edit could not be sent. Your draft is still here; please retry.": "Не вдалося надіслати зміни. Чернетку збережено; спробуйте ще раз.",+ "Discard unsent draft": "Видалити ненадіслану чернетку",+ "Discarding…": "Видалення…",+ "This draft could not be discarded. Please retry or copy it before leaving.": "Не вдалося видалити цю чернетку. Спробуйте ще раз або скопіюйте її перед виходом.","language.english": "Англійська","language.chinese": "Китайська","language.french": "Français",diff --cc web/locales/zh/app.jsonindex 2f9179b3f,1306afdf9..66791710c--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -1,6 -1,8 +1,10 @@@{+ "Partially correct": "部分正确",+ "These answers could not be submitted. Please review or retry.": "这些答案未能提交。请检查后重试。",+ "The edit could not be sent. Your draft is still here; please retry.": "修改未能发送。草稿仍保留在此,请重试。",+ "Discard unsent draft": "丢弃未发送的草稿",+ "Discarding…": "正在丢弃…",+ "This draft could not be discarded. Please retry or copy it before leaving.": "无法丢弃此草稿。请重试,或在离开前复制内容。","Review rebuild": "查看重建配置","language.english": "English","language.chinese": "中文",diff --cc web/tests/chat-failed-submission-recovery.spec.tsxindex fd7be419c,a40d714e4..7b6d9b60e--- a/web/tests/chat-failed-submission-recovery.spec.tsx+++ b/web/tests/chat-failed-submission-recovery.spec.tsx@@@ -5,8 -5,8 +5,9 @@@ importChatStateAdapterProvider,useChatStateAdapter,} from "@/features/chat/ChatStateAdapter";+import { buildVisiblePath } from "@/lib/message-branches";import { initI18n } from "@/i18n/init";+ import { updateRecoveryPrincipal } from "@/lib/recovery-principal";import {resetReadingTurnState, setReadingMaterial, setReadingViewport,setReadingWorkspace,@@@ -34,6 -35,10 +36,11 @@@ const fixture = vi.hoisted(() => (emit: undefined as undefined | ((event: Record<string, unknown>) => void),close: undefined as undefined | (() => void),session: undefined as undefined | Record<string, unknown>,+ replacementCalls: [] as Array<{ original: string; request: Record<string, unknown> }>,++ replacementSupported: true,+ replacementFails: false,+ replacementFailureAt: 0,+ replacementPending: null as Promise<void> | null,}));vi.mock("@/features/chat/transport/UnifiedTurnClient", () => ({@@@ -62,6 -67,13 +69,14 @@@}));vi.mock("@/lib/session-api", () => ({++ supportsSubmissionReplacement: async () => fixture.replacementSupported,+ replaceSubmission: async (original: string, request: Record<string, unknown>) => {+ fixture.replacementCalls.push({ original, request: { ...request } });+ if (fixture.replacementPending) await fixture.replacementPending;+ if (fixture.replacementFails || fixture.replacementFailureAt === fixture.replacementCalls.length) throw new Error("lost recovery receipt");+ return { status: "started", session_id: "s1", submission_id: request.client_submission_id,+ turn: { id: "edited-turn", status: "running" } };+ },getSession: async (sessionId: string) => {if (!fixture.session) throw new Error("no fixture session configured");return {@@@ -232,12 -268,237 +284,239 @@@ beforeEach(() =>resetReadingTurnState();fixture.connected = false;fixture.sent = [];+ fixture.deleted = [];fixture.emit = undefined;fixture.close = undefined;+ fixture.replacementCalls = [];+ fixture.replacementFails = false;++ fixture.replacementSupported = true;+ fixture.replacementFailureAt = 0;+ fixture.replacementPending = null;});afterEach(() => vi.restoreAllMocks());+ it("drops account A's visible drafts and stale runner events while preserving A's recovery data", async () => {+ updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "a" });+ storeFailedSubmission("draft:general", { submissionId: "a-draft", content: "A private draft",+ requestSnapshot: { content: "A private draft" } });+ fixture.connected = true;+ render(<ChatStateAdapterProvider><BootstrapDraft /><Harness /></ChatStateAdapterProvider>);+ expect(readMessages().map((message) => message.content)).toEqual(["A private draft"]);+ await act(async () => fireEvent.click(screen.getByText("Send another")));+ const oldEmit = fixture.emit;+ await act(async () => updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "b" }));+ expect(readMessages()).toEqual([]);+ await act(async () => oldEmit?.({ type: "session", session_id: "s1" }));+ expect(readMessages()).toEqual([]);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ await act(async () => updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "a" }));+ expect(readMessages().some((message) => message.content === "A private draft")).toBe(true);+ });++ it("ignores an old account's replacement receipt after a principal switch", async () => {+ updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "a" });+ fixture.session = completedServerSession();+ fixture.connected = true;+ seedUnsentSubmission("A private draft");+ let release!: () => void;+ fixture.replacementPending = new Promise<void>((resolve) => { release = resolve; });+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ await act(async () => fireEvent.click(screen.getByText("Edit first unsent")));+ expect(fixture.replacementCalls).toHaveLength(1);+ await act(async () => updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "b" }));+ await act(async () => release());+ expect(readMessages()).toEqual([]);+ expect(fixture.sent).toEqual([]);+ expect(readFailedSubmissions("s1")).toEqual([]);+ await act(async () => updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "a" }));+ expect(readFailedSubmissions("s1")[0].content).toBe("Edited offline");+ });++ it("durably edits an unsent message with its original attachment and request scope", async () => {+ fixture.session = completedServerSession();+ fixture.connected = true;+ storeFailedSubmission("s1", { submissionId: "original-edit", content: "Original", requestSnapshot: {+ content: "Original", capability: "chat", language: "en", enabledTools: ["reason"], knowledgeBases: ["original-kb"],+ attachments: [{ type: "image", base64: "YWJj", filename: "source.png" }],+ } });+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ await act(async () => fireEvent.click(screen.getByText("Edit first unsent")));+ expect(fixture.replacementCalls).toHaveLength(1);+ expect(fixture.replacementCalls[0].original).toBe("original-edit");+ const command = fixture.replacementCalls[0].request;+ expect(command).toMatchObject({ content: "Edited offline", knowledge_bases: ["original-kb"], tools: ["reason"],+ attachments: [{ type: "image", base64: "YWJj", filename: "source.png" }] });+ expect(command.client_submission_id).not.toBe("original-edit");+ expect(fixture.sent).toEqual([{ type: "subscribe_turn", turn_id: "edited-turn", after_seq: 0 }]);+ expect(readFailedSubmissions("s1")).toHaveLength(1);+ expect(readMessages().filter((message) => message.role === "user" && message.content.includes("offline"))).toHaveLength(1);+ });++ it("replays the same edit reservation after a lost recovery receipt and reload", async () => {+ fixture.session = completedServerSession();+ fixture.connected = true;+ fixture.replacementFails = true;+ seedUnsentSubmission();+ const first = render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ await act(async () => fireEvent.click(screen.getByText("Edit first unsent")));+ const originalRequest = fixture.replacementCalls[0].request;+ expect(fixture.sent).toHaveLength(0);+ expect(readFailedSubmissions("s1")).toHaveLength(1);+ first.unmount();+ fixture.replacementFails = false;++ fixture.replacementSupported = true;+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ await act(async () => fireEvent.click(screen.getByText("Retry first unsent")));+ expect(fixture.replacementCalls[1].request).toEqual(originalRequest);+ expect(fixture.sent).toEqual([{ type: "subscribe_turn", turn_id: "edited-turn", after_seq: 0 }]);+ });++ it("resolves an uncertain predecessor before chaining an edit and retries the latest leaf", async () => {+ fixture.session = completedServerSession();+ fixture.connected = true;+ fixture.replacementFailureAt = 1;+ seedUnsentSubmission();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ await act(async () => fireEvent.click(screen.getByText("Edit first unsent")));+ fixture.replacementFailureAt = 3;+ await act(async () => fireEvent.click(screen.getByText("Edit second version")));+ expect(fixture.replacementCalls).toHaveLength(3);+ expect(fixture.replacementCalls[1]).toEqual(fixture.replacementCalls[0]);+ expect(fixture.replacementCalls[2].original).toBe(fixture.replacementCalls[0].request.client_submission_id);+ expect(readFailedSubmissions("s1")).toHaveLength(1);+ expect(readFailedSubmissions("s1")[0].content).toBe("Second edit");+ await act(async () => fireEvent.click(screen.getByText("Retry first unsent")));+ expect(fixture.replacementCalls[3]).toEqual(fixture.replacementCalls[2]);+ });++ it("does not fence the original when only a text fallback of the edited request fits", async () => {+ fixture.session = completedServerSession();+ fixture.connected = true;+ seedUnsentSubmission();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ for (const storage of [localStorage, sessionStorage]) {+ const write = storage.setItem.bind(storage);+ vi.spyOn(storage, "setItem").mockImplementation((key, value) => {+ if (value.includes("replacementRequest")) throw new Error("Full edit exceeds quota");+ write(key, value);+ });+ }+ await act(async () => fireEvent.click(screen.getByText("Edit first unsent")));+ expect(fixture.replacementCalls).toHaveLength(0);+ expect(fixture.sent).toHaveLength(0);+ expect(readMessages().at(-1)?.content).toBe("Hello offline");+ expect(readFailedSubmissions("s1").some((record) => record.content === "Hello offline")).toBe(true);+ });++ it("discards only the local unsent shadow and does not resurrect it after reload", async () => {+ fixture.session = completedServerSession();+ seedUnsentSubmission();+ fixture.connected = true;+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ expect(readMessages().at(-1)).toMatchObject({ content: "Hello offline", failed: true });+ await act(async () => fireEvent.click(screen.getByText("Discard unsent")));+ expect(readMessages().map((message) => message.content)).toEqual(["hi", "hello"]);+ expect(fixture.sent).toHaveLength(0);+ expect(fixture.deleted).toHaveLength(0);+ expect(readFailedSubmissions("s1")).toEqual([]);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ expect(readMessages().map((message) => message.content)).toEqual(["hi", "hello"]);+ });++ it("discards one of two drafts without dropping history or breaking the remaining branch", async () => {+ fixture.session = completedServerSession();+ storeFailedSubmission("s1", { submissionId: "draft-a", content: "First local draft", requestSnapshot: { content: "First local draft" } });+ storeFailedSubmission("s1", { submissionId: "draft-b", content: "Second local draft", requestSnapshot: { content: "Second local draft" } });+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ await act(async () => fireEvent.click(screen.getByText("Select unsent branch")));+ const before = JSON.parse(screen.getByTestId("references").textContent!);+ const removed = before.messages.find((message: { content: string }) => message.content === "First local draft");+ const survivor = before.messages.find((message: { content: string }) => message.content === "Second local draft");+ expect(before.selectedBranches[String(removed.id)]).toBe(survivor.id);+ await act(async () => fireEvent.click(screen.getByText("Discard first unsent")));+ const after = JSON.parse(screen.getByTestId("references").textContent!);+ expect(after.messages.map((message: { content: string }) => message.content)).toEqual(["hi", "hello", "Second local draft"]);+ expect(after.messages.at(-1).parentMessageId).toBe(2);+ expect(after.selectedBranches["2"]).toBe(survivor.id);+ expect(after.selectedBranches[String(removed.id)]).toBeUndefined();+ expect(readFailedSubmissions("s1").map((record) => record.submissionId)).toEqual(["draft-b"]);+ expect(fixture.sent).toHaveLength(0);+ expect(fixture.deleted).toHaveLength(0);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ expect(readMessages().map((message) => message.content)).toEqual(["hi", "hello", "Second local draft"]);+ });++ it("keeps the recovery copy visible when neither storage can save its retirement", async () => {+ fixture.session = completedServerSession();+ seedUnsentSubmission();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ vi.spyOn(localStorage, "setItem").mockImplementation(() => { throw new Error("unavailable storage"); });+ vi.spyOn(sessionStorage, "setItem").mockImplementation(() => { throw new Error("unavailable storage"); });+ await act(async () => fireEvent.click(screen.getByText("Discard unsent")));+ expect(screen.getByTestId("discardResult")).toHaveTextContent("false");+ expect(readMessages().at(-1)).toMatchObject({ content: "Hello offline", failed: true });+ expect(readFailedSubmissions("s1")).toHaveLength(1);+ expect(fixture.deleted).toHaveLength(0);+ expect(fixture.sent).toHaveLength(0);+ });++ it("retires a moved draft's bound source as well as its visible target copy", () => {+ const id = storeFailedSubmission("draft:general", { content: "Bound draft", requestSnapshot: { content: "Bound draft" } })!;+ const setItem = localStorage.setItem.bind(localStorage);+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ if (key.startsWith("deeptutor.failedSubmissions.owner.single-user.record.s1:")) throw new Error("target quota");+ setItem(key, value);+ });+ expect(moveFailedSubmissions("draft:general", "s1", [id])).toEqual([id]);+ expect(readFailedSubmissions("s1")).toHaveLength(1);+ expect(clearFailedSubmission("s1", id)).toBe(true);+ expect(readFailedSubmissions("s1")).toEqual([]);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ });++ it("does not erase a detectable same-ID retry advanced during retirement", () => {+ const id = storeFailedSubmission("s1", { submissionId: "retry-id", content: "Pending copy",+ requestSnapshot: { content: "Pending copy" } })!;+ const before = readFailedSubmissions("s1")[0].savedAt;+ const setItem = localStorage.setItem.bind(localStorage);+ let advanced = false;+ vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {+ setItem(key, value);+ if (!advanced && key === "deeptutor.failedSubmissions.owner.single-user.cleared.s1:retry-id") {+ advanced = true;+ storeFailedSubmission("s1", { submissionId: id, content: "Pending copy",+ requestSnapshot: { content: "Pending copy" } });+ }+ });+ expect(clearFailedSubmission("s1", id)).toBe(false);+ expect(advanced).toBe(true);+ expect(readFailedSubmissions("s1")).toHaveLength(1);+ expect(readFailedSubmissions("s1")[0].savedAt).toBeGreaterThan(before);+ });++ it("preserves a stopped-before-admission draft across reload", async () => {+ fixture.session = completedServerSession();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => fireEvent.click(screen.getByText("Load")));+ fireEvent.click(screen.getByText("Send"));+ fireEvent.click(screen.getByText("Stop"));+ expect(readMessages().at(-1)).toMatchObject({ content: "Hello offline", failed: true });+ await act(async () => fireEvent.click(screen.getByText("Load")));+ expect(readMessages().at(-1)).toMatchObject({ content: "Hello offline", failed: true });+ expect(readFailedSubmissions("s1")).toHaveLength(1);+ expect(fixture.sent).toHaveLength(0);+ });+it("tracks attachment-only submissions with a stable identity for resend", async () => {fixture.connected = true;render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);@@@ -1194,170 -1455,3 +1473,186 @@@ it("resubscribes a parked ask_user turfixture.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({++it("leaves unowned legacy drafts quarantined across session reloads", async () => {++ const legacy = JSON.stringify({+ s1: { content: "legacy unsent", capability: "chat", requestSnapshot: {}, savedAt: Date.now() },- }));++ });++ localStorage.setItem("deeptutor.failedSubmissions", legacy);+ 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"));++ expect(readMessages().map(message => message.content)).toEqual(["hi", "hello"]);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ expect(readFailedSubmissions("s1")).toEqual([]);+ expect(readMessages().map(message => message.content)).toEqual(["hi", "hello"]);++ expect(localStorage.getItem("deeptutor.failedSubmissions")).toBe(legacy);+});++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");+});+++it("keeps the recovery row visible when browser storage cannot record its dismissal", async () => {+ seedUnsentSubmission();+ fixture.session = completedServerSession();+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);+ await act(async () => { fireEvent.click(screen.getByText("Load")); });+ for (const storage of [localStorage, sessionStorage]) {+ for (const method of ["setItem", "removeItem"] as const) {+ vi.spyOn(storage, method).mockImplementation(() => {+ throw new DOMException("Unavailable", "SecurityError");+ });+ }+ }+ await act(async () => { fireEvent.click(screen.getByText("Discard first")); });+ expect(readFailedSubmissions("s1")).toHaveLength(1);+ expect(readMessages().some(message => message.failed)).toBe(true);+});++++++it("preserves an original unsent draft when the backend lacks atomic replacement", async () => {++ fixture.session = completedServerSession();++ fixture.replacementSupported = false;++ seedUnsentSubmission("Original unsupported draft");++ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);++ await act(async () => fireEvent.click(screen.getByText("Load")));++ const before = readFailedSubmissions("s1");++ await act(async () => fireEvent.click(screen.getByText("Edit first unsent")));++ expect(fixture.replacementCalls).toEqual([]);++ expect(fixture.sent).toEqual([]);++ expect(readFailedSubmissions("s1")).toEqual(before);++ expect(readMessages().some(message => message.content === "Original unsupported draft")).toBe(true);++});diff --cc web/tests/chat-unsent-message-actions.spec.tsxindex 000000000,048b221c2..e840ce2bcmode 000000,100644..100644--- a/web/tests/chat-unsent-message-actions.spec.tsx+++ b/web/tests/chat-unsent-message-actions.spec.tsx@@@ -1,0 -1,93 +1,113 @@@+ import { act, render, screen, within } from "@testing-library/react";+ import userEvent from "@testing-library/user-event";-import { expect, it, vi } from "vitest";++import { beforeEach, expect, it, vi } from "vitest";++ import { ChatMessageList } from "@/features/chat/messages";+ import { initI18n } from "@/i18n/init";+++const supported = vi.hoisted(() => vi.fn(async () => true));++vi.mock("@/lib/session-api", async importOriginal => ({++ ...await importOriginal<typeof import("@/lib/session-api")>(),++ supportsSubmissionReplacement: supported,++}));++beforeEach(() => supported.mockResolvedValue(true));+++ initI18n("en");++ const messages = [+ { id: 1, role: "assistant" as const, content: "Earlier response", parentMessageId: null },+ { id: -2, role: "user" as const, content: "First unsent draft", parentMessageId: 1,+ failedSubmission: true, failedSubmissionId: "draft-one" },+ { id: -3, role: "user" as const, content: "Second unsent draft", parentMessageId: -2,+ failedSubmission: true, failedSubmissionId: "draft-two" },+ ];++ it("offers per-draft local discard, without requiring an assistant placeholder", async () => {+ const user = userEvent.setup();+ const discard = vi.fn(() => true);+ const { container } = render(<ChatMessageList messages={messages} isStreaming={false}+ onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined}+ {...{ onDiscardFailedSubmission: discard }} />);+ const first = within(container.querySelector('[data-chat-message-id="-2"]') as HTMLElement);+ const second = within(container.querySelector('[data-chat-message-id="-3"]') as HTMLElement);+ await user.click(first.getByRole("button", { name: "Discard unsent draft" }));+ expect(discard).toHaveBeenCalledExactlyOnceWith(-2);+ await user.click(second.getByRole("button", { name: "Discard unsent draft" }));+ expect(discard.mock.calls).toEqual([[-2], [-3]]);+ });+-it("offers editing for unsent local drafts through the recovery handler", () => {++it("offers editing for unsent local drafts through the recovery handler", async () => {+ render(<ChatMessageList messages={messages.slice(0, 2)} isStreaming={false}+ onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined}+ onEditMessage={() => undefined} />);- expect(screen.getByRole("button", { name: "Edit" })).toBeInTheDocument();++ expect(await screen.findByRole("button", { name: "Edit" })).toBeInTheDocument();+ expect(screen.getByText("First unsent draft")).toBeInTheDocument();+ });++ it("retains the editor text until the asynchronous edit succeeds", async () => {+ const user = userEvent.setup();+ let complete!: (value: boolean) => void;+ const edit = vi.fn(() => new Promise<boolean>((resolve) => { complete = resolve; }));+ render(<ChatMessageList messages={messages.slice(0, 2)} isStreaming={false}+ onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined} onEditMessage={edit} />);- await user.click(screen.getByRole("button", { name: "Edit" }));++ await user.click(await screen.findByRole("button", { name: "Edit" }));+ await user.clear(screen.getByRole("textbox"));+ await user.type(screen.getByRole("textbox"), "Corrected draft");+ await user.click(screen.getByRole("button", { name: "Send" }));+ expect(screen.getByRole("textbox")).toHaveValue("Corrected draft");+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();+ await act(async () => { complete(false); });+ await vi.waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("edit could not be sent"));+ expect(screen.getByRole("textbox")).toHaveValue("Corrected draft");+ expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();+ });++ it("retries the selected unsent row rather than the tail", async () => {+ const user = userEvent.setup();+ const retry = vi.fn(async () => true);+ const { container } = render(<ChatMessageList messages={messages} isStreaming={false}+ onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined} onRetryFailedSubmission={retry} />);+ const first = within(container.querySelector('[data-chat-message-id="-2"]') as HTMLElement);+ await user.click(first.getByRole("button", { name: "Retry" }));+ expect(retry).toHaveBeenCalledExactlyOnceWith(-2);+ });++ it("retains the visible copy and reports a failed discard", async () => {+ const user = userEvent.setup();+ const discard = vi.fn(async () => false);+ render(<ChatMessageList messages={messages.slice(0, 2)} isStreaming={false}+ onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined}+ {...{ onDiscardFailedSubmission: discard }} />);+ await user.click(screen.getByRole("button", { name: "Discard unsent draft" }));+ await vi.waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("could not be discarded"));+ expect(screen.getByText("First unsent draft")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Discard unsent draft" })).toBeEnabled();+ });++ it("leaves ordinary persisted edit available and does not offer local discard for it", () => {+ render(<ChatMessageList messages={[{ id: 2, role: "user", content: "Sent message", parentMessageId: null }]}+ isStreaming={false} onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined}+ onEditMessage={() => undefined} {...{ onDiscardFailedSubmission: () => true }} />);+ expect(screen.getByRole("button", { name: "Edit" })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Discard unsent draft" })).toBeNull();+ });++ it("does not discard while a turn is being submitted", () => {+ render(<ChatMessageList messages={messages.slice(0, 2)} isStreaming+ onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined}+ {...{ onDiscardFailedSubmission: () => true }} />);+ expect(screen.getByRole("button", { name: "Discard unsent draft" })).toBeDisabled();+ });++++++it("keeps retry and discard but hides draft editing on unsupported backends", async () => {++ supported.mockResolvedValue(false);++ render(<ChatMessageList messages={messages.slice(0, 2)} isStreaming={false}++ onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined}++ onEditMessage={() => undefined} onRetryFailedSubmission={async () => true}++ onDiscardFailedSubmission={() => true} />);++ await act(async () => {});++ expect(screen.queryByRole("button", { name: "Edit" })).toBeNull();++ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();++ expect(screen.getByRole("button", { name: "Discard unsent draft" })).toBeEnabled();++});diff --cc web/tests/question-card-assessment.test.tsindex f11357302,f11357302..9aa20cf72--- a/web/tests/question-card-assessment.test.ts+++ b/web/tests/question-card-assessment.test.ts@@@ -2,6 -2,6 +2,7 @@@ import assert from "node:assert/strict"import { readFileSync } from "node:fs";import path from "node:path";import test from "node:test";++import { questionResultBadge } from "../lib/question-bank-answers";const card = readFileSync(path.resolve(process.cwd(), "components/space/question-bank/QuestionCard.tsx"),@@@ -17,10 -17,10 +18,11 @@@ const chinese = readFileSync);test("question cards distinguish partial and ungraded results", () => {-- assert.match(card, /Partially Correct/);-- assert.match(card, /Not Graded/);-- assert.match(card, /result === "partial"/);-- assert.match(card, /result === "ungraded"/);++ for (const is_correct of [true, false]) {++ assert.equal(questionResultBadge({ result: "partial", is_correct }).label, "Partially Correct");++ assert.equal(questionResultBadge({ result: "ungraded", is_correct }).label, "Not Graded");++ }++ assert.match(card, /questionResultBadge\(entry\)/);assert.match(card, /isUserAnswer && result === "incorrect"/);assert.match(card, /result === "incorrect"\s*\? "wrong"/);assert.match(card, /ASSESSMENT_TYPE_LABELS/);