Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(turns): make lost-ack resends reuse the original conversation (#1793)

Bingxi Zhao (Frank)d15e35a378a2
diff --git a/deeptutor/app/service.py b/deeptutor/app/service.py
index 9c999b27d..e0474bb1b 100644
--- a/deeptutor/app/service.py
+++ b/deeptutor/app/service.py
@@ -5,6 +5,8 @@ from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
import contextlib
+import hashlib
+import json
import time
from typing import Any
@@ -48,9 +50,39 @@ class TurnApplicationService:
with workspace_context(payload.get("workspace_id")):
return await self.start_turn(payload)
store, runtime = self._resolve()
+ reserve = getattr(store, "reserve_submission", None)
+ if (
+ request.client_submission_id
+ and request.persist_user_message
+ and not request.regenerate
+ and callable(reserve)
+ ):
+ 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()
+ payload["session_id"] = await reserve(
+ request.client_submission_id, digest, request.session_id
+ )
+ prior = await store.submission_turn(request.client_submission_id)
+ if prior is not None and prior["status"] not in {"failed", "cancelled"}:
+ session = await store.get_session(payload["session_id"])
+ if session is None:
+ raise RuntimeError("Conversation not found in this workspace.")
+ return session, prior
try:
session, turn = await runtime.start_turn(payload)
except ActiveTurnConflict:
+ if request.client_submission_id and callable(reserve):
+ prior = await store.submission_turn(request.client_submission_id)
+ if prior is not None:
+ session = await store.get_session(prior["session_id"])
+ if session is not None:
+ return session, prior
# Retry once, and only after something was actually reclaimed, so a
# session busy with a live turn still gets its conflict.
session_id = str(payload.get("session_id") or "")
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index a9396cfc6..d15346659 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -9,6 +9,13 @@ from __future__ import annotations
from typing import Any, Protocol, runtime_checkable
+# Internal admission fields shared by the store and turn runtime. The runtime
+# consumes them before returning a public turn receipt (#1793).
+SUBMISSION_REPLAY_FIELD = "_submission_replay"
+SUBMISSION_USER_FIELD = "_submission_user_message_id"
+SUBMISSION_ASSISTANT_FIELD = "_submission_assistant_message_id"
+SUBMISSION_PREVIOUS_TURN_FIELD = "_submission_previous_turn_id"
+
class ActiveTurnConflict(RuntimeError):
"""A session already owns a turn that has not reached a terminal state.
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index 60401b334..6bb741bb6 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -29,7 +29,13 @@ from deeptutor.core.assessment import (
QUESTION_ORIGIN_TYPES,
)
from deeptutor.services.path_service import get_path_service
-from deeptutor.services.session.protocol import ActiveTurnConflict
+from deeptutor.services.session.protocol import (
+ SUBMISSION_ASSISTANT_FIELD,
+ SUBMISSION_PREVIOUS_TURN_FIELD,
+ SUBMISSION_REPLAY_FIELD,
+ SUBMISSION_USER_FIELD,
+ ActiveTurnConflict,
+)
from deeptutor.utils.secret_files import ensure_private_directory, ensure_private_file
from .ask_user_trace import select_ask_user_events
@@ -341,6 +347,14 @@ class SQLiteSessionStore:
CREATE INDEX IF NOT EXISTS idx_turns_session_status
ON turns(session_id, status, updated_at DESC);
+ CREATE TABLE IF NOT EXISTS turn_submissions (
+ client_submission_id TEXT PRIMARY KEY,
+ workspace_id TEXT NOT NULL DEFAULT '',
+ request_digest TEXT NOT NULL,
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ turn_id TEXT REFERENCES turns(id) ON DELETE SET NULL
+ );
+
CREATE TABLE IF NOT EXISTS turn_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
turn_id TEXT NOT NULL REFERENCES turns(id) ON DELETE CASCADE,
@@ -1123,6 +1137,12 @@ class SQLiteSessionStore:
self,
title: str | None = None,
session_id: str | None = None,
+ ) -> dict[str, Any]:
+ with self._connect() as conn:
+ return self._insert_session(conn, title, session_id)
+
+ def _insert_session(
+ self, conn: sqlite3.Connection, title: str | None = None, session_id: str | None = None
) -> dict[str, Any]:
now = time.time()
resolved_id = session_id or f"unified_{int(now * 1000)}_{uuid.uuid4().hex[:8]}"
@@ -1131,18 +1151,13 @@ class SQLiteSessionStore:
scope = get_workspace_scope()
preferences = {"workspace_id": scope.workspace_id} if scope is not None else {}
- with self._connect() as conn:
- conn.execute(
- """
- INSERT INTO sessions (
- id, title, created_at, updated_at,
- compressed_summary, summary_up_to_msg_id, preferences_json
- )
- VALUES (?, ?, ?, ?, '', 0, ?)
- """,
- (resolved_id, resolved_title[:100], now, now, _json_dumps(preferences)),
- )
- conn.commit()
+ conn.execute(
+ """INSERT INTO sessions (
+ id, title, created_at, updated_at,
+ compressed_summary, summary_up_to_msg_id, preferences_json
+ ) VALUES (?, ?, ?, ?, '', 0, ?)""",
+ (resolved_id, resolved_title[:100], now, now, _json_dumps(preferences)),
+ )
return {
"id": resolved_id,
"session_id": resolved_id,
@@ -1161,6 +1176,68 @@ class SQLiteSessionStore:
) -> dict[str, Any]:
return await self._run(self._create_session_sync, title, session_id)
+ def _reserve_submission_sync(
+ self, submission_id: str, digest: str, session_id: str | None
+ ) -> str:
+ from deeptutor.services.workspace.context import get_workspace_scope
+
+ scope = get_workspace_scope()
+ workspace_id = scope.workspace_id if scope is not None else ""
+ with self._connect() as conn:
+ # #1793: bind a first submission and its conversation atomically,
+ # before the transport can lose the SESSION acknowledgement.
+ conn.execute("BEGIN IMMEDIATE")
+ prior = conn.execute(
+ "SELECT * FROM turn_submissions WHERE client_submission_id = ?", (submission_id,)
+ ).fetchone()
+ if prior is not None:
+ if prior["request_digest"] != digest or prior["workspace_id"] != workspace_id:
+ raise RuntimeError(
+ "This submission ID belongs to a different request or workspace."
+ )
+ if session_id and session_id != prior["session_id"]:
+ raise RuntimeError("This submission ID belongs to another conversation.")
+ row = conn.execute(
+ "SELECT deleted_at FROM sessions WHERE id = ?", (prior["session_id"],)
+ ).fetchone()
+ if row is None or row["deleted_at"] is not None:
+ raise RuntimeError(
+ "Restore the original conversation before resending this message."
+ )
+ return str(prior["session_id"])
+ if session_id:
+ row = conn.execute(
+ "SELECT * FROM sessions WHERE id = ? AND deleted_at IS NULL", (session_id,)
+ ).fetchone()
+ if row is None:
+ raise RuntimeError("Conversation not found in this workspace.")
+ preferences = _json_loads(row["preferences_json"], {})
+ if str(preferences.get("workspace_id") or "") != workspace_id:
+ raise RuntimeError("The conversation belongs to another workspace.")
+ else:
+ session_id = str(self._insert_session(conn)["id"])
+ conn.execute(
+ "INSERT INTO turn_submissions (client_submission_id, workspace_id, request_digest, session_id) VALUES (?, ?, ?, ?)",
+ (submission_id, workspace_id, digest, session_id),
+ )
+ return session_id
+
+ async def reserve_submission(
+ self, submission_id: str, digest: str, session_id: str | None = None
+ ) -> str:
+ return await self._run(self._reserve_submission_sync, submission_id, digest, session_id)
+
+ def _submission_turn_sync(self, submission_id: str) -> dict[str, Any] | None:
+ with self._connect() as conn:
+ row = conn.execute(
+ "SELECT t.* FROM turns t JOIN turn_submissions s ON s.turn_id=t.id WHERE s.client_submission_id=?",
+ (submission_id,),
+ ).fetchone()
+ return self._serialize_turn(row) if row is not None else None
+
+ async def submission_turn(self, submission_id: str) -> dict[str, Any] | None:
+ return await self._run(self._submission_turn_sync, submission_id)
+
async def ensure_notebook_session(self, session_id: str, title: str) -> bool:
"""Insert a placeholder session row so notebook-only sources can file
entries against it (partner chat has no rows in this store otherwise).
@@ -1286,9 +1363,11 @@ class SQLiteSessionStore:
turn_id: str | None = None,
owner_id: str = "",
fencing_token: int = 0,
+ submission_id: str | None = None,
) -> dict[str, Any]:
now = time.time()
resolved_turn_id = turn_id or f"turn_{int(now * 1000)}_{uuid.uuid4().hex[:10]}"
+ replay_fields: dict[str, Any] = {}
try:
with self._connect() as conn:
# Serialize the active-turn check and insert across processes.
@@ -1298,6 +1377,24 @@ class SQLiteSessionStore:
).fetchone()
if session is None:
raise ValueError(f"Session not found: {session_id}")
+ if submission_id:
+ 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),
+ ).fetchone()
+ if old is not None:
+ if old["status"] not in {"failed", "cancelled"}:
+ return {**self._serialize_turn(old), SUBMISSION_REPLAY_FIELD: True}
+ 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, submission_id),
+ ).fetchone()
+ if user is not None:
+ replay_fields = {
+ SUBMISSION_USER_FIELD: user["id"],
+ SUBMISSION_ASSISTANT_FIELD: old["assistant_message_id"],
+ SUBMISSION_PREVIOUS_TURN_FIELD: old["id"],
+ }
active = conn.execute(
"""
SELECT id
@@ -1332,11 +1429,17 @@ class SQLiteSessionStore:
max(0, int(fencing_token)),
),
)
+ if submission_id:
+ conn.execute(
+ "UPDATE turn_submissions SET turn_id=? WHERE client_submission_id=? AND session_id=?",
+ (resolved_turn_id, submission_id, session_id),
+ )
except sqlite3.IntegrityError as exc:
# The partial unique index wins races where another process inserts
# after our read but before our insert.
raise ActiveTurnConflict(f"Session already has an active turn: {session_id}") from exc
return {
+ **replay_fields,
"id": resolved_turn_id,
"turn_id": resolved_turn_id,
"session_id": session_id,
@@ -1362,6 +1465,7 @@ class SQLiteSessionStore:
turn_id: str | None = None,
owner_id: str = "",
fencing_token: int = 0,
+ submission_id: str | None = None,
) -> dict[str, Any]:
return await self._run(
self._begin_turn_sync,
@@ -1370,10 +1474,14 @@ class SQLiteSessionStore:
turn_id,
owner_id,
fencing_token,
+ submission_id,
)
- async def create_turn(self, session_id: str, capability: str = "") -> dict[str, Any]:
- return await self.begin_turn(session_id, capability)
+ async def create_turn(
+ self, session_id: str, capability: str = "", *, submission_id: str | None = None
+ ) -> dict[str, Any]:
+ kwargs = {"submission_id": submission_id} if submission_id else {}
+ return await self.begin_turn(session_id, capability, **kwargs)
def _get_turn_sync(self, turn_id: str) -> dict[str, Any] | None:
with self._connect() as conn:
diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.py
index d047945b9..b0448c2b1 100644
--- a/deeptutor/services/session/turns/executor.py
+++ b/deeptutor/services/session/turns/executor.py
@@ -1169,10 +1169,13 @@ class TurnExecutor:
# Attach the persisted row ids so the frontend can reconcile its
# optimistic (negative) message ids with a targeted in-place swap
# instead of refetching and re-rendering the whole session.
+ accepted_user_message_id = new_user_message_id
+ if accepted_user_message_id is None and is_regenerate:
+ accepted_user_message_id = payload.get("regenerated_from_message_id")
persisted_ids = {
key: value
for key, value in (
- ("user_message_id", new_user_message_id),
+ ("user_message_id", accepted_user_message_id),
("assistant_message_id", assistant_message_id),
)
if value
diff --git a/deeptutor/services/session/turns/request_preparer.py b/deeptutor/services/session/turns/request_preparer.py
index 17e246c10..d7bd2d913 100644
--- a/deeptutor/services/session/turns/request_preparer.py
+++ b/deeptutor/services/session/turns/request_preparer.py
@@ -11,6 +11,12 @@ import uuid
from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.core.turn_request import TurnRequest
from deeptutor.runtime.capability_routing import route_explicit_quiz_request
+from deeptutor.services.session.protocol import (
+ SUBMISSION_ASSISTANT_FIELD,
+ SUBMISSION_PREVIOUS_TURN_FIELD,
+ SUBMISSION_REPLAY_FIELD,
+ SUBMISSION_USER_FIELD,
+)
from deeptutor.services.session.workspace_preferences import (
WORKSPACE_MODE_MASTERY,
WORKSPACE_MODE_READING,
@@ -682,8 +688,18 @@ class TurnRequestPreparer:
if not payload.get("preserve_session_preferences"):
await self.store.update_session_preferences(session["id"], preference_update)
try:
+ submission_kwargs = {}
+ if (
+ payload.get("client_submission_id")
+ and payload.get("persist_user_message", True)
+ and not payload.get("regenerate")
+ and callable(getattr(self.store, "reserve_submission", None))
+ ):
+ submission_kwargs["submission_id"] = payload["client_submission_id"]
if lease is None:
- turn = await self.store.create_turn(session["id"], capability=capability)
+ turn = await self.store.create_turn(
+ session["id"], capability=capability, **submission_kwargs
+ )
else:
turn = await self.store.begin_turn(
session["id"],
@@ -691,12 +707,30 @@ class TurnRequestPreparer:
turn_id=lease.turn_id,
owner_id=lease.owner_id,
fencing_token=lease.fencing_token,
+ **submission_kwargs,
)
except Exception:
if lease is not None and self.coordinator is not None:
with contextlib.suppress(Exception):
await self.coordinator.release_turn(lease)
raise
+ if turn.pop(SUBMISSION_REPLAY_FIELD, False):
+ if lease is not None and self.coordinator is not None:
+ await self.coordinator.release_turn(lease)
+ return session, turn
+ user_message_id = turn.pop(SUBMISSION_USER_FIELD, None)
+ prior_assistant_id = turn.pop(SUBMISSION_ASSISTANT_FIELD, None)
+ prior_turn_id = turn.pop(SUBMISSION_PREVIOUS_TURN_FIELD, None)
+ if user_message_id is not None:
+ payload = {
+ **payload,
+ "persist_user_message": False,
+ "regenerate": True,
+ "regenerated_from_message_id": user_message_id,
+ "superseded_turn_id": prior_turn_id,
+ }
+ if replace_assistant_message_id is None:
+ replace_assistant_message_id = prior_assistant_id
execution = _TurnExecution(
turn_id=turn["id"],
session_id=session["id"],
diff --git a/tests/app/test_turn_application_service.py b/tests/app/test_turn_application_service.py
index 30c24e5a6..147fd5e16 100644
--- a/tests/app/test_turn_application_service.py
+++ b/tests/app/test_turn_application_service.py
@@ -1,11 +1,13 @@
from __future__ import annotations
import asyncio
+from types import SimpleNamespace
import pytest
from deeptutor.app.container import RuntimeRegistry
from deeptutor.app.service import TurnApplicationService
+from deeptutor.core.stream import StreamEvent, StreamEventType
from deeptutor.runtime.coordination import MemoryCoordinator
from deeptutor.services.session.sqlite_store import SQLiteSessionStore
from deeptutor.services.session.turn_runtime import _TurnExecution
@@ -31,6 +33,116 @@ def _service(
)
+def submission_service(monkeypatch, tmp_path):
+ from deeptutor.services.path_service import PathService
+ from deeptutor.services.session.turns.title_service import SessionTitleService
+
+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))
+ monkeypatch.setattr(PathService, "_instance", PathService(workspace_root=tmp_path / "data"))
+ calls = {"count": 0, "fail": False}
+
+ class Builder:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ async def build(self, **kwargs):
+ return SimpleNamespace(
+ conversation_history=[],
+ conversation_summary="",
+ context_text="",
+ token_count=0,
+ budget=0,
+ )
+
+ class Orchestrator:
+ async def handle(self, context):
+ calls["count"] += 1
+ if calls["fail"]:
+ from deeptutor.services.llm.exceptions import LLMProviderTransportError
+
+ raise LLMProviderTransportError("controlled upstream failure")
+ yield StreamEvent(
+ type=StreamEventType.CONTENT,
+ content="Recovered answer",
+ source="chat",
+ metadata={"call_kind": "llm_final_response"},
+ )
+ yield StreamEvent(type=StreamEventType.DONE, source="chat")
+
+ async def noop(*args, **kwargs):
+ pass
+
+ monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())
+ monkeypatch.setattr("deeptutor.services.session.context_builder.ContextBuilder", Builder)
+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", Orchestrator)
+ monkeypatch.setattr(
+ "deeptutor.services.memory.get_memory_store", lambda: SimpleNamespace(emit=noop)
+ )
+ monkeypatch.setattr(SessionTitleService, "_maybe_generate_session_title", noop)
+ store = SQLiteSessionStore(tmp_path / "submissions.db")
+ coordinator = MemoryCoordinator(lease_ttl_seconds=30)
+ service, registry = _service(store, coordinator, "worker-a")
+ return service, store, coordinator, registry, calls
+
+
+async def test_lost_first_session_ack_replays_the_same_submission_after_worker_restart(
+ submission_service,
+):
+ service, store, coordinator, _registry, calls = submission_service
+ payload = {"content": "Hello", "client_submission_id": "lost-first-ack"}
+ first_session, first_turn = await service.start_turn(payload)
+ [event async for event in service.subscribe_turn(first_turn["id"])]
+ restarted_store = SQLiteSessionStore(store.db_path)
+ restarted, _ = _service(restarted_store, coordinator, "worker-b")
+ second_session, second_turn = await restarted.start_turn(payload)
+ assert second_session["id"] == first_session["id"]
+ assert second_turn["id"] == first_turn["id"]
+ assert calls["count"] == 1
+ assert len(await store.list_sessions()) == 1
+ assert [row["role"] for row in await store.get_messages(first_session["id"])] == [
+ "user",
+ "assistant",
+ ]
+
+
+async def test_failed_first_submission_resends_in_its_original_conversation_without_a_duplicate_user(
+ submission_service,
+):
+ service, store, _coordinator, _registry, calls = submission_service
+ payload = {"content": "Hello", "client_submission_id": "failed-first-ack"}
+ calls["fail"] = True
+ first_session, failed_turn = await service.start_turn(payload)
+ [event async for event in service.subscribe_turn(failed_turn["id"])]
+ original_user = await store.get_last_message(first_session["id"], role="user")
+ assert original_user is not None
+ calls["fail"] = False
+ session, retried_turn = await service.start_turn(payload)
+ events = [event async for event in service.subscribe_turn(retried_turn["id"])]
+ assert session["id"] == first_session["id"]
+ assert retried_turn["id"] != failed_turn["id"]
+ rows = await store.get_messages(session["id"])
+ assert [row["role"] for row in rows] == ["user", "assistant"]
+ assert rows[0]["id"] == original_user["id"]
+ done = next(event for event in events if event["type"] == "done")
+ assert done["metadata"]["user_message_id"] == original_user["id"]
+ assert calls["count"] == 2
+
+
+async def test_submission_key_cannot_be_reused_for_different_content(submission_service):
+ service, store, _coordinator, _registry, calls = submission_service
+ payload = {"content": "Hello", "client_submission_id": "same-key"}
+ session, turn = await service.start_turn(payload)
+ [event async for event in service.subscribe_turn(turn["id"])]
+ with pytest.raises(RuntimeError, match="different request"):
+ await service.start_turn({**payload, "content": "Changed input"})
+ assert len(await store.list_sessions()) == 1
+ assert calls["count"] == 1
+
+
@pytest.mark.asyncio
async def test_second_worker_reads_shared_event_tail_without_mutating_turn(tmp_path) -> None:
db_path = tmp_path / "chat_history.db"
diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.py
index f5c8f9fbb..5ba24842c 100644
--- a/tests/services/session/test_sqlite_store.py
+++ b/tests/services/session/test_sqlite_store.py
@@ -30,6 +30,53 @@ def test_sqlite_store_defaults_to_data_user_chat_history_db(tmp_path: Path) -> N
service._user_data_dir = original_user_dir
+async def test_submission_reservation_and_admission_are_atomic_across_workers(tmp_path):
+ """#1793: duplicate transport retries cannot allocate separate chats or turns."""
+ stores = [SQLiteSessionStore(tmp_path / "shared.db") for _ in range(2)]
+ sessions = await asyncio.gather(
+ *(store.reserve_submission("same-submission", "digest") for store in stores)
+ )
+ assert sessions[0] == sessions[1]
+ turns = await asyncio.gather(
+ *(store.begin_turn(sessions[0], submission_id="same-submission") for store in stores)
+ )
+ assert turns[0]["id"] == turns[1]["id"]
+ assert sum(bool(turn.get("_submission_replay")) for turn in turns) == 1
+ assert len(await stores[0].list_sessions()) == 1
+
+
+async def test_submission_identity_does_not_cross_accounts_or_workspaces(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"])
+ )
+ first = SQLiteSessionStore(tmp_path / "account-one.db")
+ second = SQLiteSessionStore(tmp_path / "account-two.db")
+ one = await first.reserve_submission("same-key", "same-digest")
+ two = await second.reserve_submission("same-key", "same-digest")
+ assert one != two
+ scope["id"] = "two"
+ with pytest.raises(RuntimeError, match="different request or workspace"):
+ await first.reserve_submission("same-key", "same-digest")
+ assert len(await first.list_sessions()) == 1
+
+
+async def test_resend_does_not_recreate_a_recycled_conversation(tmp_path):
+ store = SQLiteSessionStore(tmp_path / "deleted.db")
+ session_id = await store.reserve_submission("original", "digest")
+ await store.soft_delete_session(session_id)
+ with pytest.raises(RuntimeError, match="Restore the original conversation"):
+ await store.reserve_submission("original", "digest")
+ assert len(await store.list_deleted_sessions()) == 1
+
+
def test_sqlite_store_migrates_legacy_chat_history_db(tmp_path: Path) -> None:
service = PathService.get_instance()
original_root = service._project_root
diff --git a/web/features/chat/ChatStateAdapter.tsx b/web/features/chat/ChatStateAdapter.tsx
index 2f5359402..3a910f8fe 100644
--- a/web/features/chat/ChatStateAdapter.tsx
+++ b/web/features/chat/ChatStateAdapter.tsx
@@ -2949,7 +2949,7 @@ export function ChatStateAdapterProvider({
options?.displayUserMessage !== false &&
!options?.masteryAnswer &&
!options?.masterySkip &&
- content.trim() !== "";
+ (content.trim() !== "" || Boolean(effectiveAttachments?.length));
const submissionId = options?.retrySubmissionId ??
(trackNewSubmission ? randomUuid() : undefined);
const persistSubmission = Boolean(submissionId) &&
diff --git a/web/features/chat/controllers/buildStartTurnInput.ts b/web/features/chat/controllers/buildStartTurnInput.ts
index 19b76b00d..30b776444 100644
--- a/web/features/chat/controllers/buildStartTurnInput.ts
+++ b/web/features/chat/controllers/buildStartTurnInput.ts
@@ -49,7 +49,9 @@ function capabilityConfig(input: StartTurnInput): Record<string, unknown> {
}
export function buildStartTurnInput(input: StartTurnInput): StartTurnCommand {
- if (!input.content.trim()) invalid("Turn content must not be empty");
+ if (!input.content.trim() && !input.attachments?.length) {
+ invalid("Turn content must not be empty");
+ }
if (input.subagentConsultBudget != null && input.subagentConsultBudget < 0) {
invalid("Subagent consult budget must be non-negative");
}
diff --git a/web/lib/failed-submissions.ts b/web/lib/failed-submissions.ts
index 729038592..712eacf7b 100644
--- a/web/lib/failed-submissions.ts
+++ b/web/lib/failed-submissions.ts
@@ -53,11 +53,18 @@ function bindingPrefix(sessionId: string): string {
return BINDING_PREFIX + encodeURIComponent(sessionId) + ":";
}
+function hasSubmissionPayload(content: string, snapshot: unknown): boolean {
+ if (content.trim()) return true;
+ if (!snapshot || typeof snapshot !== "object") return false;
+ const attachments = (snapshot as Record<string, unknown>).attachments;
+ return Array.isArray(attachments) && attachments.length > 0;
+}
+
function isRecord(value: unknown): value is FailedSubmissionRecord {
if (!value || typeof value !== "object") return false;
const record = value as Partial<FailedSubmissionRecord>;
return typeof record.content === "string" &&
- record.content.trim() !== "" &&
+ hasSubmissionPayload(record.content, record.requestSnapshot) &&
Boolean(record.requestSnapshot) &&
typeof record.savedAt === "number";
}
@@ -207,6 +214,9 @@ function persistRecord(sessionId: string, record: FailedSubmissionRecord): Persi
// Each submission has its own key. A large attachment or a concurrent tab
// can never overwrite a different pending message's local record.
const sessionFull = browserStorage.writeRaw("session", key, full);
+ // A media-only submission has no useful text fallback. Never report an
+ // empty, attachment-free record as safely recoverable (#1793).
+ if (!record.content.trim()) return sessionFull ? "session_full" : null;
const textOnly = JSON.stringify(textOnlyRecord(record));
if (browserStorage.writeRaw("local", key, textOnly)) {
// Retain the full same-tab copy if it fits, so retry can keep attachments
@@ -277,7 +287,7 @@ export function storeFailedSubmission(
priorMatchingUserIds?: string[];
},
): string | null {
- if (!sessionId || submission.content.trim() === "") return null;
+ if (!sessionId || !hasSubmissionPayload(submission.content, submission.requestSnapshot)) return null;
const submissionId = submission.submissionId ?? randomUuid();
const record: FailedSubmissionRecord = {
content: submission.content,
diff --git a/web/tests/chat-failed-submission-recovery.spec.tsx b/web/tests/chat-failed-submission-recovery.spec.tsx
index cb2c40525..d66afe46a 100644
--- a/web/tests/chat-failed-submission-recovery.spec.tsx
+++ b/web/tests/chat-failed-submission-recovery.spec.tsx
@@ -144,6 +144,7 @@ function Harness() {
<button onClick={() => void loadSession("new-session")}>Load new</button>
<button onClick={() => sendMessage("Hello offline")}>Send</button>
<button onClick={() => sendMessage("Second offline")}>Send another</button>
+ <button onClick={() => sendMessage("", [{ type: "image", filename: "figure.png", base64: "YWJj" }])}>Send image only</button>
<button onClick={() => void resendLastMessage()}>Resend</button>
<button onClick={cancelStreamingTurn}>Stop</button>
<button onClick={() => {
@@ -232,6 +233,20 @@ beforeEach(() => {
afterEach(() => vi.restoreAllMocks());
+it("tracks attachment-only submissions with a stable identity for resend", async () => {
+ fixture.connected = true;
+ render(<ChatStateAdapterProvider><Harness /></ChatStateAdapterProvider>);
+ fireEvent.click(screen.getByRole("button", { name: "Send image only" }));
+ await act(async () => {});
+ const sent = fixture.sent.find((message) => message.type === "start_turn");
+ expect(sent?.client_submission_id).toBeTruthy();
+ const draft = readFailedSubmissions("draft:general");
+ expect(draft).toHaveLength(1);
+ expect(draft[0].submissionId).toBe(sent?.client_submission_id);
+ const snapshot = draft[0].requestSnapshot as { attachments: Array<{ filename: string }> };
+ expect(snapshot.attachments[0].filename).toBe("figure.png");
+});
+
it("restores a persisted worker loss and retries the same mastery answer snapshot", async () => {
fixture.session = {
...completedServerSession(),
diff --git a/web/tests/start-turn-input.test.ts b/web/tests/start-turn-input.test.ts
index 8b77bd33b..01b82ca40 100644
--- a/web/tests/start-turn-input.test.ts
+++ b/web/tests/start-turn-input.test.ts
@@ -8,6 +8,14 @@ import {
import type { StartTurnInput } from "../features/chat/model/start-turn";
import { ApiError } from "../shared/api/errors";
+test("media-only turns are valid while a completely empty turn is rejected", () => {
+ const attachments = [{ type: "image" as const, filename: "figure.png", base64: "YWJj" }];
+ const wire = buildStartTurnInput({ content: "", attachments });
+ assert.equal(wire.content, "");
+ assert.deepEqual(wire.attachments, attachments);
+ assert.throws(() => buildStartTurnInput({ content: "", attachments: [] }), /must not be empty/);
+});
+
test("plain, quiz, research, and visualize turns use one typed mapper", () => {
const matrix: StartTurnInput[] = [
{ content: "hello", capability: "chat" },