diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts index ba1107e9e0..57bfa92bfa 100644 --- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts +++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts @@ -79,6 +79,7 @@ export function useSessionTileDelegate({ requestGateway('session.resume', { session_id: storedSessionId, cols: 96, + omit_messages: true, ...(profile ? { profile } : {}) }) ]) diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx index 57eea9ca06..defaaf945d 100644 --- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx +++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx @@ -2194,7 +2194,7 @@ describe('usePromptActions redirectPrompt', () => { expect(await handle!.redirectPrompt('reconnect nudge')).toBe(true) expect(calls.map(c => c.method)).toEqual(['session.redirect', 'session.resume', 'session.redirect']) expect(calls[0]?.params).toEqual({ session_id: RUNTIME_SESSION_ID, text: 'reconnect nudge' }) - expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop' }) + expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop', omit_messages: true }) expect(calls[2]?.params).toEqual({ session_id: RECOVERED_SESSION_ID, text: 'reconnect nudge' }) expect(handle!.activeSessionIdRef.current).toBe(RECOVERED_SESSION_ID) }) @@ -2735,7 +2735,7 @@ describe('usePromptActions sleep/wake session recovery', () => { expect(ok).toBe(true) // First submit (stale id) → session.resume (stored id) → retry submit (fresh id). expect(calls.map(c => c.method)).toEqual(['prompt.submit', 'session.resume', 'prompt.submit']) - expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop' }) + expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop', omit_messages: true }) expect(calls[2]?.params).toEqual({ session_id: RECOVERED_SESSION_ID, text: 'message after wake' }) }) @@ -2779,7 +2779,12 @@ describe('usePromptActions sleep/wake session recovery', () => { ) expect(await handle!.submitText('message after wake')).toBe(true) - expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop', profile: 'work' }) + expect(calls[1]?.params).toEqual({ + session_id: STORED_SESSION_ID, + source: 'desktop', + omit_messages: true, + profile: 'work' + }) setSessions(() => []) }) @@ -2826,7 +2831,12 @@ describe('usePromptActions sleep/wake session recovery', () => { ) expect(await handle!.submitText('message after wake')).toBe(true) - expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop', profile: 'work' }) + expect(calls[1]?.params).toEqual({ + session_id: STORED_SESSION_ID, + source: 'desktop', + omit_messages: true, + profile: 'work' + }) vi.mocked(getSession).mockReset() setSessions(() => []) @@ -2887,7 +2897,11 @@ describe('usePromptActions sleep/wake session recovery', () => { session_id: 'rt-background-stale', text: 'queued background message after wake' }) - expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop' }) + expect(calls[1]?.params).toEqual({ + session_id: STORED_SESSION_ID, + source: 'desktop', + omit_messages: true + }) expect(calls[2]?.params).toEqual({ queued: true, session_id: RECOVERED_SESSION_ID, @@ -2935,7 +2949,11 @@ describe('usePromptActions sleep/wake session recovery', () => { expect(calls.map(c => c.method)).toEqual(['session.interrupt', 'session.resume', 'session.interrupt']) expect(calls[0]?.params).toEqual({ session_id: RUNTIME_SESSION_ID }) - expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop' }) + expect(calls[1]?.params).toEqual({ + session_id: STORED_SESSION_ID, + source: 'desktop', + omit_messages: true + }) expect(calls[2]?.params).toEqual({ session_id: RECOVERED_SESSION_ID }) }) @@ -3067,7 +3085,11 @@ describe('usePromptActions sleep/wake session recovery', () => { expect(ok).toBe(true) expect(calls.map(c => c.method)).toEqual(['prompt.submit', 'session.resume', 'prompt.submit']) - expect(calls[1]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop' }) + expect(calls[1]?.params).toEqual({ + session_id: STORED_SESSION_ID, + source: 'desktop', + omit_messages: true + }) expect(calls[2]?.params).toEqual({ session_id: RECOVERED_SESSION_ID, text: 'message during starved loop' @@ -3110,7 +3132,11 @@ describe('usePromptActions sleep/wake session recovery', () => { expect(ok).toBe(true) expect(createBackendSessionForSend).not.toHaveBeenCalled() expect(calls.map(c => c.method)).toEqual(['session.resume', 'prompt.submit']) - expect(calls[0]?.params).toEqual({ session_id: STORED_SESSION_ID, source: 'desktop' }) + expect(calls[0]?.params).toEqual({ + session_id: STORED_SESSION_ID, + source: 'desktop', + omit_messages: true + }) expect(calls[1]?.params).toMatchObject({ session_id: RECOVERED_SESSION_ID }) }) @@ -3421,7 +3447,8 @@ describe('usePromptActions submit session-context isolation (#54527)', () => { expect(calls.some(c => c.method === 'prompt.submit')).toBe(false) expect(calls.find(c => c.method === 'session.resume')?.params).toEqual({ session_id: STORED_SESSION_A, - source: 'desktop' + source: 'desktop', + omit_messages: true }) }) diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts index 6307969421..186773a874 100644 --- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts +++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts @@ -639,6 +639,7 @@ export function usePromptActions({ const resumed = await requestGateway<{ session_id: string }>('session.resume', { session_id: selectedStoredSessionIdRef.current, source: 'desktop', + omit_messages: true, ...(resumeProfile ? { profile: resumeProfile } : {}) }) @@ -744,6 +745,7 @@ export function usePromptActions({ const resumed = await requestGateway<{ session_id: string }>('session.resume', { session_id: selectedStoredSessionIdRef.current, source: 'desktop', + omit_messages: true, ...(resumeProfile ? { profile: resumeProfile } : {}) }) diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts index 20de6ea35c..36c8bfd82d 100644 --- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts +++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts @@ -484,6 +484,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) { const resumed = await requestGateway<{ session_id: string }>('session.resume', { session_id: targetStoredSessionId, source: 'desktop', + omit_messages: true, ...(resumeProfile ? { profile: resumeProfile } : {}) }) @@ -637,6 +638,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) { const resumed = await requestGateway<{ session_id: string }>('session.resume', { session_id: recoverStoredSessionId, source: 'desktop', + omit_messages: true, ...(resumeProfile ? { profile: resumeProfile } : {}) }) diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx index 35110e481b..1bdb521efa 100644 --- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx +++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx @@ -896,7 +896,7 @@ describe('resumeSession failure recovery', () => { expect(resumeParams).not.toHaveProperty('lazy') expect(resumeParams).not.toHaveProperty('eager_build') - expect(resumeParams).toMatchObject({ source: 'desktop' }) + expect(resumeParams).toMatchObject({ source: 'desktop', omit_messages: true }) }) it('arms the failure latch when resume succeeds with an empty transcript for a non-empty stored session', async () => { @@ -1431,6 +1431,10 @@ describe('resumeSession warm-cache mapping integrity', () => { expect(methods).toContain('session.activate') expect(methods).not.toContain('session.resume') expect(getSessionMessages).toHaveBeenCalledWith('stored-A', undefined) + expect(requestGateway).toHaveBeenCalledWith( + 'session.activate', + expect.objectContaining({ omit_messages: true, session_id: 'rt-A' }) + ) expect(runtimeIdByStoredSessionIdRef.current.get('stored-A')).toBe('rt-A') }) diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts index 6a7e568cba..0f13a375c0 100644 --- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts +++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts @@ -700,7 +700,8 @@ export function useSessionActions({ try { activated = await requestGateway('session.activate', { session_id: cachedRuntimeId, - cols: 96 + cols: 96, + omit_messages: true }) } catch (error) { // Compatibility for older backends. Modern backends require @@ -866,12 +867,14 @@ export function useSessionActions({ session_id: storedSessionId, cols: 96, source: 'desktop', + // REST is the transcript authority for Desktop. Avoid duplicating a + // potentially huge compression lineage in the WebSocket response. // Watch windows attach lazily (live mirror). Every other cold resume // gets the gateway's default deferred build: the RPC returns the // transcript immediately instead of blocking the switch on _make_agent // (MCP discovery / prompt build), and the agent pre-warms in the // background while the prefetch above paints the transcript. - ...(watchWindow ? { lazy: true } : {}), + ...(watchWindow ? { lazy: true } : { omit_messages: true }), ...(sessionProfile ? { profile: sessionProfile } : {}) }) diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts index 796784ff61..bc1fb5c581 100644 --- a/apps/desktop/src/types/hermes.ts +++ b/apps/desktop/src/types/hermes.ts @@ -600,6 +600,7 @@ export interface SessionResumeResponse { info?: SessionRuntimeInfo message_count: number messages: SessionMessage[] + messages_omitted?: boolean resumed: string running?: boolean session_id: string diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py index 00021195a4..e8aaa16e05 100644 --- a/tests/test_tui_gateway_server.py +++ b/tests/test_tui_gateway_server.py @@ -2415,8 +2415,10 @@ def test_history_to_messages_keeps_real_user_bracket_text(): ] -def test_session_resume_uses_parent_lineage_for_display(monkeypatch): +@pytest.mark.parametrize("omit_messages", [False, True]) +def test_session_resume_uses_parent_lineage_for_display(monkeypatch, omit_messages): captured = {} + target = "tip-omit" if omit_messages else "tip-full" class FakeDB: def get_session(self, target): @@ -2466,15 +2468,25 @@ def test_session_resume_uses_parent_lineage_for_display(monkeypatch): # _neuter_agent_prewarm_timer fixture; this test only asserts the # returned display history. + params = {"session_id": target} + if omit_messages: + params["omit_messages"] = True resp = server.handle_request( - {"id": "1", "method": "session.resume", "params": {"session_id": "tip"}} + {"id": "1", "method": "session.resume", "params": params} ) - assert resp["result"]["messages"] == [ + expected = [] if omit_messages else [ {"role": "user", "text": "root prompt"}, {"role": "assistant", "text": "root answer"}, ] - assert captured["history_calls"] == [("tip", False), ("tip", True)] + assert resp["result"]["messages"] == expected + assert resp["result"]["message_count"] == (1 if omit_messages else 2) + assert resp["result"]["messages_omitted"] is omit_messages + expected_calls = [(target, False)] if omit_messages else [ + (target, False), + (target, True), + ] + assert captured["history_calls"] == expected_calls def test_live_visible_history_prefers_db_display_with_candidate(): @@ -12396,6 +12408,33 @@ def test_session_activate_switches_live_session_without_closing_siblings(monkeyp server._sessions.pop("sid-b", None) +def test_session_activate_can_omit_duplicate_desktop_transcript(monkeypatch): + monkeypatch.setattr(server, "_session_info", lambda agent: {"model": agent.model}) + server._sessions["sid-large"] = _session( + agent=types.SimpleNamespace(model="model-large"), + history=[ + {"role": "user", "content": "large prompt"}, + {"role": "assistant", "content": "large answer"}, + ], + session_key="key-large", + ) + try: + resp = server.handle_request( + { + "id": "1", + "method": "session.activate", + "params": {"session_id": "sid-large", "omit_messages": True}, + } + ) + + assert resp["result"]["messages"] == [] + assert resp["result"]["message_count"] == 2 + assert resp["result"]["messages_omitted"] is True + assert resp["result"]["session_key"] == "key-large" + finally: + server._sessions.pop("sid-large", None) + + # ── session.most_recent ────────────────────────────────────────────── diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py index 75e473426b..d84fedcd43 100644 --- a/tui_gateway/methods_session.py +++ b/tui_gateway/methods_session.py @@ -316,6 +316,10 @@ def _(rid, params: dict) -> dict: # local profile's state.db. None/own profile → the launch profile (unchanged). profile = (params.get("profile") or "").strip() or None profile_home = _profile_home(profile) + # Desktop hydrates persisted transcripts through the authenticated REST + # route in parallel. Suppress the duplicate WebSocket transcript only when + # the caller explicitly requests it; other clients keep upstream behavior. + omit_messages = is_truthy_value(params.get("omit_messages", False)) # In a profile scope, the agent OWNS a long-lived db handle bound to that # profile (do NOT auto-close it here). Otherwise reuse the shared launch db. @@ -380,6 +384,7 @@ def _(rid, params: dict) -> dict: cols=cols, touch=True, transport=current_transport() or _stdio_transport, + omit_messages=omit_messages, ) payload["resumed"] = target # A lazy watch session never owns a run loop, so its payload's running @@ -450,14 +455,15 @@ def _(rid, params: dict) -> dict: except Exception: logger.debug("child-watch display projection read failed", exc_info=True) display_history = history - messages = _history_to_messages(display_history) + messages = [] if omit_messages else _history_to_messages(display_history) return _ok( rid, { "session_id": sid, "resumed": target, - "message_count": len(messages), + "message_count": len(display_history) if omit_messages else len(messages), "messages": messages, + "messages_omitted": omit_messages, "info": _lazy_resume_info(cwd, profile=profile), "inflight": None, "running": child_running, @@ -494,7 +500,13 @@ def _(rid, params: dict) -> dict: # (raw_history → sanitize_replay_history → the resumed session's # working conversation) and the display copy stays verbatim — # inspection/export must show what is actually stored. - raw_history, display_history = db.get_resume_conversations(target) + if omit_messages: + raw_history = db.get_messages_as_conversation( + target, repair_alternation=True + ) + display_history = [] + else: + raw_history, display_history = db.get_resume_conversations(target) except Exception as e: if lease is not None: lease.release() @@ -502,7 +514,7 @@ def _(rid, params: dict) -> dict: # Display keeps the full transcript; the model-fed history drops a # dangling/interrupted tool-call tail so a session killed mid-loop does # not replay the unanswered call forever (#29086). - prefix = db.get_ancestor_display_prefix(target) + prefix = [] if omit_messages else db.get_ancestor_display_prefix(target) history = sanitize_replay_history(raw_history) # Restore the model/provider/reasoning/tier this chat last used so the # deferred build (and the info below) match the eager path — without them @@ -530,12 +542,13 @@ def _(rid, params: dict) -> dict: _schedule_session_cap_enforcement() # trim detached idle sessions over the cap auto_continue = _maybe_schedule_auto_continue(sid, record, target) - messages = _history_to_messages(display_history) + messages = [] if omit_messages else _history_to_messages(display_history) payload = { "session_id": sid, "resumed": target, - "message_count": len(messages), + "message_count": len(raw_history) if omit_messages else len(messages), "messages": messages, + "messages_omitted": omit_messages, "info": _lazy_resume_info( cwd, model=model_override.get("model") or "", @@ -573,7 +586,13 @@ def _(rid, params: dict) -> dict: # One lineage SELECT feeds both projections (see the interactive resume # above): the model-fed copy is alternation-repaired for LIVE REPLAY, the # display copy stays verbatim. - raw_history, display_history = db.get_resume_conversations(target) + if omit_messages: + raw_history = db.get_messages_as_conversation( + target, repair_alternation=True + ) + display_history = [] + else: + raw_history, display_history = db.get_resume_conversations(target) # The display transcript keeps every row so the user still sees their # full history. The model-fed history is sanitized: a session whose # last turn died mid-tool-loop persists a dangling assistant(tool_calls) @@ -581,9 +600,11 @@ def _(rid, params: dict) -> dict: # re-issue the unanswered call forever — the permanent-"thinking" stuck # session in #29086. The messaging gateway already strips this; this is # the WebUI/TUI resume path picking up the same cleanup. - display_history_prefix = db.get_ancestor_display_prefix(target) + display_history_prefix = ( + [] if omit_messages else db.get_ancestor_display_prefix(target) + ) history = sanitize_replay_history(raw_history) - messages = _history_to_messages(display_history) + messages = [] if omit_messages else _history_to_messages(display_history) tokens = _set_session_context(target) try: # Pass the profile's db so the agent persists turns to the right @@ -632,6 +653,7 @@ def _(rid, params: dict) -> dict: cols=cols, touch=True, transport=current_transport() or _stdio_transport, + omit_messages=omit_messages, ) payload["resumed"] = target return _ok(rid, payload) @@ -685,8 +707,9 @@ def _(rid, params: dict) -> dict: payload = { "session_id": sid, "resumed": target, - "message_count": len(messages), + "message_count": len(raw_history) if omit_messages else len(messages), "messages": messages, + "messages_omitted": omit_messages, "info": _session_info(agent, session), "inflight": None, "running": False, @@ -782,6 +805,7 @@ def _(rid, params: dict) -> dict: session, touch=True, transport=current_transport() or _stdio_transport, + omit_messages=is_truthy_value(params.get("omit_messages", False)), ), ) diff --git a/tui_gateway/server.py b/tui_gateway/server.py index c5ed0080f7..a3475fc11e 100644 --- a/tui_gateway/server.py +++ b/tui_gateway/server.py @@ -7913,6 +7913,7 @@ def _live_session_payload( cols: int | None = None, touch: bool = False, transport: Transport | None = None, + omit_messages: bool = False, ) -> dict: with session["history_lock"]: if cols is not None: @@ -7930,11 +7931,16 @@ def _live_session_payload( # Prefer the persisted display lineage (candidate-inclusive) so this payload # matches the eager session.resume + REST transcript; the DB has its own # lock, so read it outside the session history lock. - history = _live_visible_history(session, _get_db(), in_memory_history) + history = ( + in_memory_history + if omit_messages + else _live_visible_history(session, _get_db(), in_memory_history) + ) payload = { "info": _fallback_session_info(session), "message_count": len(history), - "messages": _history_to_messages(history), + "messages": [] if omit_messages else _history_to_messages(history), + "messages_omitted": omit_messages, "running": running, "session_id": sid, "session_key": _session_lookup_key(session, fallback=sid),