The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): serve the Desktop preview pane's restart on the shared owner
Teknium7e8007c6aa4e
diff --git a/apps/desktop/src/api/canonical-producer-contract.test.ts b/apps/desktop/src/api/canonical-producer-contract.test.tsindex 0a4e5c04e0c..7c2c3008263 100644--- a/apps/desktop/src/api/canonical-producer-contract.test.ts+++ b/apps/desktop/src/api/canonical-producer-contract.test.ts@@ -176,7 +176,8 @@ const SITES: Array<[string, string, Record<string, unknown>, string[] | RegExp]>'use-preview-routing restart','preview.restart',{ session_id: 's', url: 'http://x' },- /preview\.restart is not available/+ // TUI-12: the owner serves it (gateway/session_tui_side.py), so it travels as itself.+ ['preview.restart']],['projects.ts moveSessionToProject (B21 / C-hx-2)',diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.tsindex d20c7199d57..1190e7cff36 100644--- a/apps/desktop/src/api/canonical-protocol.ts+++ b/apps/desktop/src/api/canonical-protocol.ts@@ -133,7 +133,8 @@ export function splitRewindSubmit(params: Record<string, unknown>): { rewind: Re// Session verbs only the legacy sidecar implements: it looks the session up in its own table,// which never holds an owner session, and answers `session not found` (read by the renderer as a// reaped runtime). Refused by name until the owner serves them.-const SIDECAR_SESSION_VERBS = new Set(['handoff.request', 'handoff.state', 'handoff.fail', 'preview.restart'])+// `preview.restart` is served by the owner (gateway/session_tui_side.py).+const SIDECAR_SESSION_VERBS = new Set(['handoff.request', 'handoff.state', 'handoff.fail'])// `config.set` keys the owner serves (tui_gateway/contracts/canonical_projections.py::CanonicalConfigSetParams;// gateway/session_tui_config.py), with the keys that take a `scope` (`reasoning --global`, thediff --git a/gateway/session_tui_side.py b/gateway/session_tui_side.pyindex 01114820e48..8b72d38a297 100644--- a/gateway/session_tui_side.py+++ b/gateway/session_tui_side.py@@ -26,14 +26,16 @@ _RUNTIME_KEYS = ('api_key', 'base_url', 'provider', 'requested_provider', 'api_mdef handlers(connection):- return {'prompt.background': partial(background, connection), 'prompt.btw': partial(btw, connection)}+ return {'prompt.background': partial(background, connection), 'prompt.btw': partial(btw, connection),+ 'preview.restart': partial(preview_restart, connection)}-def _admit(connection, ref, params, prefix):+def _admit(connection, ref, params, prefix, required='text', optional=()):"""Shared admission: ``(live, policy, text, task_id)`` or a refusal before any work starts."""- text = params.get('text')- if (set(params) - {'session_id', 'profile', 'text'} or not isinstance(ref.session_id, str)- or not ref.session_id or not isinstance(text, str) or not text.strip()):+ text = params.get(required)+ if (set(params) - {'session_id', 'profile', required, *optional} or not isinstance(ref.session_id, str)+ or not ref.session_id or not isinstance(text, str) or not text.strip()+ or any(params.get(key) is not None and not isinstance(params[key], str) for key in optional)):raise RuntimeStoreError('invalid_params')authority = connection.authorityif ref.session_id not in authority.sessions:@@ -72,6 +74,37 @@ def _resolve_runtime(authority, policy):return _resolve_policy_agent_runtime(authority.runner, policy)+def _side_agent(authority, policy, live, task_id, **overrides):+ """A fresh ``AIAgent`` on the session's frozen route (call inside ``_side_scope``)."""+ from agent.skill_utils import parse_config_string_list+ from gateway.run import _checkpoint_agent_kwargs+ from run_agent import AIAgent+ runner = authority.runner+ model, runtime = _resolve_runtime(authority, policy)+ config = policy.config(authority)+ pr = getattr(runner, '_provider_routing', None) or {}+ refresh_fallback = getattr(runner, '_refresh_fallback_model', None)+ kwargs = dict(+ model=model, **{key: runtime.get(key) for key in _RUNTIME_KEYS if key in runtime},+ **_checkpoint_agent_kwargs(config),+ max_iterations=policy.max_turns, quiet_mode=True, verbose_logging=False,+ enabled_toolsets=list(policy.current_toolsets(config)),+ disabled_toolsets=parse_config_string_list((config.get('agent') or {}).get('disabled_toolsets')) or None,+ reasoning_config=policy.current_reasoning_config(runner, live.route),+ service_tier=policy.current_service_tier(runner, live.route),+ request_overrides=dict(runtime.get('request_overrides') or {}),+ providers_allowed=pr.get('only'), providers_ignored=pr.get('ignore'), providers_order=pr.get('order'),+ provider_sort=pr.get('sort'), provider_require_parameters=pr.get('require_parameters', False),+ provider_data_collection=pr.get('data_collection'),+ # Its own session in the owning profile's store, like the sidecar's ``bg_*`` rows.+ session_id=task_id, platform=policy.platform, session_db=authority.db,+ fallback_model=refresh_fallback() if callable(refresh_fallback) else None,+ load_soul_identity=not policy.ignore_rules, skip_memory=policy.ignore_rules,+ side_agent=True)+ kwargs.update(overrides)+ return AIAgent(**kwargs)++def _spawn(authority, ref, task_id, event_type, body, extra=None):"""Run ``body()`` on a daemon thread; publish its text (or ``error: <exc>``) on the session."""extra = extra or {}@@ -100,34 +133,10 @@ async def background(connection, ref, params):"""``/bg <prompt>``: a fresh agent on the session's route runs the prompt to completion."""live, policy, text, task_id = _admit(connection, ref, params, 'bg')authority = connection.authority- runner = authority.runnerdef body():- from agent.skill_utils import parse_config_string_list- from gateway.run import _checkpoint_agent_kwargs- from run_agent import AIAgentwith _side_scope(authority, policy, task_id):- model, runtime = _resolve_runtime(authority, policy)- config = policy.config(authority)- pr = getattr(runner, '_provider_routing', None) or {}- refresh_fallback = getattr(runner, '_refresh_fallback_model', None)- agent = AIAgent(- model=model, **{key: runtime.get(key) for key in _RUNTIME_KEYS if key in runtime},- **_checkpoint_agent_kwargs(config),- max_iterations=policy.max_turns, quiet_mode=True, verbose_logging=False,- enabled_toolsets=list(policy.current_toolsets(config)),- disabled_toolsets=parse_config_string_list((config.get('agent') or {}).get('disabled_toolsets')) or None,- reasoning_config=policy.current_reasoning_config(runner, live.route),- service_tier=policy.current_service_tier(runner, live.route),- request_overrides=dict(runtime.get('request_overrides') or {}),- providers_allowed=pr.get('only'), providers_ignored=pr.get('ignore'), providers_order=pr.get('order'),- provider_sort=pr.get('sort'), provider_require_parameters=pr.get('require_parameters', False),- provider_data_collection=pr.get('data_collection'),- # Its own session in the owning profile's store, like the sidecar's ``bg_*`` rows.- session_id=task_id, platform=policy.platform, session_db=authority.db,- fallback_model=refresh_fallback() if callable(refresh_fallback) else None,- load_soul_identity=not policy.ignore_rules, skip_memory=policy.ignore_rules,- side_agent=True)+ agent = _side_agent(authority, policy, live, task_id)try:result = agent.run_conversation(user_message=text, task_id=task_id)finally:@@ -161,3 +170,58 @@ async def btw(connection, ref, params):return answer_side_question(text, history, parent_agent=agent, main_runtime=main_runtime) or ''return _spawn(authority, ref, task_id, 'btw.complete', body, extra={'question': text})+++async def preview_restart(connection, ref, params):+ """Desktop preview pane "restart dev server": a hidden terminal+file agent brings the preview+ URL's server back up (rules: ``tui_gateway/methods_prompt.py`` ``_PREVIEW_RESTART_RULES``).+ Detached like ``/bg``; progress rides ``preview.restart.progress``, the answer+ ``preview.restart.complete`` ``{task_id, text}``. Context is the session's stored transcript."""+ live, policy, url, task_id = _admit(connection, ref, params, 'preview', required='url',+ optional=('cwd', 'context'))+ authority = connection.authority+ import os+ from tui_gateway.methods_prompt import _PREVIEW_RESTART_HISTORY_NOTE, _PREVIEW_RESTART_RULES+ cwd, context = (str(params.get(key) or '').strip() for key in ('cwd', 'context'))+ from gateway.session_local_recovery import transcript_target+ target = transcript_target(authority, ref)++ def progress(text):+ if (text := str(text or '').strip()) and (stream := authority.sessions.get(ref.session_id)) is not None:+ stream.event_stream.publish(ref.session_id, {'task_id': task_id, 'text': text},+ event_type='preview.restart.progress')++ def body():+ from tui_gateway.agent_callbacks import _preview_restart_history+ try: # A malformed client path (embedded NUL, a missing dir) is "no validated cwd".+ preview_cwd = os.path.abspath(os.path.expanduser(cwd)) if cwd else ''+ preview_cwd = preview_cwd if preview_cwd and os.path.isdir(preview_cwd) else ''+ except (OSError, ValueError):+ preview_cwd = ''+ history = _preview_restart_history({'history': authority.db.get_messages_as_conversation(target)+ if target else []})+ prompt = '\n'.join(line for line in [+ 'The desktop preview pane cannot load a local server URL.', f'Preview URL: {url.strip()}',+ f"Current working directory: {cwd or '(unknown)'}",+ f'Preview console:\n{context}' if context else '',+ _PREVIEW_RESTART_HISTORY_NOTE if history else '', *_PREVIEW_RESTART_RULES] if line)+ with _side_scope(authority, policy, task_id):+ if preview_cwd:+ from tools.terminal_tool import register_task_env_overrides+ register_task_env_overrides(task_id, {'cwd': preview_cwd})+ try:+ progress('Starting hidden restart agent')+ # Deliberately NOT closed via AIAgent.close(): it would kill the background+ # server this task exists to leave running.+ agent = _side_agent(authority, policy, live, task_id, enabled_toolsets=['terminal', 'file'],+ disabled_toolsets=None, session_db=None, skip_memory=True,+ tool_start_callback=lambda _id, name, _args: progress(f'Running {name}'))+ result = agent.run_conversation(user_message=prompt, task_id=task_id,+ conversation_history=history or None)+ finally:+ with contextlib.suppress(Exception):+ from tools.terminal_tool import clear_task_env_overrides+ clear_task_env_overrides(task_id)+ return result.get('final_response', str(result)) if isinstance(result, dict) else str(result)++ return _spawn(authority, ref, task_id, 'preview.restart.complete', body)diff --git a/tests/gateway/test_session_tui_side.py b/tests/gateway/test_session_tui_side.pyindex ec62d973406..eae6af4053e 100644--- a/tests/gateway/test_session_tui_side.py+++ b/tests/gateway/test_session_tui_side.py@@ -89,3 +89,32 @@ def test_btw_answers_over_a_snapshot_without_touching_the_conversation(tmp_path)assert [r[0] for r in admissions(home)] == ['warm']assert (await rpc(ws, 'session.resume', session_id=sid))['result']['messages'] == beforeasyncio.run(probe())++[email protected]("linux")+def test_preview_restart_runs_a_hidden_terminal_agent_and_reports_on_the_session(tmp_path):+ """TUI-12: Desktop's preview-pane "restart dev server" (``preview.restart``) had no owner+ handler, so it always errored on the shared gateway."""+ with owner(tmp_path) as (home, peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ sid = (await rpc(ws, 'session.create', request_id='pv', source='tui', toolsets=[]))['result']['session_id']+ reply, event = await call_and_await_event(+ ws, 'preview.restart', 'preview.restart.complete', session_id=sid,+ url='http://127.0.0.1:5173/', cwd=str(tmp_path), context='PREVIEW_CONSOLE')+ task = reply.get('result', {}).get('task_id', '')+ assert task.startswith('preview_'), reply+ assert event['session_id'] == sid+ assert event['payload'] == {'task_id': task, 'text': 'CONTROL_ACK'}, event+ sent = json.dumps(peer.requests[-1])+ assert 'http://127.0.0.1:5173/' in sent and 'PREVIEW_CONSOLE' in sent+ tools = {t['function']['name'] for t in peer.requests[-1].get('tools') or []}+ assert 'terminal' in tools and 'delegate_task' not in tools, tools+ for params, reason in [({'session_id': sid, 'url': ' '}, 'invalid_params'),+ ({'session_id': sid, 'url': 'http://x', 'cwd': 3}, 'invalid_params'),+ ({'session_id': sid, 'url': 'http://x', 'profile': 'foreign'}, 'profile_mismatch')]:+ denied = await rpc(ws, 'preview.restart', **params)+ assert denied.get('error', {}).get('message') == reason, denied+ assert not admissions(home)+ assert not (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']+ asyncio.run(probe())