DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): durably replace uncertain submissions and isolate recovery owners
yepyhunf986774b872f
diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.pyindex 2f88caff8..7c3cdbda1 100644--- a/deeptutor/api/routers/sessions.py+++ b/deeptutor/api/routers/sessions.py@@ -12,6 +12,7 @@ from typing import Any, Literalfrom fastapi import APIRouter, HTTPException, Query, Requestfrom pydantic import BaseModel, Field, field_validator+from deeptutor.core.turn_request import TurnRequestfrom deeptutor.learning.storage import LearningStorefrom deeptutor.reading.catalog_store import ReadingCatalogStorefrom deeptutor.response_languages import validate_reply_language_override@@ -38,6 +39,29 @@ def _turn_application_service():return get_application_container().turns+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]++[email protected]("/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 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 --git a/deeptutor/app/service.py b/deeptutor/app/service.pyindex b81fb02cf..8acec1c7b 100644--- a/deeptutor/app/service.py+++ b/deeptutor/app/service.py@@ -19,6 +19,82 @@ from .contracts import TurnRequestclass 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.")+ 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,@@ -59,14 +135,7 @@ class TurnApplicationService:and callable(reserve)and callable(submission_turn)):- identity_payload = {- key: value- for key, value in payload.items()- if key not in {"session_id", "workspace_id"}- }- digest = hashlib.sha256(- json.dumps(identity_payload, sort_keys=True, default=str).encode()- ).hexdigest()+ digest = self._submission_digest(payload)payload["session_id"] = await reserve(request.client_submission_id, digest, request.session_id)diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex e26881b7c..3dc8b9ac0 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -472,6 +472,11 @@ class SQLiteSessionStore:);""")+ submission_columns = {+ row[1] for row in conn.execute("PRAGMA table_info(turn_submissions)")+ }+ if "superseded_by" not in submission_columns:+ conn.execute("ALTER TABLE turn_submissions ADD COLUMN superseded_by TEXT")columns = {row[1] for row in conn.execute("PRAGMA table_info(sessions)").fetchall()}if "preferences_json" not in columns:conn.execute("ALTER TABLE sessions ADD COLUMN preferences_json TEXT DEFAULT '{}'")@@ -1191,6 +1196,8 @@ class SQLiteSessionStore:"SELECT * FROM turn_submissions WHERE client_submission_id = ?", (submission_id,)).fetchone()if prior is not None:+ if prior["superseded_by"]:+ raise RuntimeError("This submission was superseded by an edited message.")if prior["request_digest"] != digest or prior["workspace_id"] != workspace_id:raise RuntimeError("This submission ID belongs to a different request or workspace."@@ -1227,6 +1234,99 @@ class SQLiteSessionStore:) -> str:return await self._run(self._reserve_submission_sync, submission_id, digest, session_id)+ def _replace_submission_sync(+ self, original_id: str, replacement_id: str, digest: str, session_id: str | None+ ) -> dict[str, Any]:+ """Fence an unadmitted request and reserve its edit in one transaction.++ A transcript is deliberately not consulted to decide admission: a turn+ can already own execution before its user row is written.+ """+ from deeptutor.services.workspace.context import get_workspace_scope++ if original_id == replacement_id:+ raise RuntimeError("An edit requires a new submission ID.")+ scope = get_workspace_scope()+ workspace_id = scope.workspace_id if scope is not None else ""+ with self._connect() as conn:+ conn.execute("BEGIN IMMEDIATE")+ old = conn.execute(+ "SELECT * FROM turn_submissions WHERE client_submission_id=?", (original_id,)+ ).fetchone()+ if old is not None:+ if old["workspace_id"] != workspace_id or (+ session_id and old["session_id"] != session_id+ ):+ raise RuntimeError(+ "The submission belongs to another conversation or workspace."+ )+ session_id = old["session_id"]+ if session_id:+ session = conn.execute(+ "SELECT * FROM sessions WHERE id=?", (session_id,)+ ).fetchone()+ if session is None or session["deleted_at"] is not None:+ raise RuntimeError(+ "Restore the original conversation before editing this message."+ )+ if (+ str(_json_loads(session["preferences_json"], {}).get("workspace_id") or "")+ != workspace_id+ ):+ raise RuntimeError("The conversation belongs to another workspace.")+ else:+ session_id = str(self._insert_session(conn)["id"])+ if old is not None and old["turn_id"]:+ turn = conn.execute("SELECT * FROM turns WHERE id=?", (old["turn_id"],)).fetchone()+ user = conn.execute(+ "SELECT id FROM messages WHERE session_id=? AND role='user' AND json_valid(metadata_json) AND json_extract(metadata_json, '$.client_submission_id')=? ORDER BY id LIMIT 1",+ (session_id, original_id),+ ).fetchone()+ return {+ "status": "admitted",+ "session_id": session_id,+ "turn": self._serialize_turn(turn),+ "user_message_id": user["id"] if user else None,+ }+ replacement = conn.execute(+ "SELECT * FROM turn_submissions WHERE client_submission_id=?", (replacement_id,)+ ).fetchone()+ if old is not None and old["superseded_by"]:+ if old["superseded_by"] != replacement_id:+ raise RuntimeError("This submission was already superseded by another edit.")+ if (+ replacement is None+ or replacement["request_digest"] != digest+ or replacement["superseded_by"]+ ):+ raise RuntimeError("This replacement ID belongs to a different request.")+ else:+ if replacement is not None:+ raise RuntimeError("This replacement ID is already in use.")+ conn.execute(+ "INSERT INTO turn_submissions (client_submission_id, workspace_id, request_digest, session_id) VALUES (?, ?, ?, ?)",+ (replacement_id, workspace_id, digest, session_id),+ )+ if old is None:+ # The original may still be in a delayed transport queue.+ conn.execute(+ "INSERT INTO turn_submissions (client_submission_id, workspace_id, request_digest, session_id, superseded_by) VALUES (?, ?, '', ?, ?)",+ (original_id, workspace_id, session_id, replacement_id),+ )+ else:+ conn.execute(+ "UPDATE turn_submissions SET superseded_by=? WHERE client_submission_id=?",+ (replacement_id, original_id),+ )+ return {"status": "reserved", "session_id": session_id, "submission_id": replacement_id}++ async def replace_submission(+ self, original_id: str, replacement_id: str, digest: str, session_id: str | None = None+ ) -> dict[str, Any]:+ return await self._run(+ self._replace_submission_sync, original_id, replacement_id, digest, session_id+ )+def _submission_turn_sync(self, submission_id: str) -> dict[str, Any] | None:with self._connect() as conn:row = conn.execute(@@ -1378,6 +1478,14 @@ class SQLiteSessionStore:if session is None:raise ValueError(f"Session not found: {session_id}")if submission_id:+ reservation = conn.execute(+ "SELECT * FROM turn_submissions WHERE client_submission_id=?",+ (submission_id,),+ ).fetchone()+ if reservation is not None and reservation["superseded_by"]:+ raise RuntimeError("This submission was superseded by an edited message.")+ if reservation is not None and reservation["session_id"] != session_id:+ raise RuntimeError("This submission belongs to another conversation.")old = conn.execute("SELECT t.* FROM turns t JOIN turn_submissions s ON s.turn_id=t.id WHERE s.client_submission_id=? AND s.session_id=?",(submission_id, session_id),diff --git a/tests/app/test_turn_application_service.py b/tests/app/test_turn_application_service.pyindex 147fd5e16..737494ff0 100644--- a/tests/app/test_turn_application_service.py+++ b/tests/app/test_turn_application_service.py@@ -86,6 +86,75 @@ def submission_service(monkeypatch, tmp_path):return service, store, coordinator, registry, calls+async def test_replacement_endpoint_workflow_starts_once_and_branches_admitted_user(+ submission_service,+):+ service, store, _, _, calls = submission_service+ session, original_turn = await service.start_turn(+ {"content": "Original", "client_submission_id": "already-admitted"}+ )+ [event async for event in service.subscribe_turn(original_turn["id"])]+ payload = {+ "content": "Edited",+ "client_submission_id": "branch-edit",+ "session_id": session["id"],+ }+ receipt = await service.replace_submission("already-admitted", payload, start=True)+ assert receipt["status"] == "started"+ [event async for event in service.subscribe_turn(receipt["turn"]["id"])]+ replay = await service.replace_submission("already-admitted", payload, start=True)+ assert replay["turn"]["id"] == receipt["turn"]["id"]+ users = [row for row in await store.get_messages(session["id"]) if row["role"] == "user"]+ assert [row["content"] for row in users] == ["Original", "Edited"]+ assert users[0]["parent_message_id"] == users[1]["parent_message_id"]+ assert calls["count"] == 2+++async def test_edit_admitted_before_user_persistence_waits_for_cancellation(submission_service):+ service, store, _, _, calls = submission_service+ sid = await store.reserve_submission("before-user", "original-digest")+ original = await store.begin_turn(sid, submission_id="before-user")+ receipt = await service.replace_submission(+ "before-user",+ {+ "content": "Edited",+ "client_submission_id": "edit-before-user",+ "session_id": sid,+ },+ start=True,+ )+ assert (await store.get_turn(original["id"]))["status"] in {"cancelled", "failed"}+ [event async for event in service.subscribe_turn(receipt["turn"]["id"])]+ assert calls["count"] == 1+ assert [row["content"] for row in await store.get_messages(sid) if row["role"] == "user"] == [+ "Edited"+ ]+++async def test_reserved_edit_replays_exact_request_after_lost_receipt(submission_service):+ service, store, _, _, calls = submission_service+ payload = {+ "content": "Edited",+ "client_submission_id": "edited",+ "tools": ["reason"],+ "config": {},+ "attachments": [],+ }+ receipt = await service.replace_submission("unsent", payload)+ assert await service.replace_submission("unsent", payload) == receipt+ with pytest.raises(RuntimeError, match="superseded"):+ await service.start_turn({"content": "Original", "client_submission_id": "unsent"})+ session, turn = await service.start_turn({**payload, "session_id": receipt["session_id"]})+ [event async for event in service.subscribe_turn(turn["id"])]+ replay_session, replay_turn = await service.start_turn(payload)+ assert replay_session["id"] == session["id"]+ assert replay_turn["id"] == turn["id"]+ assert calls["count"] == 1++@pytest.mark.asyncioasync def test_lost_first_session_ack_replays_the_same_submission_after_worker_restart(submission_service,diff --git a/tests/services/session/test_submission_replacement.py b/tests/services/session/test_submission_replacement.pynew file mode 100644index 000000000..1930f8fe1--- /dev/null+++ b/tests/services/session/test_submission_replacement.py@@ -0,0 +1,70 @@+import asyncio++import pytest++from deeptutor.services.session.sqlite_store import SQLiteSessionStore+++async def test_replacement_fences_delayed_original_at_reserve_and_admission(tmp_path):+ store = SQLiteSessionStore(tmp_path / "recovery.db")+ sid = await store.reserve_submission("original", "old")+ receipt = await store.replace_submission("original", "edited", "new", sid)+ assert receipt == {"status": "reserved", "session_id": sid, "submission_id": "edited"}+ with pytest.raises(RuntimeError, match="superseded"):+ await store.reserve_submission("original", "old", sid)+ with pytest.raises(RuntimeError, match="superseded"):+ await store.begin_turn(sid, submission_id="original")+ assert await store.reserve_submission("edited", "new", sid) == sid+ assert await store.replace_submission("original", "edited", "new", sid) == receipt+ with pytest.raises(RuntimeError):+ await store.replace_submission("original", "edited", "changed", sid)+++async def test_replacement_before_original_arrives_fences_it(tmp_path):+ store = SQLiteSessionStore(tmp_path / "recovery.db")+ receipt = await store.replace_submission("late", "edited", "new", None)+ with pytest.raises(RuntimeError, match="superseded"):+ await store.reserve_submission("late", "old")+ await store.begin_turn(receipt["session_id"], submission_id="edited")+++async def test_admission_replacement_race_has_one_winner(tmp_path):+ a = SQLiteSessionStore(tmp_path / "race.db")+ b = SQLiteSessionStore(tmp_path / "race.db")+ sid = await a.reserve_submission("old", "old-digest")+ admitted, replaced = await asyncio.gather(+ a.begin_turn(sid, submission_id="old"),+ b.replace_submission("old", "new", "new-digest", sid),+ return_exceptions=True,+ )+ if isinstance(admitted, Exception):+ assert "superseded" in str(admitted)+ assert replaced["status"] == "reserved"+ await b.begin_turn(sid, submission_id="new")+ else:+ assert replaced["status"] == "admitted"+ assert replaced["turn"]["id"] == admitted["id"]+ assert replaced["user_message_id"] is None+++async def test_replacement_cannot_cross_workspace_or_session(tmp_path, monkeypatch):+ from types import SimpleNamespace++ from deeptutor.services.workspace import context++ scope = {"id": "one"}+ monkeypatch.setattr(+ context, "get_workspace_scope", lambda: SimpleNamespace(workspace_id=scope["id"])+ )+ store = SQLiteSessionStore(tmp_path / "scope.db")+ sid = await store.reserve_submission("old", "digest")+ other = await store.reserve_submission("other", "digest")+ with pytest.raises(RuntimeError):+ await store.replace_submission("old", "new", "new", other)+ scope["id"] = "two"+ with pytest.raises(RuntimeError):+ await store.replace_submission("old", "new", "new", sid)diff --git a/web/components/reading/workspace/ReadingCompanion.tsx b/web/components/reading/workspace/ReadingCompanion.tsxindex 8dcc5a1b7..bb4f210a9 100644--- a/web/components/reading/workspace/ReadingCompanion.tsx+++ b/web/components/reading/workspace/ReadingCompanion.tsx@@ -107,6 +107,8 @@ export function ReadingCompanion({regenerateLastMessage,deleteTurn,editMessage,+ discardFailedSubmission,+ retryFailedSubmission,switchBranch,loadMessageTrace,releaseMessageTrace,@@ -446,6 +448,8 @@ export function ReadingCompanion({onDeleteTurn={deleteTurn}selectedBranches={state.selectedBranches}onEditMessage={editMessage}+ onDiscardFailedSubmission={discardFailedSubmission}+ onRetryFailedSubmission={retryFailedSubmission}onSwitchBranch={switchBranch}onSubmitUserReply={submitUserReply}onConfirmOutline={confirmResearchOutline}diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.tsindex 1c2d25e92..c3b90c648 100644--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@ -7681,6 +7681,26 @@ export interface paths {readonly patch?: never;readonly trace?: never;};+ readonly "/api/sessions/submission-replacement": {+ readonly parameters: {+ readonly query?: never;+ readonly header?: never;+ readonly path?: never;+ readonly cookie?: never;+ };+ readonly get?: never;+ readonly put?: never;+ /**+ * Replace Submission+ * @description Resolve admission atomically before an edited retry is sent.+ */+ readonly post: operations["replace_submission_api_sessions_submission_replacement_post"];+ readonly delete?: never;+ readonly options?: never;+ readonly head?: never;+ readonly patch?: never;+ readonly trace?: never;+ };readonly "/api/settings": {readonly parameters: {readonly query?: never;@@ -11427,10 +11447,7 @@ export interface components {};/** Body_admin_import_users_api_auth_users_import_post */readonly Body_admin_import_users_api_auth_users_import_post: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;};/** Body_create_knowledge_base_api_knowledge_bases_post */@@ -11474,10 +11491,7 @@ export interface components {};/** Body_import_docx_api_documents_import_docx_post */readonly Body_import_docx_api_documents_import_docx_post: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;};/** Body_import_preview_api_question_notebook_practice_import_preview_post */@@ -11487,10 +11501,7 @@ export interface components {* @default*/readonly course_id: string;- /**- * File- * Format: binary- */+ /** File */readonly file: string;/*** Target@@ -11501,17 +11512,13 @@ export interface components {};/** Body_import_visualizer_api_visualizers_import_post */readonly Body_import_visualizer_api_visualizers_import_post: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;};/** Body_library_add */readonly Body_library_add: {/*** File- * Format: binary* @description Raw file bytes*/readonly file: string;@@ -11528,10 +11535,7 @@ export interface components {};/** Body_preview_office_upload_api_file_preview_pdf_post */readonly Body_preview_office_upload_api_file_preview_pdf_post: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;};/** Body_reindex_knowledge_base_api_knowledge_bases__kb_name__reindex_post */@@ -11554,20 +11558,14 @@ export interface components {};/** Body_speech_to_text_api_voice_stt_post */readonly Body_speech_to_text_api_voice_stt_post: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;/** Language */readonly language?: string | null;};/** Body_upload_avatar_api_auth_profile_avatar_put */readonly Body_upload_avatar_api_auth_profile_avatar_put: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;};/** Body_upload_files_api_knowledge_bases__kb_name__upload_post */@@ -11588,10 +11586,7 @@ export interface components {};/** Body_upload_material_api_reading_materials_post */readonly Body_upload_material_api_reading_materials_post: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;};/** BookmarkInfo */@@ -15657,6 +15652,28 @@ export interface components {/** Consult Budget */readonly consult_budget?: number | null;};+ /** SubmissionReplacementRequest */+ readonly SubmissionReplacementRequest: {+ /** Original Submission Id */+ readonly original_submission_id: string;+ readonly request: components["schemas"]["TurnRequest"];+ };+ /** SubmissionReplacementResponse */+ readonly SubmissionReplacementResponse: {+ /** Session Id */+ readonly session_id: string;+ /**+ * Status+ * @constant+ */+ readonly status: "started";+ /** Submission Id */+ readonly submission_id: string;+ /** Turn */+ readonly turn: {+ readonly [key: string]: unknown;+ };+ };/** SupplementRequest */readonly SupplementRequest: {/** Book Id */@@ -17635,6 +17652,10 @@ export type SchemaSubagentMessageRequest =components["schemas"]["SubagentMessageRequest"];export type SchemaSubagentSettingsPayload =components["schemas"]["SubagentSettingsPayload"];+export type SchemaSubmissionReplacementRequest =+ components["schemas"]["SubmissionReplacementRequest"];+export type SchemaSubmissionReplacementResponse =+ components["schemas"]["SubmissionReplacementResponse"];export type SchemaSupplementRequest =components["schemas"]["SupplementRequest"];export type SchemaSupportedFileTypesInfo =@@ -34892,6 +34913,43 @@ export interface operations {};};};+ readonly replace_submission_api_sessions_submission_replacement_post: {+ readonly parameters: {+ readonly query?: never;+ readonly header?: {+ readonly Authorization?: string | null;+ };+ readonly path?: never;+ readonly cookie?: {+ readonly dt_token?: string | null;+ };+ };+ readonly requestBody: {+ readonly content: {+ readonly "application/json": components["schemas"]["SubmissionReplacementRequest"];+ };+ };+ readonly responses: {+ /** @description Successful Response */+ readonly 200: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": components["schemas"]["SubmissionReplacementResponse"];+ };+ };+ /** @description Validation Error */+ readonly 422: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };readonly get_settings_api_settings_get: {readonly parameters: {readonly query?: never;diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.jsonindex e371c204d..0bdae2815 100644--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@ -784,7 +784,7 @@"Body_admin_import_users_api_auth_users_import_post": {"properties": {"file": {- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","type": "string"}@@ -805,7 +805,7 @@"files": {"default": [],"items": {- "format": "binary",+ "contentMediaType": "application/octet-stream","type": "string"},"title": "Files",@@ -863,7 +863,7 @@"Body_import_docx_api_documents_import_docx_post": {"properties": {"file": {- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","type": "string"}@@ -883,7 +883,7 @@"type": "string"},"file": {- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","type": "string"},@@ -906,7 +906,7 @@"Body_import_visualizer_api_visualizers_import_post": {"properties": {"file": {- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","type": "string"}@@ -920,8 +920,8 @@"Body_library_add": {"properties": {"file": {+ "contentMediaType": "application/octet-stream","description": "Raw file bytes",- "format": "binary","title": "File","type": "string"},@@ -946,7 +946,7 @@"Body_preview_office_upload_api_file_preview_pdf_post": {"properties": {"file": {- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","type": "string"}@@ -981,7 +981,7 @@"Body_speech_to_text_api_voice_stt_post": {"properties": {"file": {- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","type": "string"},@@ -1006,7 +1006,7 @@"Body_upload_avatar_api_auth_profile_avatar_put": {"properties": {"file": {- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","type": "string"}@@ -1025,7 +1025,7 @@},"files": {"items": {- "format": "binary",+ "contentMediaType": "application/octet-stream","type": "string"},"title": "Files",@@ -1064,7 +1064,7 @@"Body_upload_material_api_reading_materials_post": {"properties": {"file": {- "format": "binary",+ "contentMediaType": "application/octet-stream","title": "File","type": "string"}@@ -9785,6 +9785,55 @@"title": "SubagentSettingsPayload","type": "object"},+ "SubmissionReplacementRequest": {+ "properties": {+ "original_submission_id": {+ "maxLength": 100,+ "minLength": 1,+ "title": "Original Submission Id",+ "type": "string"+ },+ "request": {+ "$ref": "#/components/schemas/TurnRequest"+ }+ },+ "required": [+ "original_submission_id",+ "request"+ ],+ "title": "SubmissionReplacementRequest",+ "type": "object"+ },+ "SubmissionReplacementResponse": {+ "properties": {+ "session_id": {+ "title": "Session Id",+ "type": "string"+ },+ "status": {+ "const": "started",+ "title": "Status",+ "type": "string"+ },+ "submission_id": {+ "title": "Submission Id",+ "type": "string"+ },+ "turn": {+ "additionalProperties": true,+ "title": "Turn",+ "type": "object"+ }+ },+ "required": [+ "status",+ "session_id",+ "submission_id",+ "turn"+ ],+ "title": "SubmissionReplacementResponse",+ "type": "object"+ },"SupplementRequest": {"properties": {"book_id": {@@ -48144,6 +48193,82 @@]}},+ "/api/sessions/submission-replacement": {+ "post": {+ "description": "Resolve admission atomically before an edited retry is sent.",+ "operationId": "replace_submission_api_sessions_submission_replacement_post",+ "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"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SubmissionReplacementRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SubmissionReplacementResponse"+ }+ }+ },+ "description": "Successful Response"+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ },+ "description": "Validation Error"+ }+ },+ "summary": "Replace Submission",+ "tags": [+ "sessions"+ ]+ }+ },"/api/sessions/{session_id}": {"delete": {"operationId": "delete_session_api_sessions__session_id__delete",diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsxindex 2ea420354..adcd156d5 100644--- a/web/features/chat/ChatStateAdapter.tsx+++ b/web/features/chat/ChatStateAdapter.tsx@@ -41,6 +41,7 @@ import { UnifiedTurnClient } from "@/features/chat/transport/UnifiedTurnClient";import { buildStartTurnInput } from "@/features/chat/controllers/buildStartTurnInput";import {getSession,+ replaceSubmission,getMessageTrace,deleteMessage,updateBranchSelection,@@ -70,6 +71,7 @@ import {tipMessageId,} from "@/lib/message-branches";import { nextOptimisticId, resolvePersistedMessage } from "@/lib/optimistic-id";+import { recoveryPrincipal, RECOVERY_PRINCIPAL_CHANGED } from "@/lib/recovery-principal";import {SUBMIT_CONNECT_RETRY_INTERVAL_MS,SUBMIT_CONNECT_RETRY_LIMIT,@@ -135,6 +137,9 @@ export interface SendMessageOptions {requestSnapshotOverride?: MessageRequestSnapshot;/** Internal resend identity: reuse the original server correlation token. */retrySubmissionId?: string;+ replacesSubmissionId?: string;+ replacementRootSubmissionId?: string;+ replacedMessageId?: number;bookReferences?: BookReferencePayload[];readingReferences?: ReadingReferencePayload[];/** Edit-branching: when set, the new user message is inserted as a@@ -268,6 +273,10 @@ export interface MessageAttachment {}export interface MessageRequestSnapshot {+ /** Durable edit intent; replay the exact reserved wire request after a lost acknowledgement. */+ replacesSubmissionId?: string;+ replacementRootSubmissionId?: string;+ replacementRequest?: Record<string, unknown>;resourceSelection?: ResourceSelection;content: string;capability?: string | null;@@ -379,6 +388,7 @@ interface SessionSnapshot {}type Action =+ | { type: "RESET_ACCOUNT" }| { type: "SET_TOOLS"; tools: string[] }| { type: "SET_CAPABILITY"; cap: string | null }| { type: "SET_KB"; kbs: string[] }@@ -642,6 +652,7 @@ function isSameTurnEvent(a: StreamEvent, b: StreamEvent): boolean {}function reducer(state: ProviderState, action: Action): ProviderState {+ if (action.type === "RESET_ACCOUNT") return initialState;switch (action.type) {case "SET_TOOLS":return updateSelectedSession(state, (session) => ({@@ -1574,7 +1585,8 @@ interface ChatContextValue {* Uses the composer's current capability / refs — only the text is* taken from ``newContent``. Re-runs the turn from the original's* parent context. */- editMessage: (messageId: number, newContent: string) => Promise<void>;+ editMessage: (messageId: number, newContent: string) => Promise<boolean>;+ retryFailedSubmission: (messageId: number) => Promise<boolean>;/** Switch which sibling is currently visible at a branch point. */switchBranch: (parentMessageId: number | null, childId: number) => void;renameSessionTitle: (title: string) => Promise<void>;@@ -1855,6 +1867,41 @@ export function ChatStateAdapterProvider({const loadSessionRef = useRef<((sessionId: string) => Promise<MessageItem[] | undefined>) | null>(null);+ const principalRef = useRef(recoveryPrincipal());+ const principalResolvedRef = useRef(principalRef.current !== null);++ useEffect(() => {+ const onPrincipalChanged = () => {+ const principal = recoveryPrincipal();+ if (principal === principalRef.current) return;+ const firstResolution = !principalResolvedRef.current && principalRef.current === null;+ principalRef.current = principal;+ if (principal !== null) principalResolvedRef.current = true;+ if (!firstResolution) {+ runtimeGeneration.current += 1;+ runnersRef.current.forEach(({ client }) => client.disconnect());+ runnersRef.current.clear();+ retryTimersRef.current.forEach(clearTimeout);+ retryTimersRef.current.clear();+ traceRequestsRef.current.forEach((controller) => controller.abort());+ traceRequestsRef.current.clear();+ traceCacheRef.current.clear();+ pendingSubmissionIdsRef.current.clear();+ pendingRegenerateRef.current.clear();+ pendingResendRef.current.clear();+ resolvingResendRef.current.clear();+ resumedParkedTurnsRef.current.clear();+ stateRef.current = initialState;+ dispatch({ type: "RESET_ACCOUNT" });+ writeStoredActiveSessionId(null);+ }+ dispatch({ type: "ENSURE_DRAFT_SESSION", key: `draft_${Date.now()}_${++draftCounterRef.current}`,+ failedRecords: readFailedSubmissions(draftFailedSubmissionKey()) });+ };+ window.addEventListener(RECOVERY_PRINCIPAL_CHANGED, onPrincipalChanged);+ onPrincipalChanged();+ return () => window.removeEventListener(RECOVERY_PRINCIPAL_CHANGED, onPrincipalChanged);+ }, []);useLayoutEffect(() => {stateRef.current = state;@@ -1940,6 +1987,8 @@ export function ChatStateAdapterProvider({? null: message.parent_message_id,...(requestSnapshot ? { requestSnapshot } : {}),+ ...(typeof message.metadata?.client_submission_id === "string"+ ? { failedSubmissionId: message.metadata.client_submission_id } : {}),...(message.role === "user" && message.metadata?.orphaned_failed_turn? { orphanedFailedTurn: message.metadata.orphaned_failed_turn }: {}),@@ -2219,6 +2268,7 @@ export function ChatStateAdapterProvider({if (!existing.client.connected) existing.client.connect();return existing;}+ const generation = runtimeGeneration.current;const record: {key: string;client: UnifiedTurnClient;@@ -2226,8 +2276,11 @@ export function ChatStateAdapterProvider({} = {key,client: new UnifiedTurnClient(- (event) => handleRunnerEvent(record.key, event),+ (event) => {+ if (generation === runtimeGeneration.current) handleRunnerEvent(record.key, event);+ },() => {+ if (generation !== runtimeGeneration.current) return;const session = stateRef.current.sessions[record.key];if (session?.isStreaming) {if (@@ -2714,7 +2767,7 @@ export function ChatStateAdapterProvider({}, [sendThroughRunner]);const sendMessage = useCallback(- (+ async (content: string,attachments?: OutgoingAttachment[],config?: Record<string, unknown>,@@ -2725,6 +2778,7 @@ export function ChatStateAdapterProvider({persona?: string,memoryReferences?: MemoryReferencePayload,) => {+ const generation = runtimeGeneration.current;const msgAttachments = attachments?.map((a) => ({type: a.type,filename: a.filename,@@ -2740,7 +2794,7 @@ export function ChatStateAdapterProvider({}const session = currentState.sessions[key] ?? createSessionEntry(key);const replaySnapshot = options?.requestSnapshotOverride;- const exactReplay = Boolean(options?.retrySubmissionId && replaySnapshot);+ const exactReplay = Boolean(replaySnapshot);const effectiveCapability =exactReplay ? (replaySnapshot?.capability ?? null) :replaySnapshot?.capability ??@@ -2863,7 +2917,7 @@ export function ChatStateAdapterProvider({const effectiveTimedMediaId = replaySnapshot?.timedMediaId;const effectiveWatchingTurnFields = replaySnapshot?.watchingTurnFields ??(effectiveTimedMediaId ? { timed_media_id: effectiveTimedMediaId } : {});- const requestSnapshot: MessageRequestSnapshot = replaySnapshot ?? {+ const requestSnapshot: MessageRequestSnapshot = replaySnapshot ? { ...replaySnapshot } : {resourceSelection: {skills:[...effectiveResources.skills],mcp:[...effectiveResources.mcp]},content,capability: effectiveCapability,@@ -2964,7 +3018,9 @@ export function ChatStateAdapterProvider({(trackNewSubmission ? randomUuid() : undefined);const persistSubmission = Boolean(submissionId) &&(trackNewSubmission || Boolean(options?.retrySubmissionId));- if (options?.displayUserMessage !== false) {+ const replacesSubmissionId = options?.replacesSubmissionId ?? replaySnapshot?.replacesSubmissionId;+ const showSubmission = () => {+ if (options?.displayUserMessage !== false) {dispatch({type: "ADD_USER_MSG",key,@@ -2975,8 +3031,10 @@ export function ChatStateAdapterProvider({parentMessageId: localParentId,failedSubmissionId: submissionId,});- }- dispatch({ type: "STREAM_START", key, startedAt: Date.now() / 1000 });+ }+ dispatch({ type: "STREAM_START", key, startedAt: Date.now() / 1000 });+ };+ if (!replacesSubmissionId) showSubmission();const {_persist_user_message: legacyPersistUserMessage,_course_id: _legacyCourseId,@@ -2996,7 +3054,7 @@ export function ChatStateAdapterProvider({// Persist before attempting the socket, including a first turn that// has no server session yet. Replays reuse their original identity.const submissionStorageKey = session.sessionId ?? draftFailedSubmissionKey();- if (persistSubmission && submissionId) {+ if (persistSubmission && submissionId && !replacesSubmissionId) {const saved = storeFailedSubmission(submissionStorageKey, {content,capability: effectiveCapability,@@ -3025,9 +3083,7 @@ export function ChatStateAdapterProvider({],});}- return sendThroughRunner(- key,- buildStartTurnInput({+ let command = buildStartTurnInput({content,clientSubmissionId: submissionId,tools: effectiveTools,@@ -3112,13 +3168,52 @@ export function ChatStateAdapterProvider({// negative id, omit the key and let the backend auto-append to// the latest persisted row.parentMessageId: wireParentId,- }),- );+ });+ if (replacesSubmissionId && submissionId) {+ command = (replaySnapshot?.replacementRequest ?? command) as typeof command;+ requestSnapshot.replacesSubmissionId = replacesSubmissionId;+ requestSnapshot.replacementRootSubmissionId = options?.replacementRootSubmissionId ??+ replaySnapshot?.replacementRootSubmissionId ?? replacesSubmissionId;+ requestSnapshot.replacementRequest = { ...command };+ // Save the edit and its identity before fencing the original. A lost+ // HTTP receipt then retries the same native reservation after reload.+ if (!storeFailedSubmission(submissionStorageKey, {+ content, capability: effectiveCapability, requestSnapshot, submissionId,+ })) return false;+ const durable = readFailedSubmissions(submissionStorageKey).find((record) => record.submissionId === submissionId);+ if (!durable || durable.retryRequiresReview || JSON.stringify(durable.requestSnapshot) !== JSON.stringify(requestSnapshot)) {+ notify(i18n.t("This unsent message could not be saved in your browser. Copy it before leaving this page."), { tone: "error" });+ return false;+ }+ try {+ const receipt = await replaceSubmission(replacesSubmissionId, { ...command });+ if (generation !== runtimeGeneration.current) return true;+ command.session_id = receipt.session_id;+ // The server receipt, not transcript absence, authorizes retirement+ // of the superseded local copy. The new durable record already exists.+ clearFailedSubmission(submissionStorageKey, replacesSubmissionId);+ if (options?.replacedMessageId != null) {+ const replaced = session.messages.find((message) => message.id === options.replacedMessageId);+ if (replaced?.failedSubmissionId) dispatch({ type: "DISCARD_FAILED_SUBMISSION", key,+ messageId: options.replacedMessageId, submissionId: replaced.failedSubmissionId });+ }+ showSubmission();+ // HTTP acknowledged native admission. Subscribe/replay the same+ // turn; never send another start command for this edit.+ ensureRunner(key).client.send({ type: "subscribe_turn", turn_id: receipt.turn.id, after_seq: 0 });+ return true;+ } catch {+ pendingSubmissionIdsRef.current.delete(key);+ return false;+ }+ }+ return sendThroughRunner(key, command);},- [makeDraftKey, sendThroughRunner],+ [makeDraftKey, sendThroughRunner, ensureRunner],);- const cancelStreamingTurn = useCallback(() => {+ const cancelStreamingTurn = useCallback(async () => {+ const generation = runtimeGeneration.current;const currentState = stateRef.current;const key = currentState.selectedKey;if (!key) return;@@ -3127,8 +3222,17 @@ export function ChatStateAdapterProvider({const turnId = session.activeTurnId;const runner = runnersRef.current.get(key);if (runner) {- if (runner.client.connected && turnId) {- runner.client.send({ type: "cancel_turn", turn_id: turnId });+ if (turnId) {+ try {+ if (!await runner.client.sendAwaitingAck({ type: "cancel_turn", turn_id: turnId })) {+ notify(i18n.t("Couldn't reach the server. Please check your connection and retry."), { tone: "error" });+ return;+ }+ if (generation !== runtimeGeneration.current) return;+ } catch {+ notify(i18n.t("Couldn't reach the server. Please check your connection and retry."), { tone: "error" });+ return;+ }}runner.client.disconnect();runnersRef.current.delete(key);@@ -3552,25 +3656,67 @@ export function ChatStateAdapterProvider({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;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) {+ 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(@@ -3583,17 +3729,20 @@ export function ChatStateAdapterProvider({: undefined,);} catch {- return;+ return false;}- if (!original || generation !== runtimeGeneration.current) return;+ if (!original || generation !== runtimeGeneration.current) return false;const parentId = original.parentMessageId ?? null;- sendMessage(+ return sendMessage(trimmed,+ original.attachments,undefined,undefined,undefined,- undefined,- { parentMessageId: parentId },+ { parentMessageId: parentId,+ requestSnapshotOverride: (local?.requestSnapshot ?? original.requestSnapshot)+ ? { ...(local?.requestSnapshot ?? original.requestSnapshot)!, content: trimmed,+ replacesSubmissionId: undefined, replacementRequest: undefined } : undefined },undefined,undefined,undefined,@@ -3602,6 +3751,28 @@ export function ChatStateAdapterProvider({[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;+ 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;@@ -3699,6 +3870,7 @@ export function ChatStateAdapterProvider({resendLastMessage,deleteTurn,discardFailedSubmission,+ retryFailedSubmission,editMessage,switchBranch,renameSessionTitle,@@ -3732,6 +3904,7 @@ export function ChatStateAdapterProvider({resendLastMessage,deleteTurn,discardFailedSubmission,+ retryFailedSubmission,editMessage,switchBranch,renameSessionTitle,diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex d63e91ef6..9ce8657ae 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -282,6 +282,7 @@ export default function ChatWorkspace() {resendLastMessage,deleteTurn,discardFailedSubmission,+ retryFailedSubmission,editMessage,switchBranch,newSession,@@ -2581,6 +2582,7 @@ export default function ChatWorkspace() {}}onDeleteTurn={deleteTurn}onDiscardFailedSubmission={discardFailedSubmission}+ onRetryFailedSubmission={retryFailedSubmission}selectedBranches={state.selectedBranches}onEditMessage={editMessage}onSwitchBranch={switchBranch}diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex 68afee33c..9c3a8a6fc 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -1560,6 +1560,7 @@ export const UserMessage = memo(function UserMessage({onCopy,onEdit,onDiscardFailedSubmission,+ onRetryFailedSubmission,editDisabled,siblingInfo,onSwitchBranch,@@ -1572,8 +1573,9 @@ export const UserMessage = memo(function UserMessage({index: number;onPreviewAttachment?: (attachment: MessageAttachment) => void;onCopy?: CopyHandler;- onEdit?: (messageId: number, newContent: string) => void;+ onEdit?: (messageId: number, newContent: string) => void | boolean | Promise<void | boolean>;onDiscardFailedSubmission?: (messageId: number) => boolean | Promise<boolean>;+ onRetryFailedSubmission?: (messageId: number) => boolean | Promise<boolean>;editDisabled?: boolean;siblingInfo?: SiblingInfo;onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;@@ -1592,6 +1594,9 @@ export const UserMessage = memo(function UserMessage({const [draft, setDraft] = useState(msg.content);const [discarding, setDiscarding] = useState(false);const [discardFailed, setDiscardFailed] = useState(false);+ const [submittingEdit, setSubmittingEdit] = useState(false);+ const [editFailed, setEditFailed] = useState(false);+ const [retrying, setRetrying] = useState(false);const { isComposingRef, onCompositionStart, onCompositionEnd } =useImeComposing();// Connected subagents ride in knowledge_bases (same selection path) but are@@ -1606,7 +1611,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 && !msg.failedSubmission;+ Boolean(onEdit) && typeof msg.id === "number" && !editDisabled;const discardDraft = async () => {if (!onDiscardFailedSubmission || typeof msg.id !== "number" || editDisabled || discarding) return;setDiscarding(true);@@ -1628,15 +1633,24 @@ export const UserMessage = memo(function UserMessage({setEditing(false);setDraft(msg.content);};- const submitEdit = () => {+ const submitEdit = async () => {+ if (submittingEdit) return;const trimmed = draft.trim();if (!trimmed || trimmed === msg.content) {cancelEdit();return;}if (typeof msg.id !== "number") return;- onEdit?.(msg.id, trimmed);- setEditing(false);+ setSubmittingEdit(true);+ setEditFailed(false);+ try {+ if (await onEdit?.(msg.id, trimmed) === false) setEditFailed(true);+ else setEditing(false);+ } catch {+ setEditFailed(true);+ } finally {+ setSubmittingEdit(false);+ }};// Everything this turn carried — file attachments plus the request@@ -1776,6 +1790,7 @@ export const UserMessage = memo(function UserMessage({<textareaautoFocusvalue={draft}+ disabled={submittingEdit}onChange={(e) => setDraft(e.target.value)}onKeyDown={(e) => {if (e.key === "Escape") {@@ -1802,6 +1817,7 @@ export const UserMessage = memo(function UserMessage({<buttontype="button"onClick={cancelEdit}+ disabled={submittingEdit}className="rounded-md px-2 py-0.5 text-[11px] font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40">{t("Cancel")}@@ -1809,13 +1825,14 @@ export const UserMessage = memo(function UserMessage({<buttontype="button"onClick={submitEdit}- disabled={!draft.trim() || draft.trim() === msg.content}+ disabled={submittingEdit || !draft.trim() || draft.trim() === msg.content}className="rounded-md bg-[var(--primary)] px-2.5 py-0.5 text-[11px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40">{t("Send")}</button></div></div>+ {editFailed && <p role="alert" className="text-xs text-[var(--destructive)]">{t("The edit could not be sent. Your draft is still here; please retry.")}</p>}</div>) : (<div@@ -1849,6 +1866,13 @@ export const UserMessage = memo(function UserMessage({><AlertCircle className="h-3.5 w-3.5" aria-hidden="true" />{t("Not sent")}+ {onRetryFailedSubmission && 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={() => 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">@@ -1945,6 +1969,7 @@ export const ChatMessageList = memo(function ChatMessageList({onOpenConsultation,onDeleteTurn,onDiscardFailedSubmission,+ onRetryFailedSubmission,selectedBranches,onEditMessage,onSwitchBranch,@@ -1978,9 +2003,10 @@ export const ChatMessageList = memo(function ChatMessageList({onOpenConsultation?: (events: StreamEvent[]) => void;onDeleteTurn?: (messageId: number) => void;onDiscardFailedSubmission?: (messageId: number) => boolean | Promise<boolean>;+ onRetryFailedSubmission?: (messageId: number) => boolean | Promise<boolean>;/** Edit-branching: selected sibling at each branch point. */selectedBranches?: Record<string, number>;- onEditMessage?: (messageId: number, newContent: string) => void;+ onEditMessage?: (messageId: number, newContent: string) => void | boolean | Promise<void | boolean>;onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;/*** Deliver an ``ask_user`` reply back to the backend so the agentic@@ -2249,6 +2275,7 @@ export const ChatMessageList = memo(function ChatMessageList({onCopy={onCopyAssistantMessage}onEdit={onEditMessage}onDiscardFailedSubmission={onDiscardFailedSubmission}+ onRetryFailedSubmission={onRetryFailedSubmission}editDisabled={isStreaming}siblingInfo={sib}onSwitchBranch={onSwitchBranch}diff --git a/web/lib/auth.ts b/web/lib/auth.tsindex e12194021..d548cfb3e 100644--- a/web/lib/auth.ts+++ b/web/lib/auth.ts@@ -1,4 +1,5 @@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@@ -33,13 +34,36 @@ export interface AuthStatus {}const AUTH_STATUS_CACHE_MS = 5_000;+const AUTH_BOUNDARY_KEY = "deeptutor.authBoundary";+let authGeneration = 0;+let boundaryListenerInstalled = false;let authStatusRequest: Promise<AuthStatus | null> | null = null;let cachedAuthStatus: { value: AuthStatus | null; expiresAt: number } | null =null;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()}`); }+ 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();+ });}/**@@ -47,24 +71,28 @@ export function invalidateAuthStatusCache(): void {* Returns null on network error so callers can decide how to handle it.*/export function fetchAuthStatus(): Promise<AuthStatus | null> {+ listenForAuthBoundary();if (cachedAuthStatus && cachedAuthStatus.expiresAt > Date.now()) {return Promise.resolve(cachedAuthStatus.value);}if (!authStatusRequest) {- authStatusRequest = (async () => {+ const generation = authGeneration;+ const request = (async () => {try {const res = await apiFetch(apiUrl("/api/auth/status"));if (!res.ok) return null;const status: AuthStatus = await res.json();// Record the real auth state so apiFetch's in-session 401 → /login redirect// fires only when auth is actually enabled.- setRuntimeAuthEnabled(Boolean(status.enabled));return status;} catch {return null;}})().then((status) => {+ if (generation !== authGeneration) return null;+ if (status !== null) setRuntimeAuthEnabled(Boolean(status.enabled));+ updateRecoveryPrincipal(status);cachedAuthStatus = {value: status,// Retry unavailable backends quickly; stable answers can be shared@@ -74,8 +102,9 @@ export function fetchAuthStatus(): Promise<AuthStatus | null> {return status;}).finally(() => {- authStatusRequest = null;+ if (authStatusRequest === request) authStatusRequest = null;});+ authStatusRequest = request;}return authStatusRequest;}@@ -99,6 +128,7 @@ export async function login(if (res.ok) {invalidateAuthStatusCache();+ broadcastAuthBoundary();return { ok: true };}@@ -149,6 +179,7 @@ export async function register(const data = await res.json().catch(() => ({}));if (res.ok) {invalidateAuthStatusCache();+ broadcastAuthBoundary();return { ok: true, role: data.role, is_first_user: data.is_first_user };}return { ok: false, error: extractDetail(data.detail) };@@ -175,6 +206,7 @@ export async function checkIsFirstUser(): Promise<boolean> {* POST to the logout endpoint to clear the session cookie.*/export async function logout(): Promise<void> {+ invalidateAuthStatusCache();try {await apiFetch(apiUrl("/api/auth/logout"), {method: "POST",@@ -183,5 +215,6 @@ export async function logout(): Promise<void> {// Ignore — we'll redirect regardless} finally {invalidateAuthStatusCache();+ broadcastAuthBoundary();}}diff --git a/web/lib/failed-submissions.ts b/web/lib/failed-submissions.tsindex 11a39d968..f7076871e 100644--- a/web/lib/failed-submissions.ts+++ b/web/lib/failed-submissions.ts@@ -2,6 +2,7 @@import { browserStorage } from "@/shared/storage";import { randomUuid } from "@/lib/random-uuid";+import { recoveryPrincipal } from "@/lib/recovery-principal";/** Kept opaque here so lib/ does not depend on features/. */export type FailedSubmissionSnapshot = unknown;@@ -19,38 +20,39 @@ export interface FailedSubmissionRecord {retryRequiresReview?: boolean;}-const LEGACY_KEY = "deeptutor.failedSubmissions";-const LEGACY_FALLBACK_PREFIX = LEGACY_KEY + ".fallback.";-const RECORD_PREFIX = LEGACY_KEY + ".record.";-const TOMBSTONE_PREFIX = LEGACY_KEY + ".cleared.";-const BINDING_PREFIX = LEGACY_KEY + ".binding.";const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;+function ownerPrefix(kind: "record" | "cleared" | "binding"): string {+ const principal = recoveryPrincipal();+ if (principal === null) throw new Error("Recovery ownership is unresolved");+ return "deeptutor.failedSubmissions.owner." + encodeURIComponent(principal) + "." + kind + ".";+}+function recordKey(sessionId: string, submissionId: string): string {- return RECORD_PREFIX + encodeURIComponent(sessionId) + ":" ++ return ownerPrefix("record") + encodeURIComponent(sessionId) + ":" +encodeURIComponent(submissionId);}function recordPrefix(sessionId: string): string {- return RECORD_PREFIX + encodeURIComponent(sessionId) + ":";+ return ownerPrefix("record") + encodeURIComponent(sessionId) + ":";}function tombstoneKey(sessionId: string, submissionId: string): string {- return TOMBSTONE_PREFIX + encodeURIComponent(sessionId) + ":" ++ return ownerPrefix("cleared") + encodeURIComponent(sessionId) + ":" +encodeURIComponent(submissionId);}function tombstonePrefix(sessionId: string): string {- return TOMBSTONE_PREFIX + encodeURIComponent(sessionId) + ":";+ return ownerPrefix("cleared") + encodeURIComponent(sessionId) + ":";}function bindingKey(sessionId: string, submissionId: string): string {- return BINDING_PREFIX + encodeURIComponent(sessionId) + ":" ++ return ownerPrefix("binding") + encodeURIComponent(sessionId) + ":" +encodeURIComponent(submissionId);}function bindingPrefix(sessionId: string): string {- return BINDING_PREFIX + encodeURIComponent(sessionId) + ":";+ return ownerPrefix("binding") + encodeURIComponent(sessionId) + ":";}function hasSubmissionPayload(content: string, snapshot: unknown): boolean {@@ -69,44 +71,6 @@ function isRecord(value: unknown): value is FailedSubmissionRecord {typeof record.savedAt === "number";}-function asLegacyRecords(value: unknown): FailedSubmissionRecord[] {- const records = isRecord(value) ? [value] :- (Array.isArray(value) ? value.filter(isRecord) : []);- // Records written before client_submission_id cannot be matched safely to- // server rows. Keep their text, but require review before an automatic retry.- return records.map((record) => record.submissionId- ? record- : { ...record, submissionId: "legacy:" + record.savedAt, retryRequiresReview: true });-}--function legacyRecords(sessionId: string): FailedSubmissionRecord[] {- try {- const raw = browserStorage.readRaw("local", LEGACY_KEY);- const parsed: unknown = raw ? JSON.parse(raw) : null;- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return [];- return asLegacyRecords((parsed as Record<string, unknown>)[sessionId]);- } catch {- return [];- }-}--function legacyRecordsForSession(sessionId: string): FailedSubmissionRecord[] {- try {- const raw = browserStorage.readRaw(- "session", LEGACY_FALLBACK_PREFIX + encodeURIComponent(sessionId),- );- if (raw) {- const parsed: unknown = JSON.parse(raw);- // The old fallback, including an empty-array tombstone, took priority- // over the shared map when the map could not be rewritten.- if (isRecord(parsed) || Array.isArray(parsed)) return asLegacyRecords(parsed);- }- } catch {- // A malformed or unavailable fallback cannot hide the local map.- }- return legacyRecords(sessionId);-}-function storedRecords(scope: "local" | "session", sessionId: string): FailedSubmissionRecord[] {return browserStorage.listRaw(scope, recordPrefix(sessionId)).flatMap(([key, raw]) => {try {@@ -176,7 +140,7 @@ type PersistedAs = "local_full" | "local_text" | "session_full" | "session_text"function pruneExpiredEntries(): void {const now = Date.now();for (const scope of ["local", "session"] as const) {- for (const [key, raw] of browserStorage.listRaw(scope, RECORD_PREFIX)) {+ for (const [key, raw] of browserStorage.listRaw(scope, ownerPrefix("record"))) {let savedAt = Number.NaN;try {const value: unknown = JSON.parse(raw);@@ -186,7 +150,7 @@ function pruneExpiredEntries(): void {if (browserStorage.readRaw(scope, key) === raw) browserStorage.removeRaw(scope, key);}}- for (const [key, raw] of browserStorage.listRaw(scope, TOMBSTONE_PREFIX)) {+ for (const [key, raw] of browserStorage.listRaw(scope, ownerPrefix("cleared"))) {const savedAt = Number(raw);if (!Number.isFinite(savedAt) || now - savedAt > MAX_AGE_MS) {if (browserStorage.readRaw(scope, key) === raw) browserStorage.removeRaw(scope, key);@@ -237,7 +201,7 @@ interface DraftBinding {function readBindings(targetSessionId?: string): DraftBinding[] {return browserStorage.listRaw(- "session", targetSessionId ? bindingPrefix(targetSessionId) : BINDING_PREFIX,+ "session", targetSessionId ? bindingPrefix(targetSessionId) : ownerPrefix("binding"),).flatMap(([key, raw]) => {try {const value = JSON.parse(raw) as Partial<DraftBinding>;@@ -260,7 +224,6 @@ function directRecords(sessionId: string): FailedSubmissionRecord[] {const cleared = clearedIds(sessionId);const byId = new Map<string, FailedSubmissionRecord>();for (const record of [- ...legacyRecordsForSession(sessionId),...storedRecords("local", sessionId),...storedRecords("session", sessionId),]) {@@ -287,7 +250,7 @@ export function storeFailedSubmission(priorMatchingUserIds?: string[];},): string | null {- if (!sessionId || !hasSubmissionPayload(submission.content, submission.requestSnapshot)) return null;+ if (recoveryPrincipal() === null || !sessionId || !hasSubmissionPayload(submission.content, submission.requestSnapshot)) return null;const submissionId = submission.submissionId ?? randomUuid();const record: FailedSubmissionRecord = {content: submission.content,@@ -304,9 +267,10 @@ export function storeFailedSubmission(return persistRecord(sessionId, record) ? submissionId : null;}-/** Read the union of shared local, this tab's fallback, and old formats. */-export function readFailedSubmissions(sessionId: string): FailedSubmissionRecord[] {- if (!sessionId) return [];+/** Read this owner's local and tab fallback records. Unowned legacy data is+ * preserved in storage, never silently attributed to the current account. */+export function readFailedSubmissions(sessionId: string, includeSuperseded = false): FailedSubmissionRecord[] {+ if (recoveryPrincipal() === null || !sessionId) return [];const byId = new Map<string, FailedSubmissionRecord>();const bindings = readBindings();const boundAwayIds = new Set(@@ -329,7 +293,13 @@ export function readFailedSubmissions(sessionId: string): FailedSubmissionRecordbyId.set(record.submissionId, record);}}- return [...byId.values()].sort((left, right) => left.savedAt - right.savedAt);+ const records = [...byId.values()];+ const replacedIds = new Set(records.flatMap((record) => {+ const snapshot = record.requestSnapshot as { replacesSubmissionId?: string } | null;+ return snapshot?.replacesSubmissionId ? [snapshot.replacesSubmissionId] : [];+ }));+ return records.filter((record) => includeSuperseded || !replacedIds.has(record.submissionId!))+ .sort((left, right) => left.savedAt - right.savedAt);}/** Kept for callers interested in the most recent pending submission. */@@ -344,7 +314,7 @@ export function moveFailedSubmissions(sessionId: string,submissionIds: readonly string[],): string[] {- if (!sourceKey || !sessionId || sourceKey === sessionId || !submissionIds.length) return [];+ if (recoveryPrincipal() === null || !sourceKey || !sessionId || sourceKey === sessionId || !submissionIds.length) return [];const ids = new Set(submissionIds);const visible: string[] = [];for (const record of readFailedSubmissions(sourceKey)) {@@ -372,7 +342,7 @@ export function moveFailedSubmissions(/** Remove one causal record; return whether its retirement was recorded. */export function clearFailedSubmission(sessionId: string, submissionId?: string): boolean {- if (!sessionId) return false;+ if (recoveryPrincipal() === null || !sessionId) return false;if (!submissionId) {let cleared = true;for (const record of readFailedSubmissions(sessionId)) {diff --git a/web/lib/optimistic-id.ts b/web/lib/optimistic-id.tsindex 5274231f6..876184c9a 100644--- a/web/lib/optimistic-id.ts+++ b/web/lib/optimistic-id.ts@@ -29,6 +29,8 @@ export function nextOptimisticId(): number {interface IdentifiedMessage {id?: number;role: string;+ failedSubmissionId?: string;+ metadata?: Record<string, unknown>;}/**@@ -50,8 +52,12 @@ export async function resolvePersistedMessage<T extends IdentifiedMessage>(const original = messages[index];if (typeof original.id === "number" && original.id >= 0) return original;+ const submissionId = original.failedSubmissionId ?? original.metadata?.client_submission_id;+ if (typeof submissionId !== "string" || !submissionId) return undefined;const refreshed = await refreshMessages();- const candidate = refreshed?.[index];+ const candidates = refreshed?.filter((message) => message.role === expectedRole &&+ (message.metadata?.client_submission_id ?? message.failedSubmissionId) === submissionId);+ const candidate = candidates?.length === 1 ? candidates[0] : undefined;if (!candidate ||candidate.role !== expectedRole ||diff --git a/web/lib/recovery-principal.ts b/web/lib/recovery-principal.tsnew file mode 100644index 000000000..81653a804--- /dev/null+++ b/web/lib/recovery-principal.ts@@ -0,0 +1,19 @@+/** Recovery ownership comes only from a resolved server authentication status. */+export const RECOVERY_PRINCIPAL_CHANGED = "deeptutor:recovery-principal-changed";+let principal: string | null = null;++export function recoveryPrincipal(): string | null {+ return principal;+}++export function updateRecoveryPrincipal(status: {+ enabled: boolean; authenticated: boolean; user_id?: string;+} | null): void {+ const next = status?.enabled === false ? "single-user"+ : status?.enabled === true && status.authenticated === true &&+ typeof status.user_id === "string" && status.user_id.trim()+ ? "user:" + status.user_id : null;+ if (next === principal) return;+ principal = next;+ if (typeof window !== "undefined") window.dispatchEvent(new Event(RECOVERY_PRINCIPAL_CHANGED));+}diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 7708cd778..d31c9d8aa 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -306,6 +306,21 @@ export async function getSession(return expectJson<SessionDetail>(response);}+export type SubmissionReplacementReceipt = {+ status: "started"; session_id: string; submission_id: string;+ turn: { id: string; status: string };+};++export async function replaceSubmission(+ originalSubmissionId: string, request: Record<string, unknown>,+): Promise<SubmissionReplacementReceipt> {+ const { type: _type, protocol_version: _version, ...payload } = request;+ return expectJson<SubmissionReplacementReceipt>(await apiFetch(apiUrl("/api/sessions/submission-replacement"), {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ original_submission_id: originalSubmissionId, request: payload }),+ }));+}+/** Opening an old Watching conversation is the explicit migration boundary. */export async function migrateWatchingSession(sessionId: string): Promise<SessionDetail> {return expectJson<SessionDetail>(await apiFetch(apiUrl(`/api/sessions/${encodeURIComponent(sessionId)}/migrate-watching`), { method: "POST" }));diff --git a/web/locales/de/app.json b/web/locales/de/app.jsonindex 5bcc16a2e..60ad77103 100644--- a/web/locales/de/app.json+++ b/web/locales/de/app.json@@ -1,4 +1,5 @@{+ "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.",diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 082fc7489..466ce83ab 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -1,4 +1,5 @@{+ "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.",diff --git a/web/locales/fr/app.json b/web/locales/fr/app.jsonindex 6ebd2ee59..3afbf9e82 100644--- a/web/locales/fr/app.json+++ b/web/locales/fr/app.json@@ -1,4 +1,5 @@{+ "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.",diff --git a/web/locales/pl/app.json b/web/locales/pl/app.jsonindex 497f3543c..ab05e69ab 100644--- a/web/locales/pl/app.json+++ b/web/locales/pl/app.json@@ -1,4 +1,5 @@{+ "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.",diff --git a/web/locales/uk/app.json b/web/locales/uk/app.jsonindex 8677346da..4de06ee49 100644--- a/web/locales/uk/app.json+++ b/web/locales/uk/app.json@@ -1,4 +1,5 @@{+ "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.": "Не вдалося видалити цю чернетку. Спробуйте ще раз або скопіюйте її перед виходом.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 76bbc0c6b..1306afdf9 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1,4 +1,5 @@{+ "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.": "无法丢弃此草稿。请重试,或在离开前复制内容。",diff --git a/web/tests/chat-failed-submission-recovery.spec.tsx b/web/tests/chat-failed-submission-recovery.spec.tsxindex 266db6c9d..a40d714e4 100644--- a/web/tests/chat-failed-submission-recovery.spec.tsx+++ b/web/tests/chat-failed-submission-recovery.spec.tsx@@ -6,6 +6,7 @@ import {useChatStateAdapter,} from "@/features/chat/ChatStateAdapter";import { initI18n } from "@/i18n/init";+import { updateRecoveryPrincipal } from "@/lib/recovery-principal";import {resetReadingTurnState, setReadingMaterial, setReadingViewport,setReadingWorkspace,@@ -34,6 +35,10 @@ 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> }>,+ replacementFails: false,+ replacementFailureAt: 0,+ replacementPending: null as Promise<void> | null,}));vi.mock("@/features/chat/transport/UnifiedTurnClient", () => ({@@ -62,6 +67,13 @@ vi.mock("@/features/chat/transport/UnifiedTurnClient", () => ({}));vi.mock("@/lib/session-api", () => ({+ 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 {@@ -138,7 +150,7 @@ function Harness() {const [discardResult, setDiscardResult] = useState<boolean | null>(null);const { state, sendMessage, resendLastMessage, loadSession, cancelStreamingTurn,configureSession, setPersonaSelection, setLLMSelection,- setReplyLanguageOverride, discardFailedSubmission, switchBranch } =+ setReplyLanguageOverride, discardFailedSubmission, switchBranch, editMessage, retryFailedSubmission } =useChatStateAdapter();return (<>@@ -148,6 +160,18 @@ function Harness() {<button onClick={() => sendMessage("Second offline")}>Send another</button><button onClick={() => sendMessage("", [{ type: "image", filename: "figure.png", base64: "YWJj" }])}>Send image only</button><button onClick={() => void resendLastMessage()}>Resend</button>+ <button onClick={() => {+ const draft = state.messages.find((message) => message.failedSubmission);+ if (typeof draft?.id === "number") void editMessage(draft.id, "Edited offline");+ }}>Edit first unsent</button>+ <button onClick={() => {+ const draft = state.messages.find((message) => message.failedSubmission);+ if (typeof draft?.id === "number") void editMessage(draft.id, "Second edit");+ }}>Edit second version</button>+ <button onClick={() => {+ const draft = state.messages.find((message) => message.failedSubmission);+ if (typeof draft?.id === "number") void retryFailedSubmission(draft.id);+ }}>Retry first unsent</button><button onClick={cancelStreamingTurn}>Stop</button><button onClick={() => {const draft = [...state.messages].reverse().find((message) => message.failedSubmission);@@ -238,6 +262,7 @@ function readStoredKeys() {}beforeEach(() => {+ updateRecoveryPrincipal({ enabled: false, authenticated: true });localStorage.clear();sessionStorage.clear();resetReadingTurnState();@@ -246,10 +271,132 @@ beforeEach(() => {fixture.deleted = [];fixture.emit = undefined;fixture.close = undefined;+ fixture.replacementCalls = [];+ fixture.replacementFails = false;+ 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;+ 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();@@ -309,7 +456,7 @@ 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.record.s1:")) throw new Error("target quota");+ 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]);@@ -327,7 +474,7 @@ it("does not erase a detectable same-ID retry advanced during retirement", () =>let advanced = false;vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {setItem(key, value);- if (!advanced && key === "deeptutor.failedSubmissions.cleared.s1:retry-id") {+ 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" } });@@ -986,11 +1133,11 @@ it("falls back to localStorage text when sessionStorage is unavailable", () => {expect(record?.content).toBe("Keep this text");expect(record?.retryRequiresReview).toBe(true);expect(localStorage.getItem(- "deeptutor.failedSubmissions.record.s1:" + record?.submissionId,+ "deeptutor.failedSubmissions.owner.single-user.record.s1:" + record?.submissionId,)).toContain("Keep this text");});-it("keeps the old session fallback's precedence, including an empty tombstone", () => {+it("preserves unowned legacy fallback data without exposing it to the current account", () => {const old = {submissionId: "old-map", content: "Stale map text", capability: "chat",requestSnapshot: { content: "Stale map text" }, savedAt: Date.now(),@@ -1001,9 +1148,9 @@ it("keeps the old session fallback's precedence, including an empty tombstone",sessionStorage.setItem("deeptutor.failedSubmissions.fallback.s1", JSON.stringify([{...old, submissionId: "fallback", content: "Fallback text",}]));- expect(readFailedSubmissions("s1").map((record) => record.content)).toEqual([- "Fallback text",- ]);+ expect(readFailedSubmissions("s1")).toEqual([]);+ expect(localStorage.getItem("deeptutor.failedSubmissions")).toContain("Stale map text");+ expect(sessionStorage.getItem("deeptutor.failedSubmissions.fallback.s1")).toContain("Fallback text");});it("saves to localStorage when the sessionStorage getter itself throws", () => {@@ -1017,7 +1164,7 @@ it("saves to localStorage when the sessionStorage getter itself throws", () => {});it("prunes expired records across sessions before falling back on quota", () => {- const staleKey = "deeptutor.failedSubmissions.record.old:stale";+ const staleKey = "deeptutor.failedSubmissions.owner.single-user.record.old:stale";localStorage.setItem(staleKey, JSON.stringify({submissionId: "stale", content: "Old attachment", capability: "chat",requestSnapshot: { content: "Old attachment", attachment: "A".repeat(10_000) },@@ -1025,7 +1172,7 @@ it("prunes expired records across sessions before falling back on quota", () =>}));const localSetItem = localStorage.setItem.bind(localStorage);vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {- if (key.startsWith("deeptutor.failedSubmissions.record.") &&+ if (key.startsWith("deeptutor.failedSubmissions.owner.single-user.record.") &&localStorage.getItem(staleKey)) {throw new DOMException("Quota", "QuotaExceededError");}@@ -1076,17 +1223,17 @@ it("binds a failed draft to its server session when no destination copy fits", (submissionId: "draft-a", content: "Full draft", capability: "chat",requestSnapshot: { content: "Full draft", attachment: "A".repeat(10_000) },});- const sourceKey = "deeptutor.failedSubmissions.record.draft%3Ageneral:draft-a";+ const sourceKey = "deeptutor.failedSubmissions.owner.single-user.record.draft%3Ageneral:draft-a";const localSetItem = localStorage.setItem.bind(localStorage);vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {- if (key.startsWith("deeptutor.failedSubmissions.record.s2:")) {+ if (key.startsWith("deeptutor.failedSubmissions.owner.single-user.record.s2:")) {throw new DOMException("Quota", "QuotaExceededError");}localSetItem(key, value);});const sessionSetItem = sessionStorage.setItem.bind(sessionStorage);vi.spyOn(sessionStorage, "setItem").mockImplementation((key, value) => {- if (key.startsWith("deeptutor.failedSubmissions.record.s2:")) {+ if (key.startsWith("deeptutor.failedSubmissions.owner.single-user.record.s2:")) {throw new DOMException("Quota", "QuotaExceededError");}sessionSetItem(key, value);@@ -1108,7 +1255,7 @@ it("keeps the durable draft source when its destination only fits in sessionStor});const localSetItem = localStorage.setItem.bind(localStorage);vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {- if (key.startsWith("deeptutor.failedSubmissions.record.s2:")) {+ if (key.startsWith("deeptutor.failedSubmissions.owner.single-user.record.s2:")) {throw new DOMException("Quota", "QuotaExceededError");}localSetItem(key, value);@@ -1128,7 +1275,7 @@ it("clears the bound draft source once the server accepts its submission", () =>});const localSetItem = localStorage.setItem.bind(localStorage);vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {- if (key.startsWith("deeptutor.failedSubmissions.record.s2:")) {+ if (key.startsWith("deeptutor.failedSubmissions.owner.single-user.record.s2:")) {throw new DOMException("Quota", "QuotaExceededError");}localSetItem(key, value);@@ -1138,7 +1285,7 @@ it("clears the bound draft source once the server accepts its submission", () =>expect(readFailedSubmissions("s2")).toEqual([]);expect(readFailedSubmissions("draft:general")).toEqual([]);expect(localStorage.getItem(- "deeptutor.failedSubmissions.record.draft%3Ageneral:draft-a",+ "deeptutor.failedSubmissions.owner.single-user.record.draft%3Ageneral:draft-a",)).toBeNull();});@@ -1177,7 +1324,7 @@ it("unions one tab's session fallback with another tab's local record", () => {},});expect(sessionStorage.getItem(- "deeptutor.failedSubmissions.record.s1:large-tab-a",+ "deeptutor.failedSubmissions.owner.single-user.record.s1:large-tab-a",)).toContain("Tab A attachment");storeFailedSubmission("s1", {submissionId: "small-tab-b", content: "Tab B text", capability: "chat",@@ -1196,10 +1343,10 @@ it("preserves an interleaved write from another tab while storing and clearing",const localSetItem = localStorage.setItem.bind(localStorage);let interleaved = false;vi.spyOn(localStorage, "setItem").mockImplementation((key, value) => {- if (!interleaved && key === "deeptutor.failedSubmissions.record.s1:tab-a") {+ if (!interleaved && key === "deeptutor.failedSubmissions.owner.single-user.record.s1:tab-a") {interleaved = true;// Tab B writes after A has prepared its value but before A commits.- localSetItem("deeptutor.failedSubmissions.record.s2:tab-b", JSON.stringify({+ localSetItem("deeptutor.failedSubmissions.owner.single-user.record.s2:tab-b", JSON.stringify({submissionId: "tab-b", content: "Tab B pending", capability: "chat",requestSnapshot: { content: "Tab B pending", language: "en" },savedAt: Date.now(),@@ -1217,9 +1364,9 @@ it("preserves an interleaved write from another tab while storing and clearing",const localRemoveItem = localStorage.removeItem.bind(localStorage);let interleavedClear = false;vi.spyOn(localStorage, "removeItem").mockImplementation((key) => {- if (!interleavedClear && key === "deeptutor.failedSubmissions.record.s1:tab-a") {+ if (!interleavedClear && key === "deeptutor.failedSubmissions.owner.single-user.record.s1:tab-a") {interleavedClear = true;- localSetItem("deeptutor.failedSubmissions.record.s2:tab-c", JSON.stringify({+ localSetItem("deeptutor.failedSubmissions.owner.single-user.record.s2:tab-c", JSON.stringify({submissionId: "tab-c", content: "Tab C pending", capability: "chat",requestSnapshot: { content: "Tab C pending", language: "en" },savedAt: Date.now(),diff --git a/web/tests/chat-unsent-message-actions.spec.tsx b/web/tests/chat-unsent-message-actions.spec.tsxindex e96bb434d..048b221c2 100644--- a/web/tests/chat-unsent-message-actions.spec.tsx+++ b/web/tests/chat-unsent-message-actions.spec.tsx@@ -1,4 +1,4 @@-import { render, screen, within } from "@testing-library/react";+import { act, render, screen, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { expect, it, vi } from "vitest";@@ -29,14 +29,42 @@ it("offers per-draft local discard, without requiring an assistant placeholder",expect(discard.mock.calls).toEqual([[-2], [-3]]);});-it("does not advertise unsupported editing for unsent local drafts", () => {+it("offers editing for unsent local drafts through the recovery handler", () => {render(<ChatMessageList messages={messages.slice(0, 2)} isStreaming={false}onCopyAssistantMessage={async () => undefined} onRegenerateMessage={() => undefined}onEditMessage={() => undefined} />);- expect(screen.queryByRole("button", { name: "Edit" })).toBeNull();+ expect(screen.getByRole("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.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);diff --git a/web/tests/failed-submission-account-isolation.spec.ts b/web/tests/failed-submission-account-isolation.spec.tsnew file mode 100644index 000000000..1569af336--- /dev/null+++ b/web/tests/failed-submission-account-isolation.spec.ts@@ -0,0 +1,150 @@+import { beforeEach, expect, it, vi } from "vitest";+import { fetchAuthStatus, invalidateAuthStatusCache } from "@/lib/auth";+import { RECOVERY_PRINCIPAL_CHANGED, recoveryPrincipal, updateRecoveryPrincipal } from "@/lib/recovery-principal";+import { clearFailedSubmission, moveFailedSubmissions, readFailedSubmissions, storeFailedSubmission } from "@/lib/failed-submissions";++const fixture = vi.hoisted(() => ({ fetch: vi.fn() }));+vi.mock("@/lib/api", () => ({ apiFetch: fixture.fetch, apiUrl: (path: string) => path, setRuntimeAuthEnabled: vi.fn() }));++beforeEach(() => {+ localStorage.clear();+ sessionStorage.clear();+ fixture.fetch.mockReset();+ invalidateAuthStatusCache();+});++async function principal(user: string | null, enabled = true) {+ invalidateAuthStatusCache();+ fixture.fetch.mockResolvedValue({ ok: true, json: async () => ({ enabled,+ authenticated: user !== null, user_id: user ?? undefined }) });+ await fetchAuthStatus();+}++function save(id = "same-id", content = "Private draft") {+ return storeFailedSubmission("draft:general", { submissionId: id, content,+ requestSnapshot: { content, capability: "chat", attachments: [{ name: "private.pdf" }] } });+}++it("fails closed before the server establishes a principal", () => {+ expect(save()).toBeNull();+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ expect(clearFailedSubmission("draft:general", "same-id")).toBe(false);+});++it("keeps each account's draft, attachment context and tombstones separate", async () => {+ await principal("account-a");+ expect(save()).toBe("same-id");+ await principal("account-b");+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ save("same-id", "Other account draft");+ clearFailedSubmission("draft:general", "same-id");+ await principal("account-a");+ expect(readFailedSubmissions("draft:general")[0].content).toBe("Private draft");+ expect(readFailedSubmissions("draft:general")[0].requestSnapshot).toMatchObject({ attachments: [{ name: "private.pdf" }] });+});++it("separates authenticated, logged-out, unavailable and single-user modes", async () => {+ await principal("account-a");+ save();+ await principal(null);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ expect(save()).toBeNull();+ await principal(null, false);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ save("single", "Single-user draft");+ invalidateAuthStatusCache();+ fixture.fetch.mockRejectedValue(new Error("offline"));+ await fetchAuthStatus();+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ await principal("account-a");+ expect(readFailedSubmissions("draft:general").map((r) => r.content)).toEqual(["Private draft"]);+});++it("preserves unowned legacy records without assigning them to any current account", async () => {+ const key = "deeptutor.failedSubmissions.record.draft%3Ageneral:legacy-id";+ const raw = JSON.stringify({ submissionId: "legacy-id", content: "Unowned private draft", savedAt: Date.now(),+ requestSnapshot: { content: "Unowned private draft" } });+ localStorage.setItem(key, raw);+ const legacyMap = JSON.stringify({ "draft:general": [JSON.parse(raw)] });+ localStorage.setItem("deeptutor.failedSubmissions", legacyMap);+ sessionStorage.setItem("deeptutor.failedSubmissions.fallback.draft%3Ageneral", raw);+ for (const user of ["account-a", null]) {+ await principal(user, user !== null);+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ expect(localStorage.getItem(key)).toBe(raw);+ expect(localStorage.getItem("deeptutor.failedSubmissions")).toBe(legacyMap);+ expect(sessionStorage.getItem("deeptutor.failedSubmissions.fallback.draft%3Ageneral")).toBe(raw);+ }+});++it("does not expose another account through draft-to-session bindings", async () => {+ await principal("account-a");+ save();+ const original = Storage.prototype.setItem;+ const quota = vi.spyOn(Storage.prototype, "setItem").mockImplementation(function (this: Storage, key, value) {+ if (key.includes(".record.same-session:")) throw new DOMException("Quota", "QuotaExceededError");+ return original.call(this, key, value);+ });+ expect(moveFailedSubmissions("draft:general", "same-session", ["same-id"])).toEqual(["same-id"]);+ quota.mockRestore();+ await principal("account-b");+ expect(readFailedSubmissions("same-session")).toEqual([]);+ clearFailedSubmission("same-session", "same-id");+ await principal("account-a");+ expect(readFailedSubmissions("same-session")[0].content).toBe("Private draft");+});++it("ignores an old auth response arriving after an account boundary", async () => {+ await principal("account-a");+ save();+ invalidateAuthStatusCache();+ let resolveOld!: (value: unknown) => void;+ fixture.fetch.mockReturnValueOnce(new Promise((resolve) => { resolveOld = resolve; }));+ const oldRequest = fetchAuthStatus();+ await principal("account-b");+ save("other", "Account B draft");+ resolveOld({ ok: true, json: async () => ({ enabled: true, authenticated: true, user_id: "account-a" }) });+ await oldRequest;+ expect(readFailedSubmissions("draft:general").map((r) => r.content)).toEqual(["Account B draft"]);+});++it("invalidates synchronously across tabs and resolves identity from the server, not the signal", async () => {+ await principal("account-a");+ save();+ fixture.fetch.mockResolvedValue({ ok: true, json: async () => ({ enabled: true,+ authenticated: true, user_id: "account-b" }) });+ window.dispatchEvent(new StorageEvent("storage", {+ key: "deeptutor.authBoundary", newValue: "user:account-a",+ }));+ expect(recoveryPrincipal()).toBeNull();+ expect(readFailedSubmissions("draft:general")).toEqual([]);+ await fetchAuthStatus();+ expect(recoveryPrincipal()).toBe("user:account-b");+ expect(readFailedSubmissions("draft:general")).toEqual([]);+});++it("emits one boundary event only when the effective principal changes", () => {+ const listener = vi.fn();+ window.addEventListener(RECOVERY_PRINCIPAL_CHANGED, listener);+ updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "account-a" });+ updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "account-a" });+ expect(listener).toHaveBeenCalledTimes(1);+ updateRecoveryPrincipal({ enabled: true, authenticated: true });+ expect(recoveryPrincipal()).toBeNull();+ expect(listener).toHaveBeenCalledTimes(2);+ window.removeEventListener(RECOVERY_PRINCIPAL_CHANGED, listener);+});++it("isolates two tab runtimes sharing local storage with different resolved principals", async () => {+ await principal("account-a");+ save();+ vi.resetModules();+ const otherPrincipal = await import("@/lib/recovery-principal");+ const otherRecovery = await import("@/lib/failed-submissions");+ otherPrincipal.updateRecoveryPrincipal({ enabled: true, authenticated: true, user_id: "account-b" });+ expect(otherRecovery.readFailedSubmissions("draft:general")).toEqual([]);+ otherRecovery.storeFailedSubmission("draft:general", { submissionId: "same-id", content: "B only",+ requestSnapshot: { content: "B only" } });+ otherRecovery.clearFailedSubmission("draft:general", "same-id");+ expect(readFailedSubmissions("draft:general")[0].content).toBe("Private draft");+});diff --git a/web/tests/optimistic-id.test.ts b/web/tests/optimistic-id.test.tsindex 60fb25bc9..3eed6720a 100644--- a/web/tests/optimistic-id.test.ts+++ b/web/tests/optimistic-id.test.ts@@ -30,10 +30,10 @@ test("optimistic ids are negative and strictly decreasing", () => {// loadSession just returned instead of immediately reading the stale ref.test("an optimistic message resolves from the returned refresh snapshot", async () => {const optimistic = [- { id: -100, role: "user", content: "question", parentMessageId: 10 },+ { id: -100, role: "user", content: "question", parentMessageId: 10, failedSubmissionId: "ours" },];const persisted = [- { id: 11, role: "user", content: "question", parentMessageId: 10 },+ { id: 11, role: "user", content: "question", parentMessageId: 10, failedSubmissionId: "ours" },];const resolved = await resolvePersistedMessage(@@ -51,11 +51,11 @@ test("an optimistic message resolves from the returned refresh snapshot", async// edit path). Both mutations must trust the refresh snapshot's id.test("deleteTurn-style resolution keeps working when the state ref is stale", async () => {const staleRef = [- { id: -42, role: "user", content: "to delete", parentMessageId: 1 },+ { id: -42, role: "user", content: "to delete", parentMessageId: 1, failedSubmissionId: "delete-ours" },{ id: -43, role: "assistant", content: "reply", parentMessageId: -42 },];const serverSnapshot = [- { id: 201, role: "user", content: "to delete", parentMessageId: 1 },+ { id: 201, role: "user", content: "to delete", parentMessageId: 1, metadata: { client_submission_id: "delete-ours" } },{ id: 202, role: "assistant", content: "reply", parentMessageId: 201 },];@@ -70,6 +70,15 @@ test("deleteTurn-style resolution keeps working when the state ref is stale", asassert.equal(staleRef[0].id, -42);});+test("optimistic mutations follow causal identity across reordered identical rows", async () => {+ const original: Array<{ id: number; role: string; failedSubmissionId?: string; metadata?: Record<string, unknown> }> =+ [{ id: -1, role: "user", failedSubmissionId: "ours" }];+ const remote = [{ id: 99, role: "user", metadata: { client_submission_id: "theirs" } },+ { id: 100, role: "user", metadata: { client_submission_id: "ours" } }];+ assert.equal((await resolvePersistedMessage(original, -1, "user", async () => remote))?.id, 100);+ assert.equal(await resolvePersistedMessage(original, -1, "user", async () => remote.slice(0, 1)), undefined);+});+// Issue #698: the user row and the assistant placeholder are minted// back-to-back (ADD_USER_MSG then STREAM_START). When they shared an id, the// remap in reconcileTurnIds collapsed both onto the user's persisted id, so