Skip to content

The agent that grows with you

feat(gateway): session.resume carries the session's todo snapshot

kshitijk4poor98159a32006b
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 811f61b191a..639c49f98ab 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4962,6 +4962,7 @@ export interface CanonicalSnapshot {
prompts: CanonicalPendingPrompt[]
info: CanonicalSnapshotInfo
pending_connection?: ConnectionRequestPayload | null
+ todo_state?: TodoState | null
}
export interface CanonicalPendingAdmission {
admission_id: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index bf0e80e9f20..0d8c05765f9 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -10672,6 +10672,17 @@
}
],
"default": null
+ },
+ "todo_state": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/TodoState"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
}
},
"required": [
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 15b3847284c..417f4d6cf94 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -623,13 +623,15 @@ class AuthorityConnection:
await asyncio.to_thread(refresh_profile_hooks, policy_for_source(self.authority.runner, source))
info = await snapshot_info(self.authority, snapshot.handle.ref)
from gateway.session_connections import pending_connection
- display = {}
+ # Its home module, not tui_gateway.server: importing the stdio sidecar points sys.stdout at stderr.
+ from tui_gateway.tool_progress import _todo_state_from_history
+ history, display = list(snapshot.history), {}
if params.get('display_projection'):
# A micro-compaction merge stays in ``messages`` (an undo target); its originals are what shows.
display['display_messages'] = display_projection(
- [row for row in snapshot.history if not model_only(row)], self.authority.profile_id)
+ [row for row in history if not model_only(row)], self.authority.profile_id)
return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,
- 'messages': list(snapshot.history), **display, 'message_count': len(snapshot.history),
+ 'messages': history, **display, 'message_count': len(history),
'running': snapshot.handle.execution_state == 'running',
'authority_epoch': snapshot.handle.authority_epoch,
'replay_epoch': snapshot.replay_epoch, 'last_sequence': snapshot.last_sequence,
@@ -637,7 +639,10 @@ class AuthorityConnection:
'execution_generation': snapshot.handle.execution_generation,
'pending': [asdict(r) for r in snapshot.pending],
'prompts': list(snapshot.prompts), 'info': info,
- 'pending_connection': pending_connection(self.authority, ref.session_id)}
+ 'pending_connection': pending_connection(self.authority, ref.session_id),
+ # The newest todo result in the transcript, the snapshot the session's agent hydrates
+ # from and its ``todo.updated`` frames carried: a viewer attaching shows the plan now.
+ 'todo_state': _todo_state_from_history(history)}
def _spawn_notice(self, ref):
"""Low-disk auto-prune question for this viewer, off the resume reply's path."""
diff --git a/tests/gateway/test_resume_todo_state.py b/tests/gateway/test_resume_todo_state.py
new file mode 100644
index 00000000000..6f61f0daa23
--- /dev/null
+++ b/tests/gateway/test_resume_todo_state.py
@@ -0,0 +1,62 @@
+"""``session.resume`` carries the session's todo snapshot (``todo_state``): a viewer attaching to a session
+with a plan (the classic CLI's /resume or ``-c``) shows it before the next ``todo.updated``.
+
+Real store, authority, local session and ``AuthorityConnection.resume`` (the helpers of
+``test_resume_display_history``).
+"""
+import json
+import sys
+
+import pytest
+
+from tests.gateway.test_resume_display_history import _local_session, _resume
+
+TODOS = [{'id': '1', 'content': 'write the fix', 'status': 'completed'},
+ {'id': '2', 'content': 'ship it', 'status': 'in_progress'}]
+
+
+def _todo_turn(db, sid, call_id, todos, revision):
+ call = {'id': call_id, 'type': 'function',
+ 'function': {'name': 'todo_list', 'arguments': json.dumps({'todos': todos})}}
+ db.append_message(sid, 'assistant', '', tool_calls=[call])
+ db.append_message(sid, 'tool', json.dumps({'todos': todos, 'revision': revision}), tool_name='todo_list',
+ tool_call_id=call_id)
+
+
+async def test_resume_carries_the_newest_todo_snapshot(tmp_path, monkeypatch):
+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)
+ db = authority.db
+ assert (await _resume(authority, actor, ref))['todo_state'] is None # no plan yet
+ db.append_message(physical, 'user', 'plan it')
+ _todo_turn(db, physical, 'call-1', TODOS[:1], 1)
+ _todo_turn(db, physical, 'call-2', TODOS, 2)
+ db.append_message(physical, 'assistant', 'planned')
+ assert (await _resume(authority, actor, ref))['todo_state'] == {'todos': TODOS, 'revision': 2}
+
+
+def test_the_home_module_reads_the_snapshot_when_imported_directly():
+ """``tool_progress`` bodies are also rebound onto ``tui_gateway.server``; the module's own copy (what the
+ gateway imports) must not lean on the server's globals for ``json``/``logger``."""
+ from tui_gateway.tool_progress import _todo_state_from_history
+ call = {'id': 'call-1', 'type': 'function', 'function': {'name': 'todo_list', 'arguments': '{}'}}
+ history = [{'role': 'assistant', 'content': '', 'tool_calls': [call]},
+ {'role': 'tool', 'tool_call_id': 'call-1', 'content': json.dumps({'todos': TODOS, 'revision': 2})}]
+ assert _todo_state_from_history(history) == {'todos': TODOS, 'revision': 2}
+
+
+async def test_resume_leaves_the_gateway_processs_stdout_alone(tmp_path, monkeypatch):
+ """Importing ``tui_gateway.server`` (the stdio JSON-RPC sidecar) points ``sys.stdout`` at stderr, so the
+ resume path must not import it: a CLI sharing the process would print to stderr from then on."""
+ import tui_gateway
+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)
+ _todo_turn(authority.db, physical, 'call-1', TODOS, 2)
+ monkeypatch.delitem(sys.modules, 'tui_gateway.server', raising=False)
+ monkeypatch.delattr(tui_gateway, 'server', raising=False)
+ monkeypatch.setattr(sys, 'stdout', sys.stdout) # restored even if the import below swaps it
+ stdout = sys.stdout
+ assert (await _resume(authority, actor, ref))['todo_state'] == {'todos': TODOS, 'revision': 2}
+ assert sys.stdout is stdout
+ assert 'tui_gateway.server' not in sys.modules
+
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index ed6356347c0..db394b039bc 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -9,6 +9,7 @@ from pydantic import RootModel
from .base import JsonValue, Params, Result
from .common import ProfileParams, TranscriptMessage
from .connectors_operation import ConnectionRequestPayload
+from .sessions import TodoState
from .canonical import AdmissionStatus, CanonicalSessionRef, PromptResponseResult, SessionInventoryFields
from .registry import canonical_method
@@ -152,6 +153,8 @@ class CanonicalSnapshot(Result):
info: CanonicalSnapshotInfo
# The open ``manage_connections`` card, so a resume restores it while the tool waits.
pending_connection: ConnectionRequestPayload | None = None
+ # The session's todo snapshot (its transcript's newest todo result); null when it has none.
+ todo_state: TodoState | None = None
class CanonicalListParams(ProfileParams):
diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.py
index b0b545de12a..8e427a9ae44 100644
--- a/tui_gateway/tool_progress.py
+++ b/tui_gateway/tool_progress.py
@@ -3,8 +3,14 @@ projection. Bodies are rebound onto server.py's globals (method_ctx.bind_module)
from __future__ import annotations
+import json
+import logging
+
from .method_ctx import bind_module
+# Bound copies resolve these on server.py; the module's own (imported directly) needs them too.
+logger = logging.getLogger(__name__)
+
# Verbose tool text is capped to the Ink render budget (a hair more, so the "[omitted …]" label
# stays informative): unbounded output fed a render-tree blowup that OOM-killed the TUI parent.
# Full output stays in the agent context and the SQLite session, untouched.