← Commit history

Preserve native engine selection and rename without a daemon

John Lauer ·ccb2edbca4 · ·parent 2824405
6 files changed +118−8
.pkgignoreadded+8
@@ -0,0 +1,8 @@+# Documentation media remains on the wiki; it is not needed by the installed app.+# Keep the explicitly declared videos and dashboard media used by local playback.+docs/**/*.png+docs/**/*.jpg+docs/**/*.jpeg+docs/**/*.webp+docs/**/*.mp4+docs/**/*.zip
docs/THREAD-NAMES.md+3
@@ -20,6 +20,9 @@ adom-codex thread rename "Load tests" The command targets `CODEX_THREAD_ID`; `--id <UUID>` explicitly targets another conversation. It writes through `thread/name/set`, verifies `thread/read`, and synchronizes Hydrogen's display label when available. It never writes SQLite.+It uses an existing Adom backend when available; otherwise a short-lived native+metadata process performs only the rename/readback and exits, without starting+a model turn or leaving a daemon running. The user's engine choice stays intact. `--native-only` is the internal nonrecursive path used by Hydrogen. Output clearly separates native persistence from visible-tab verification. 
runtime/manage.py+8−1
@@ -55,6 +55,13 @@ class Integration:         text = self.settings.read_text() if self.settings.exists() else '{}\n'         current = {e[0]: e[1] for e in entries(text)[0]}         previous = current.get(KEY)+        native_engine = current.get('adom-vscode.codexEngine') == 'codex'+        if self.home == Path.home().resolve() and shutil.which('adom-vscode'):+            try:+                choice = subprocess.run(['adom-vscode', 'config', 'get', 'adom-vscode.codexEngine'],+                                        capture_output=True, text=True, timeout=5)+                native_engine = json.loads(choice.stdout).get('value') == 'codex' or native_engine+            except (OSError, ValueError, subprocess.TimeoutExpired): pass         if previous and previous != str(self.launcher):             return {'state': 'custom_cli_preserved', 'reason': 'Existing custom Codex CLI retained'}         if self.launcher.exists() and not any(s in self.launcher.read_text() for s in@@ -77,7 +84,7 @@ class Integration:         launcher = '#!/bin/sh\n# adom/codex runtime\nexec python3 ' + shlex.quote(str(self.directory / 'runtime.py')) + ' "$@"\n'         atomic(self.launcher, launcher)         self.launcher.chmod(0o755)-        atomic(self.settings, change(text, KEY, str(self.launcher)))+        if not native_engine: atomic(self.settings, change(text, KEY, str(self.launcher)))         report = self.reconcile()         if not isolated:             self.cron(True)
runtime/thread_names.py+65−7
@@ -6,10 +6,73 @@ import re import sqlite3 import time from urllib.parse import quote+from contextlib import contextmanager+import selectors+import subprocess  UUID = re.compile(r'^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$', re.I)  +def name_binary():+    from runtime import native_binary, newer_engine+    try: return native_binary()+    except RuntimeError:+        if os.environ.get('ADOM_CODEX_NATIVE'): raise+        # Outside an IDE child PATH, several VSIX versions can be on disk. Use+        # the registered build, not an arbitrary newest directory.+        directory = Path.home() / '.local/share/code-server/extensions'+        entries = json.loads((directory / 'extensions.json').read_text())+        entry = next(e for e in entries if e.get('identifier', {}).get('id') == 'openai.chatgpt')+        location = entry.get('relativeLocation')+        package = directory / location if location else Path(entry['location']['path'])+        if package.resolve().parent != directory.resolve(): raise RuntimeError('Registered Codex path is outside the extension directory')+        arch = 'linux-aarch64' if os.uname().machine == 'aarch64' else 'linux-x86_64'+        binary = package / 'bin' / arch / 'codex'+        if not binary.is_file(): raise RuntimeError('The registered Codex executable is unavailable')+        return newer_engine(binary)+++@contextmanager+def name_connection():+    from runtime import state_dir, process_matches, unix_connect+    try: metadata = json.loads((state_dir() / 'server.json').read_text())+    except (OSError, ValueError): metadata = None+    if metadata and process_matches(metadata):+        with unix_connect(metadata['socket'], compression=None, open_timeout=5,+                          close_timeout=1, max_size=None) as connection:+            yield connection+        return+    # A native/custom engine need not keep an Adom backend alive. This metadata-+    # only client starts no chat/model turn and leaves no daemon behind.+    process = subprocess.Popen([str(name_binary()), 'app-server'], stdin=subprocess.PIPE,+                               stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0)+    selector = selectors.DefaultSelector()+    selector.register(process.stdout, selectors.EVENT_READ)+    class Stdio:+        buffer = b''+        def send(self, message):+            process.stdin.write(message.encode() + b'\n')+        def recv(self, timeout):+            deadline = time.monotonic() + timeout+            while b'\n' not in self.buffer:+                if not selector.select(max(0, deadline-time.monotonic())):+                    raise TimeoutError('Codex metadata request timed out')+                chunk = os.read(process.stdout.fileno(), 65536)+                if not chunk: raise RuntimeError('Codex metadata process closed unexpectedly')+                self.buffer += chunk+                if len(self.buffer) > 16 * 1024 * 1024: raise RuntimeError('Codex metadata response exceeded its size limit')+            line, self.buffer = self.buffer.split(b'\n', 1)+            return line.decode()+    try: yield Stdio()+    finally:+        selector.close()+        process.stdin.close()+        if process.poll() is None: process.terminate()+        try: process.wait(timeout=3)+        except subprocess.TimeoutExpired: process.kill(); process.wait(timeout=3)+        process.stdout.close()++ def list_threads(home=None, limit=300):     home = Path(home or os.environ.get('CODEX_HOME', Path.home() / '.codex'))     # Numeric schema order (state_10 must outrank state_9). Never create or write a DB.@@ -50,18 +113,13 @@ def native_names(thread_ids, home=None):   def rename_thread(name, thread_id=None):-    from runtime import state_dir, process_matches, unix_connect     thread_id = thread_id or os.environ.get('CODEX_THREAD_ID', '')     if not UUID.fullmatch(thread_id):         raise ValueError('Pass --id <conversation UUID>, or run inside a Codex thread (CODEX_THREAD_ID).')     name = name.strip()     if not name or len(name) > 200 or any(ord(c) < 32 for c in name):         raise ValueError('Use a nonempty, single-line name of at most 200 characters.')-    metadata = json.loads((state_dir() / 'server.json').read_text())-    if not process_matches(metadata):-        raise RuntimeError('The Adom Codex backend is unavailable; no name was changed.')-    with unix_connect(metadata['socket'], compression=None, open_timeout=5,-                      close_timeout=1, max_size=None) as connection:+    with name_connection() as connection:         seq = 0          def rpc(method, params):@@ -71,7 +129,7 @@ def rename_thread(name, thread_id=None):             deadline = time.monotonic() + 15             while time.monotonic() < deadline:                 reply = json.loads(connection.recv(timeout=max(.01, deadline-time.monotonic())))-                if reply.get('id') == seq:+                if reply.get('id') == seq and ('result' in reply or 'error' in reply):                     if 'error' in reply:                         raise RuntimeError(str(reply['error']))                     return reply['result']
tests/test_integration.py+11
@@ -113,6 +113,17 @@ class PackageLifecycle(unittest.TestCase):             manager.uninstall(isolated=True)             self.assertEqual(main.read_text(), original) +    def test_native_engine_choice_keeps_cli_setting_untouched_but_installs_titles(self):+        with tempfile.TemporaryDirectory() as tmp:+            manager = Integration(Path(tmp))+            extension, _ = self.extension(Path(tmp))+            manager.settings.parent.mkdir(parents=True)+            original = '{"adom-vscode.codexEngine":"codex","editor.fontSize":17}'+            manager.settings.write_text(original)+            manager.install(isolated=True)+            self.assertEqual(manager.settings.read_text(), original)+            self.assertIn('prepareForProvider', (extension / 'out/extension.js').read_text())+     def test_whole_package_installs_with_no_system_dependencies(self):         with tempfile.TemporaryDirectory() as tmp:             subprocess.run([sys.executable, str(ROOT/'install.py'), '--home', tmp], check=True, capture_output=True)
tests/test_thread_names.py+23
@@ -75,5 +75,28 @@ class ThreadNamesTest(unittest.TestCase):                 db.execute('insert into threads values(?,?,?)', (SID, None, 'Explain voltage versus current'))             self.assertEqual(native_names([SID], directory), {SID: 'Explain voltage versus current'}) +    def test_native_engine_without_daemon_uses_and_reaps_metadata_process(self):+        with tempfile.TemporaryDirectory() as directory:+            directory = Path(directory)+            program = directory / 'metadata-server'+            program.write_text('''#!/usr/bin/env python3+import sys,json,os+from pathlib import Path+Path(__file__).with_suffix('.pid').write_text(str(os.getpid()))+name=None+for line in sys.stdin:+ request=json.loads(line)+ if 'id' not in request:continue+ if request['method']=='thread/name/set':name=request['params']['name']+ result={'thread':{'id':request.get('params',{}).get('threadId'),'name':name}} if request['method']=='thread/read' else {}+ print(json.dumps({'id':request['id'],'result':result}),flush=True)+''')+            program.chmod(0o755)+            with patch.object(runtime, 'state_dir', return_value=directory), patch('thread_names.name_binary', return_value=program):+                result = rename_thread('Native engine name', SID)+            self.assertTrue(result['persisted'])+            self.assertFalse((directory / 'server.json').exists())+            with self.assertRaises(ProcessLookupError): os.kill(int(program.with_suffix('.pid').read_text()), 0)+  if __name__ == '__main__': unittest.main()