Skip to content

The agent that grows with you

fix: desktop saves the first message at send time and session tabs survive a profile rename

teknium12f273962dbab
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md
index eac0d0f4a68..ae540cca9de 100644
--- a/apps/desktop/AGENTS.md
+++ b/apps/desktop/AGENTS.md
@@ -56,6 +56,19 @@ that must outlive compression keys off the lineage root. Keep the mapping betwee
them explicit and translate at the boundary rather than passing the wrong id
inward.
+Two guarantees follow from this (#111868). The user's message is durable at
+send: `prompt.submit` writes the session row AND the user row before the agent
+build starts, and the turn adopts that row (`_adopt_submit_user_row` →
+`agent._pending_cli_user_message`) instead of appending a second one, so a
+freeze or force-quit during a slow first build leaves a resumable transcript
+(user message present, no reply). And renderer state keyed by profile name —
+persisted tabs (`tilesByProfile`), Bot tile owner routes, cached transcript
+tails, remembered session/route, session owner hints — follows a profile
+rename via `migrateTilesForProfile(old, new)` (`store/session-states.ts`), the
+rename sibling of `dropTilesForProfile`. Add any new profile-keyed localStorage
+family to BOTH, or a rename leaves it pointing at a backend that no longer
+exists ("Couldn't open this session" on every restore).
+
## Server truth is cached, not owned
The renderer paints from a cache of backend truth, so it must reconcile, not
diff --git a/apps/desktop/src/app/profiles/rename-profile-dialog.test.tsx b/apps/desktop/src/app/profiles/rename-profile-dialog.test.tsx
index 7f4089f7907..a9b48e79c49 100644
--- a/apps/desktop/src/app/profiles/rename-profile-dialog.test.tsx
+++ b/apps/desktop/src/app/profiles/rename-profile-dialog.test.tsx
@@ -3,6 +3,7 @@ import { afterEach, expect, it, vi } from 'vitest'
import { renameProfile } from '@/hermes'
import { retireLocalProfileGateways } from '@/store/gateway'
+import { migrateTilesForProfile } from '@/store/session-states'
import { RenameProfileDialog } from './rename-profile-dialog'
@@ -25,6 +26,10 @@ vi.mock('@/store/gateway', () => ({
retireLocalProfileGateways: vi.fn()
}))
+vi.mock('@/store/session-states', () => ({
+ migrateTilesForProfile: vi.fn()
+}))
+
it('retires the old-name local gateways before issuing the rename', async () => {
const order: string[] = []
@@ -45,6 +50,9 @@ it('retires the old-name local gateways before issuing the rename', async () =>
await waitFor(() => expect(renameProfile).toHaveBeenCalledWith('selena', 'renamed'))
expect(retireLocalProfileGateways).toHaveBeenCalledWith('selena')
expect(order).toEqual(['retire', 'rename'])
+ // The sessions moved with the directory: tabs / cached tails / remembered ids keyed by the
+ // old name follow, else every restored tab 404s against a backend that no longer exists (#111868).
+ expect(migrateTilesForProfile).toHaveBeenCalledWith('selena', 'renamed')
})
it('does not retire gateways when validation rejects the submit', async () => {
diff --git a/apps/desktop/src/app/profiles/rename-profile-dialog.tsx b/apps/desktop/src/app/profiles/rename-profile-dialog.tsx
index 94e035750f4..5013e82a461 100644
--- a/apps/desktop/src/app/profiles/rename-profile-dialog.tsx
+++ b/apps/desktop/src/app/profiles/rename-profile-dialog.tsx
@@ -18,6 +18,7 @@ import { useI18n } from '@/i18n'
import { AlertTriangle } from '@/lib/icons'
import { slug } from '@/lib/sanitize'
import { retireLocalProfileGateways } from '@/store/gateway'
+import { migrateTilesForProfile } from '@/store/session-states'
import { isValidProfileName } from './create-profile-dialog'
@@ -95,6 +96,14 @@ export function RenameProfileDialog({
}
await (scope == null ? renameProfile(currentName, trimmed) : renameProfile(currentName, trimmed, scope))
+
+ // The sessions moved with the directory; the tabs, cached tails and
+ // remembered ids keyed by the old name must follow, or every open
+ // dials a backend that no longer exists (#111868).
+ if (!isDefault && scope == null) {
+ migrateTilesForProfile(currentName, trimmed)
+ }
+
await onRenamed?.(trimmed)
setStatus('done')
window.setTimeout(onClose, 800)
diff --git a/apps/desktop/src/store/session-states-profile-rename.test.ts b/apps/desktop/src/store/session-states-profile-rename.test.ts
new file mode 100644
index 00000000000..dd2a0f3563c
--- /dev/null
+++ b/apps/desktop/src/store/session-states-profile-rename.test.ts
@@ -0,0 +1,68 @@
+// A profile rename keeps its sessions: every localStorage family keyed by the old profile name must move
+// to the new one, or the restored tabs dial a backend that no longer exists and 404 forever (#111868).
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+describe('migrateTilesForProfile', () => {
+ beforeEach(() => {
+ window.localStorage.clear()
+ vi.resetModules()
+ })
+
+ it('moves tabs, bot tiles, cached tails, remembered ids and owner hints to the new profile name', async () => {
+ const storage = await import('@/lib/storage')
+ storage.writeJson('hermes.desktop.sessionTiles.v2', {
+ webdesign_bhp: [
+ { storedSessionId: 's-1', dir: 'right', ownerRoute: { connectionId: 'local', profile: 'webdesign_bhp' } }
+ ],
+ __bots_workspace__: [
+ {
+ storedSessionId: 'bot-1',
+ dir: 'right',
+ workspaceMode: 'bots',
+ ownerRoute: { connectionId: 'local', profile: 'webdesign_bhp', targetProfile: 'webdesign_bhp' }
+ },
+ {
+ storedSessionId: 'bot-2',
+ dir: 'right',
+ workspaceMode: 'bots',
+ ownerRoute: { connectionId: 'local', profile: 'other' }
+ }
+ ]
+ })
+ storage.writeJson('hermes.desktop.sessionOwnerHints.v1', [
+ ['s-1', { connectionId: 'local', profile: 'webdesign_bhp', targetProfile: 'webdesign_bhp' }]
+ ])
+
+ const tails = await import('@/store/transcript-tail-cache')
+ tails.saveTranscriptTail('s-1', [{ id: 'm1', parts: [{ text: 'hello', type: 'text' }], role: 'user' } as never], {
+ connectionId: 'local',
+ profile: 'webdesign_bhp'
+ })
+
+ const sessionStore = await import('@/store/session')
+ sessionStore.setRememberedSessionId('s-1', 'webdesign_bhp')
+
+ const { migrateTilesForProfile } = await import('@/store/session-states')
+ migrateTilesForProfile('webdesign_bhp', 'hutnik-projectmanager')
+
+ type Tile = { ownerRoute?: { profile: string; targetProfile?: string }; storedSessionId: string }
+ const tiles = storage.readJson<Record<string, Tile[]>>('hermes.desktop.sessionTiles.v2')
+ expect(tiles?.webdesign_bhp).toBeUndefined()
+ expect(tiles?.['hutnik-projectmanager']?.map(t => [t.storedSessionId, t.ownerRoute?.profile])).toEqual([
+ ['s-1', 'hutnik-projectmanager']
+ ])
+ expect(tiles?.__bots_workspace__?.map(t => t.ownerRoute)).toEqual([
+ { connectionId: 'local', profile: 'hutnik-projectmanager', targetProfile: 'hutnik-projectmanager' },
+ { connectionId: 'local', profile: 'other' }
+ ])
+
+ expect(tails.loadTranscriptTail('s-1', { connectionId: 'local', profile: 'hutnik-projectmanager' })).toHaveLength(1)
+ expect(tails.loadTranscriptTail('s-1', { connectionId: 'local', profile: 'webdesign_bhp' })).toBeNull()
+
+ expect(sessionStore.getRememberedSessionId('hutnik-projectmanager')).toBe('s-1')
+ expect(sessionStore.getRememberedSessionId('webdesign_bhp')).toBeNull()
+ expect(sessionStore.getSessionOwnerHints('s-1')).toEqual([
+ { connectionId: 'local', profile: 'hutnik-projectmanager', targetProfile: 'hutnik-projectmanager' }
+ ])
+ })
+})
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 3320ca3be95..cdcae439813 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -48,6 +48,8 @@ import {
knownSessionOwner,
lineageAliases,
markSessionRead,
+ migrateRememberedNavigationForProfile,
+ migrateSessionOwnerHintsForProfile,
ownerLookupSessionRows,
sessionMatchesStoredId,
setActiveSessionStoredIdRotation,
@@ -66,6 +68,7 @@ import {
type SessionProfileRoute
} from './session-request-router'
import { ackStoredSessionId, markSessionUnreadFinished } from './session-unread'
+import { migrateTranscriptTailsForProfile } from './transcript-tail-cache'
import { isBrowserWindow, isSecondaryWindow } from './windows'
// ---------------------------------------------------------------------------
@@ -2019,6 +2022,64 @@ export function dropTilesForProfile(
persistTiles()
}
+/**
+ * Rename counterpart of dropTilesForProfile: the profile's sessions still exist
+ * under the new name, so its persisted tabs, Bot tiles routed at it, cached
+ * transcript tails, remembered session/route and owner hints move to the new
+ * name instead of being left under `local::<old>` where every open resolves
+ * to a backend that no longer exists ("Couldn't open this session", #111868).
+ * Local-connection state only; a remote gateway rename executes there.
+ */
+export function migrateTilesForProfile(oldProfile: string, newProfile: string): void {
+ const from = normalizeProfileKey(oldProfile)
+ const to = normalizeProfileKey(newProfile)
+
+ if (!from || !to || from === to) {
+ return
+ }
+
+ const isLocal = (owner: SessionProfileRoute | undefined) =>
+ Boolean(owner) && (String(owner?.connectionId ?? '').trim() || 'local') === 'local'
+
+ const renamedOwner = (owner: SessionProfileRoute | undefined): SessionProfileRoute | undefined => {
+ if (!owner || !isLocal(owner)) {
+ return owner
+ }
+
+ const profile = normalizeProfileKey(owner.profile) === from ? to : owner.profile
+ const targetProfile = normalizeProfileKey(owner.targetProfile) === from ? to : owner.targetProfile
+
+ return profile === owner.profile && targetProfile === owner.targetProfile
+ ? owner
+ : { ...owner, profile, ...(targetProfile === undefined ? {} : { targetProfile }) }
+ }
+
+ const moved = tilesByProfile[from]
+
+ if (moved) {
+ delete tilesByProfile[from]
+ tilesByProfile[to] = [...(tilesByProfile[to] ?? []), ...moved.map(tile => ({ ...tile, ownerRoute: renamedOwner(tile.ownerRoute) }))]
+ }
+
+ const botTiles = tilesByProfile[BOTS_TILE_BUCKET]
+
+ if (botTiles) {
+ tilesByProfile[BOTS_TILE_BUCKET] = botTiles.map(tile => ({ ...tile, ownerRoute: renamedOwner(tile.ownerRoute) }))
+ }
+
+ const live = $sessionTiles.get()
+ const next = live.map(tile => (tile.ownerRoute ? { ...tile, ownerRoute: renamedOwner(tile.ownerRoute) } : tile))
+
+ if (next.some((tile, index) => tile !== live[index] && tile.ownerRoute !== live[index].ownerRoute)) {
+ $sessionTiles.set(next)
+ }
+
+ persistTiles()
+ migrateTranscriptTailsForProfile(from, to)
+ migrateRememberedNavigationForProfile(from, to)
+ migrateSessionOwnerHintsForProfile(from, to)
+}
+
/** ⌘⇧T — reopen the most recently closed tab where it was, then focus it.
* Adoption alone is silent (won't steal the active tab), so restore has to
* front the pane explicitly. Skips ids that are live again (reopened / now
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index fe23c29b7ad..aec717572f3 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -144,6 +144,48 @@ export function setRememberedSessionId(id: null | string, profile: string): void
persistString(profileNavigationKey(LAST_SESSION_KEY, profile), id)
}
+/** A renamed profile keeps its sessions, so the remembered session / route and
+ * every owner hint pointing at the old name move to the new one instead of
+ * routing the next open at a backend that no longer exists (#111868). */
+export function migrateRememberedNavigationForProfile(oldProfile: string, newProfile: string): void {
+ discardLegacyRememberedNavigation()
+
+ for (const base of [LAST_SESSION_KEY, LAST_ROUTE_KEY]) {
+ const value = storedString(profileNavigationKey(base, oldProfile))
+
+ if (value !== null) {
+ persistString(profileNavigationKey(base, newProfile), value)
+ persistString(profileNavigationKey(base, oldProfile), null)
+ }
+ }
+}
+
+export function migrateSessionOwnerHintsForProfile(oldProfile: string, newProfile: string): void {
+ const from = oldProfile.trim() || 'default'
+ const to = newProfile.trim() || 'default'
+ let changed = false
+
+ for (const [key, entry] of [...sessionOwnerHints]) {
+ const { route } = entry
+
+ if (route.profile !== from && route.targetProfile !== from) {
+ continue
+ }
+
+ sessionOwnerHints.delete(key)
+ rememberSessionOwnerHint(entry.id, {
+ ...route,
+ profile: route.profile === from ? to : route.profile,
+ ...(route.targetProfile === from ? { targetProfile: to } : {})
+ })
+ changed = true
+ }
+
+ if (changed) {
+ persistSessionOwnerHints()
+ }
+}
+
export function sessionBelongsToProfile(
sessions: readonly Pick<SessionInfo, '_lineage_root_id' | 'id' | 'profile'>[],
storedSessionId: string,
diff --git a/apps/desktop/src/store/transcript-tail-cache.ts b/apps/desktop/src/store/transcript-tail-cache.ts
index 65619d19d25..b06f35a2cb7 100644
--- a/apps/desktop/src/store/transcript-tail-cache.ts
+++ b/apps/desktop/src/store/transcript-tail-cache.ts
@@ -339,6 +339,54 @@ export function dropTranscriptTailEverywhere(storedSessionId: string): void {
}
/** Wipe the whole cache (connection/mode re-home, quota recovery). */
+/** Re-key every cached tail owned by `oldProfile` under `newProfile` (profile
+ * rename; the sessions still exist, only their owner's name changed). Entries
+ * stay unreachable under the old name by construction, so without this a
+ * rename costs a cold paint for every open chat. Best effort. */
+export function migrateTranscriptTailsForProfile(oldProfile: string, newProfile: string): void {
+ const store = storage()
+ const from = oldProfile.trim() || 'default'
+ const to = newProfile.trim() || 'default'
+
+ if (!store || from === to) {
+ return
+ }
+
+ const ids = readIndex(store)
+
+ for (const [position, suffix] of ids.entries()) {
+ let parsed: unknown
+
+ try {
+ parsed = JSON.parse(suffix)
+ } catch {
+ continue // bare-id legacy suffix: carries no owner
+ }
+
+ if (!Array.isArray(parsed) || parsed.length !== 3 || parsed[1] !== from) {
+ continue
+ }
+
+ const [connectionId, , storedId] = parsed as [string, string, string]
+ const next = JSON.stringify([connectionId, to, storedId])
+
+ try {
+ const raw = store.getItem(PREFIX + suffix)
+
+ if (raw !== null) {
+ store.setItem(PREFIX + next, raw)
+ }
+
+ store.removeItem(PREFIX + suffix)
+ ids[position] = next
+ } catch {
+ // best effort
+ }
+ }
+
+ writeIndex(store, ids)
+}
+
export function clearTranscriptTails(): void {
const store = storage()
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index c6073d65850..29e5faa82d0 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -682,6 +682,17 @@ class SessionMessagesMixin:
"AND role = 'user' AND active = 1 AND content IS ?",
(_scrub_surrogates(api_content), row_id, session_id, self._encode_content(content)))
+ def set_user_message_content(self, session_id: str, row_id: int, content: Any) -> int:
+ """Rewrite the content of ONE known active user row. Used when a user turn was written at submit
+ time (before the agent ran) and the turn prologue then rewrote the prompt it persists (@-file
+ expansion, native image parts): the early row must show what the transcript will replay, not the
+ raw keystrokes, and the turn must not append a second row for the same input."""
+ if not session_id or isinstance(row_id, bool) or not isinstance(row_id, int) or row_id <= 0:
+ return 0
+ return self._write_rowcount(
+ "UPDATE messages SET content = ? WHERE id = ? AND session_id = ? AND role = 'user' AND active = 1",
+ (self._encode_content(content), row_id, session_id))
+
def _display_dedupe_key(self, row) -> Tuple[Any, ...]:
"""Historical display identity, including normalized live content from user handoff carriers."""
dedupe_content = row["content"]
diff --git a/tests/tui_gateway/test_submit_time_user_row.py b/tests/tui_gateway/test_submit_time_user_row.py
new file mode 100644
index 00000000000..059bf0d89b9
--- /dev/null
+++ b/tests/tui_gateway/test_submit_time_user_row.py
@@ -0,0 +1,77 @@
+"""prompt.submit writes the user's message at send time, and the turn that follows adopts that row instead of
+writing a second one (#111868: a Desktop freeze during a slow first agent build left a session row with no message)."""
+
+from types import SimpleNamespace
+
+from agent.turn_context import _stage_turn_user_message
+from hermes_state import SessionDB
+from run_agent import AIAgent
+from tui_gateway import server
+
+
+def _desktop_session(monkeypatch, db):
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ monkeypatch.setattr(server, "_schedule_agent_build", lambda _sid: None)
+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)
+ monkeypatch.setattr(server, "_register_session_cwd", lambda _session: None)
+ resp = server.handle_request({"id": "c", "method": "session.create", "params": {"cols": 96, "source": "desktop"}})
+ assert "result" in resp, resp
+ return resp["result"]["session_id"], resp["result"]["stored_session_id"]
+
+
+def _flush_agent(db, key):
+ """Agent shell owning the real flush (the crash persist at turn start runs this same code)."""
+ agent = SimpleNamespace(
+ _session_db=db, _session_db_created=True, _persist_disabled=False, session_id=key,
+ _session_persist_lock=None, _flushed_db_message_ids=set(), _flushed_db_message_session_id=None,
+ _last_flushed_db_idx=0, _persist_user_message_idx=None, _persist_user_message_override=None,
+ _persist_user_message_timestamp=None, _pending_cli_user_message=None)
+ agent._ensure_db_session = lambda: None
+ agent._flush_messages_to_session_db = AIAgent._flush_messages_to_session_db.__get__(agent, AIAgent)
+ agent._flush_messages_to_session_db_unlocked = AIAgent._flush_messages_to_session_db_unlocked.__get__(agent, AIAgent)
+ return agent
+
+
+def test_user_message_is_durable_at_submit_before_any_agent_turn(monkeypatch, tmp_path):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+ try:
+ with session["history_lock"]:
+ session["running"] = True
+ server._start_inflight_turn(session, "please refactor the login page")
+ assert server._persist_session_row_for_submit("rid", session, "please refactor the login page", None) is None
+ # The agent build has not even started: the transcript already resumes with the sent message.
+ assert [(r["role"], r["content"]) for r in db.get_messages_as_conversation(key)] == [
+ ("user", "please refactor the login page")]
+ assert db.get_session(key)["message_count"] == 1
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
+def test_turn_adopts_the_submit_row_and_writes_no_duplicate(monkeypatch, tmp_path):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+ try:
+ with session["history_lock"]:
+ session["running"] = True
+ server._start_inflight_turn(session, "look at @notes.md")
+ assert server._persist_session_row_for_submit("rid", session, "look at @notes.md", None) is None
+ agent = _flush_agent(db, key)
+ # The prologue rewrote the persisted prompt (@-expansion): the early row follows it.
+ expanded = "look at @notes.md\n\n<file notes.md>todo</file>"
+ server._adopt_submit_user_row(session, agent, expanded)
+ assert "_submit_user_row" not in session
+ user_msg, _pending = _stage_turn_user_message(agent, expanded, expanded, None, None, None, None)
+ assert user_msg is agent._pending_cli_user_message # adopted by identity, not rebuilt
+ messages = [user_msg]
+ agent._persist_user_message_idx = 0
+ agent._flush_messages_to_session_db(messages, []) # the turn-start crash persist
+ agent._flush_messages_to_session_db(messages + [{"role": "assistant", "content": "done"}], []) # turn end
+ rows = db.get_messages_as_conversation(key, include_inactive=True)
+ assert [(r["role"], r["content"]) for r in rows] == [("user", expanded), ("assistant", "done")]
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index ab6ab6b3a57..aecab10b4b6 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -21828,12 +21828,11 @@ def test_prompt_submit_row_id_real_sessiondb_resolve_without_memory_stamps(
assert len(sess["history"]) == 2
assert sess["history"][0]["content"] == "first"
assert sess["history"][1]["content"] == "reply 1"
- # Durable active transcript matches the cut (archive_dropped keeps
- # inactive rows; get_messages_as_conversation returns active only).
+ # Durable active transcript matches the cut plus the prompt just sent, which is durable at
+ # submit (#111868) — before the turn runs (archive_dropped keeps inactive rows;
+ # get_messages_as_conversation returns active only).
active = db.get_messages_as_conversation(session_key)
- assert len(active) == 2
- assert active[0]["content"] == "first"
- assert active[1]["content"] == "reply 1"
+ assert [m["content"] for m in active] == ["first", "reply 1", "rewound second"]
# Heal stamps for subsequent rewinds when memory lined up with DB.
assert sess["history"][0].get("_row_id") is not None
finally:
@@ -22236,7 +22235,8 @@ def test_prompt_submit_consecutive_rewinds_with_returned_survivor_row_ids(
assert len(sess["history"]) == 2
assert sess["history"][0]["content"] == "first"
active = db.get_messages_as_conversation(session_key)
- assert [m["content"] for m in active] == ["first", "reply 1"]
+ # The cut, plus the prompt just sent (durable at submit, #111868).
+ assert [m["content"] for m in active] == ["first", "reply 1", "rewound second (fresh id)"]
# And the second response rebinds again: one surviving user turn.
survivors2 = resp2["result"].get("survivor_user_row_ids")
assert isinstance(survivors2, list) and len(survivors2) == 1
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index e318c087182..0b7fb57cebc 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -444,9 +444,10 @@ def _storage_error_data(failure, raw) -> dict:
return {"code": failure.code, "cause": failure.cause, "details": storage_failure_details(raw)}
-def _persist_session_row_for_submit(rid, session):
+def _persist_session_row_for_submit(rid, session, text=None, display_kind=None):
"""Lazily persist the DB row now that the user sent a message (a branch becomes real
- here); the error reply is the only user-visible signal (desktop maps it to a toast)."""
+ here), then the message itself (#111868: a freeze during the first build must leave a
+ resumable transcript); the error reply is the only user-visible signal (desktop maps it to a toast)."""
from hermes_state_user_copy import describe_storage_failure
try:
if _ensure_session_db_row(session) is False:
@@ -458,6 +459,7 @@ def _persist_session_row_for_submit(rid, session):
data=_storage_error_data(failure, _db_error))
else:
_persist_branch_seed(session)
+ _persist_submit_user_row(session, text, display_kind)
return None
except Exception as exc:
failure = describe_storage_failure(exc)
@@ -663,7 +665,7 @@ def _(rid, params: dict) -> dict:
logger.warning(
"compute-host dispatch failed for session %s; falling back inline: %s", sid,
isolated_response["error"].get("message", "unknown error"))
- if (err := _persist_session_row_for_submit(rid, session)) is not None:
+ if (err := _persist_session_row_for_submit(rid, session, text, display_kind)) is not None:
return err
# A completed FAILED build must not wedge the session: rebuild, don't replay it.
if not _restart_completed_failed_agent_build(sid, session, session.get("agent_ready")):
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index a7af899d11b..2fa45ba19c4 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -599,6 +599,7 @@ def _invoke_agent(
run_kwargs["persist_user_display_metadata"] = display_metadata
if turn_author and "turn_author" in run_params:
run_kwargs["turn_author"] = turn_author
+ _adopt_submit_user_row(session, agent, run_kwargs["persist_user_message"])
# Live-rename hook: auto-titling fires inside the turn prologue.
_title_key = session.get("session_key") or sid
agent._on_session_title = lambda t, _src, _k=_title_key: _emit(
diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.py
index 1728724673f..e35102026c0 100644
--- a/tui_gateway/session_history.py
+++ b/tui_gateway/session_history.py
@@ -309,6 +309,9 @@ def _record_inflight_correction(session: dict, text: Any) -> None:
def _clear_inflight_turn(session: dict) -> None:
session["inflight_turn"] = None
+ # A turn that never reached the agent (cancelled/refused before ready) leaves its submit-time row
+ # as the durable record of the send; a later turn must not adopt it as its own input.
+ session.pop("_submit_user_row", None)
def _fail_inflight_turn(session: dict, error: Any, error_surface: Optional[dict] = None) -> None:
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index cee9319047b..81117b19ae3 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -337,6 +337,59 @@ def _persist_branch_seed(session: dict) -> None:
_workdir_reraise_disk_full(exc, "branch seed persist failed")
+def _persist_submit_user_row(session: dict, text: Any, display_kind: str | None) -> None:
+ """Write the submitted user turn at send time, before the agent build and turn: the agent's own
+ crash persist only runs once the build finished, so quitting a frozen app during a slow first build
+ left a session row with no message (#111868). The dict is staged on the session already stamped
+ durable (the shape ``quiet_single_query`` re-stages an unanswered DM in) so the turn adopts it via
+ ``_stage_turn_user_message`` and the flush writes no second row. A failed write stages nothing:
+ the turn's crash persist then writes the row as before."""
+ key = session.get("session_key")
+ if not key or not isinstance(text, str) or not text.strip():
+ return
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+ from agent.message_metadata import stamp_message_timestamp
+ staged = stamp_message_timestamp({"role": "user", "content": text})
+ if display_kind:
+ staged["display_kind"] = display_kind
+ with _session_db(session) as db:
+ if db is None:
+ return
+ try:
+ staged["_row_id"] = db.append_message(
+ key, "user", content=text, display_kind=display_kind, timestamp=staged["timestamp"])
+ except Exception as exc:
+ _workdir_reraise_disk_full(exc, "submit-time user row persist failed")
+ return
+ staged[_DB_PERSISTED_MARKER] = True
+ session["_submit_user_row"] = staged
+
+
+def _adopt_submit_user_row(session: dict, agent, persist_user_message: Any) -> None:
+ """Hand the row written at submit to the turn as its user dict (``agent._pending_cli_user_message``,
+ adopted by ``_stage_turn_user_message`` when the content matches). A prompt the prologue rewrote
+ (@-expansion, image parts) first updates that row so the durable transcript replays what the model
+ was sent and the ``api_content`` sidecar can address it; ``_row_id`` rides along for that stamp."""
+ staged = session.pop("_submit_user_row", None)
+ if not isinstance(staged, dict) or agent is None:
+ return
+ if staged["content"] != persist_user_message:
+ from agent.session_persistence import _durable_content
+ with _session_db(session) as db:
+ if db is None:
+ return
+ try:
+ db.set_user_message_content(
+ session["session_key"], staged["_row_id"], _durable_content(persist_user_message))
+ except Exception:
+ logger.debug("submit-time user row update failed; the turn writes its own row", exc_info=True)
+ return
+ staged["content"] = persist_user_message
+ from agent.session_persistence import _persist_lock
+ with _persist_lock(agent):
+ agent._pending_cli_user_message = staged
+
+
# Yielded by _workdir_owner_db when the profile db failed to OPEN (vs "no store in this context"); row creation fails loud.
_WORKDIR_DB_OPEN_FAILED = object()