The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): serve complete.path for local sessions on the canonical connection
unsupportedpastels0ca88e677128
diff --git a/gateway/session_complete_path.py b/gateway/session_complete_path.pynew file mode 100644index 00000000000..5698037d858--- /dev/null+++ b/gateway/session_complete_path.py@@ -0,0 +1,39 @@+"""``complete.path`` on the shared gateway: the sidecar's path / ``@`` listing, rooted in one session's folder.++The Ink TUI asks its canonical connection for composer completions. The listing is the sidecar's own+(``tui_gateway/methods_complete.py``); its root is the session's frozen policy cwd, never a cwd the+client sends or the daemon's own folder.+"""+import asyncio+import json+from pathlib import Path++from gateway.session_busy_controls import authorize+from hermes_state_runtime import RuntimeStoreError+++async def complete_path(connection, ref, params):+ if (set(params) - {'session_id', 'profile', 'word', 'cwd'}+ or any(not isinstance(value, str) for value in params.values())):+ raise RuntimeStoreError('invalid_params')+ word = params.get('word', '')+ if not word or not ref.session_id:+ return {'items': []}+ authority = connection.authority+ if ref.session_id not in authority.sessions:+ raise RuntimeStoreError('not_found')+ authorize(connection, ref, params, 'session:read')+ from gateway.session_policy import policy_for_source, terminal_uses_host_cwd+ policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)+ if policy is None or not terminal_uses_host_cwd(json.loads(policy.terminal_json)):+ # A remote or sandboxed backend's tree is not this host's; completion is advisory, so nothing.+ return {'items': []}+ # The listing helpers are bound onto the sidecar module's globals (method_ctx.bind_module).+ from tui_gateway import server++ def listing():+ from gateway.run import _profile_runtime_scope+ with _profile_runtime_scope(Path(authority.profile_id)):+ return server._path_completion_items(word, policy.cwd, None, True)++ return {'items': await asyncio.to_thread(listing)}diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 8d6949c1dfd..46bd859e8e3 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -120,6 +120,8 @@ class AuthorityConnection:from gateway.session_images import attach_bytesfrom functools import partialhandlers['image.attach_bytes'] = partial(attach_bytes, self)+ from gateway.session_complete_path import complete_path+ handlers['complete.path'] = partial(complete_path, self)from gateway.session_prune import prunehandlers['session.prune'] = partial(prune, self)from gateway.session_usage import statsdiff --git a/tests/gateway/test_canonical_complete_path.py b/tests/gateway/test_canonical_complete_path.pynew file mode 100644index 00000000000..b4b5850962c--- /dev/null+++ b/tests/gateway/test_canonical_complete_path.py@@ -0,0 +1,67 @@+"""The Ink TUI's ``complete.path`` over the canonical connection lists the session's own folder.++The local TUI sends every request on its canonical connection; with no handler there, each path+or ``@`` completion answered ``-32601``. The shared gateway's own cwd is its daemon folder, so the+listing must be rooted at the session's policy cwd.+"""+import json+from types import SimpleNamespace++import pytest++from gateway import session_policy+from gateway.session_authority import LiveSession, SessionAuthority+from gateway.session_controls import AuthorityConnection+from hermes_state import SessionDB+from hermes_state_runtime import begin_runtime_epoch+++def rpc(tmp_path, monkeypatch):+ project, daemon, home = tmp_path / 'project', tmp_path / 'daemon', tmp_path / 'home'+ for folder, name in ((project, 'project-notes.md'), (daemon, 'daemon-notes.md'), (home, None)):+ folder.mkdir()+ if name:+ (folder / name).write_text('x', encoding='utf-8')+ monkeypatch.chdir(daemon)+ monkeypatch.setenv('TERMINAL_CWD', str(daemon))+ backend = {'TERMINAL_ENV': 'local'}+ monkeypatch.setattr(session_policy, 'policy_for_source', lambda runner, source: SimpleNamespace(+ cwd=str(project), terminal_json=json.dumps({**backend, 'TERMINAL_CWD': str(project)})))+ with SessionDB(db_path=tmp_path / 'state.db') as db:+ db.create_session('s', source='test')+ epoch = begin_runtime_epoch(db, instance_id='current')+ authority = SessionAuthority(SimpleNamespace(_draining=False), profile_id=str(home),+ instance_id='current', db=db, epoch=epoch)+ authority.sessions['s'] = LiveSession(None, 'route')+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})++ async def call(params):+ return await connection.dispatch({'id': 1, 'method': 'complete.path', 'params': params})++ yield call, backend+++async def test_complete_path_lists_the_session_folder(rpc):+ call, _ = rpc+ reply = await call({'word': '@file:', 'session_id': 's', 'cwd': '/client/claim'})+ assert 'error' not in reply, reply+ texts = [item['text'] for item in reply['result']['items']]+ assert '@file:project-notes.md' in texts+ assert '@file:daemon-notes.md' not in texts+++async def test_complete_path_lists_nothing_for_a_remote_backend_or_without_a_session(rpc):+ call, backend = rpc+ assert (await call({'word': '@file:'}))['result'] == {'items': []}+ backend['TERMINAL_ENV'] = 'ssh'+ assert (await call({'word': '@file:', 'session_id': 's'}))['result'] == {'items': []}+++async def test_complete_path_refuses_a_session_it_does_not_serve(rpc):+ call, _ = rpc+ reply = await call({'word': '@file:', 'session_id': 'other'})+ assert reply['error']['data']['reason'] == 'not_found'diff --git a/tui_gateway/methods_complete.py b/tui_gateway/methods_complete.pyindex 6c57e3caba7..43ac54229cf 100644--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@ -182,10 +182,10 @@ def _backend_dir_entries(search_dir: str, session_key: str | None) -> list[tupledef _dir_listing_items(root: str, word: str, path_part: str, prefix_tag: str, is_context: bool,- session_key: str | None = None) -> list[dict]:+ session_key: str | None = None, local: bool | None = None) -> list[dict]:"""Prefix-match entries of the directory ``path_part`` points at (max 30)."""import posixpath- local = _effective_terminal_backend() == "local"+ local = _effective_terminal_backend() == "local" if local is None else local# A non-local backend expands ``~`` itself (the gateway host's home is the wrong one) and its listing# script speaks POSIX: from a Windows gateway host, os.path would hand it ``~\\src`` and list nothing.pth = os.path if local else posixpath@@ -238,15 +238,21 @@ def _(rid, params: dict) -> dict:# session cwd (Desktop sends it) or the session's terminal cwd as-is.root = _completion_cwd(params) if local else (params.get("cwd") or _terminal_task_cwd(session))session_key = session.get("session_key") if session else None+ return _ok(rid, {"items": _path_completion_items(word, root, session_key, local)})+++def _path_completion_items(word: str, root: str, session_key: str | None, local: bool) -> list[dict]:+ """``complete.path``'s items for ``word`` resolved against ``root``; the shared gateway serves the+ same listing against a local session's own folder (``gateway/session_complete_path.py``)."""is_context = word.startswith("@")query = word[1:] if is_context else wordif is_context and not query:- return _ok(rid, {"items": _at_root_items()})+ return _at_root_items()# Plugin `@<prefix>:<query>` runs before the built-in file/folder branching.if is_context and ":" in query:pfx, _, qval = query.partition(":")if pfx not in _BUILTIN_AT_PREFIXES and (plugin_items := _plugin_reference_items(pfx, qval)) is not None:- return _ok(rid, {"items": plugin_items})+ return plugin_items# Bare `@folder` lists as soon as the keyword is typed (the static `@folder:` hint is not accepted).if is_context and (query in {"file", "folder"} or query.startswith(("file:", "folder:"))):prefix_tag, _, path_part = query.partition(":")@@ -263,12 +269,12 @@ def _(rid, params: dict) -> dict:if local and bare_word and len(path_part.strip()) >= 2 and prefix_tag != "folder":items = _fuzzy_basename_items(root, path_part, prefix_tag)else:- items = _dir_listing_items(root, word, path_part, prefix_tag, is_context, session_key)+ items = _dir_listing_items(root, word, path_part, prefix_tag, is_context, session_key, local)# Bare-word `@name` may be an agent mention: profiles rank ABOVE file hits.if bare_word and not prefix_tag:with contextlib.suppress(Exception):items = _profile_mention_items(path_part) + items- return _ok(rid, {"items": items})+ return items@method("complete.slash")diff --git a/ui-tui/src/__tests__/useCompletion.test.ts b/ui-tui/src/__tests__/useCompletion.test.tsindex 6f27aa9a135..2771e46af47 100644--- a/ui-tui/src/__tests__/useCompletion.test.ts+++ b/ui-tui/src/__tests__/useCompletion.test.ts@@ -50,4 +50,19 @@ describe('completionRequestForInput', () => {vi.unstubAllEnvs()}})++ it('names the asking session, whose folder the shared gateway lists', () => {+ try {+ patchUiState({ sid: 'sess-1' })+ expect(completionRequestForInput('read @file:sr')).toMatchObject({+ method: 'complete.path',+ params: { word: '@file:sr', session_id: 'sess-1' }+ })+ resetUiState()+ expect(completionRequestForInput('./sr')?.params).not.toHaveProperty('session_id')+ } finally {+ resetUiState()+ vi.unstubAllEnvs()+ }+ })})diff --git a/ui-tui/src/hooks/useCompletion.ts b/ui-tui/src/hooks/useCompletion.tsindex 5ff69fb0024..e80ba6ab07c 100644--- a/ui-tui/src/hooks/useCompletion.ts+++ b/ui-tui/src/hooks/useCompletion.ts@@ -34,7 +34,7 @@ const TAB_PATH_RE = /((?:["']?(?:[A-Za-z]:[\\/]|\.{1,2}\/|~\/|\/|@|[^"'`\s]+\/))export function completionRequestForInput(input: string):- | { method: 'complete.path'; params: { word: string; cwd?: string }; replaceFrom: number }+ | { method: 'complete.path'; params: { word: string; cwd?: string; session_id?: string }; replaceFrom: number }| { method: 'complete.slash'; params: { text: string }; replaceFrom: number; skillsOnly?: boolean }| null {const isSlashCommand = looksLikeSlashCommand(input)@@ -73,10 +73,12 @@ export function completionRequestForInput(}const cwd = sessionCwd()+ // The shared gateway lists the session's own folder, so it must know which session is asking.+ const sid = getUiState().sidreturn {method: 'complete.path',- params: { word: pathWord, ...(cwd ? { cwd } : {}) },+ params: { word: pathWord, ...(cwd ? { cwd } : {}), ...(sid ? { session_id: sid } : {}) },replaceFrom: input.length - pathWord.length}}