← All Pull Requests

Use native conversation names for Codex editor titles and verified rename #7

Closed Draft opened by John Lauer

Related to #4; keep the issue open until native editor validation and deployed release.

Codex already generates concise thread names, but Adom paints legacy prompt previews while the real editor title stays Codex. This candidate uses Codex's saved native name as the authority and updates WebviewPanel.title, so the intended behavior includes Ctrl+Tab and Open Editors as well as the tab strip.

Adds a verified native rename CLI, panel-scoped title subscriptions, a renderer identity bridge for new panels, persisted identity for uniquely identified hidden restored panels, protection against late reads/vendor previews, and lifecycle cleanup. The managed patch can upgrade from 0.1.38 and uninstall reversibly. Installed instructions execute native rename for natural-language requests and /rename.

Validation: 4 naming tests, 6 integration tests, Node identity/race/lifecycle/CSP/hidden-restore tests pass. Live native rename/readback and native rename event verified. The existing reconnection fixture fails identically on unmodified 0.1.38 and candidate; runtime.py is unchanged. See docs/THREAD-NAMES.md.

Draft: requires a real editor Ctrl+Tab/Open Editors/reopen/restart acceptance run and a tested legacy Hydrogen-alias migration policy before release. Pair with adom/adom-vscode#8 and adom/hydrogen#192. No package release, runtime installation or editor reload has been performed.

(edited)

Diff Skip to comments

--- a/adom_codex.py+++ b/adom_codex.py@@ -1,115 +1,137 @@⋯ 82 unchanged lines ⋯   if self.path in ['/ai-threads/run-prompt','/codex/ai-threads/run-prompt']:return self.proxy()   return self.send_error(404) def main():+ if len(sys.argv)>1 and sys.argv[1]=='thread':+  sys.path.insert(0,str(ROOT/'runtime'))+  from thread_names import list_threads,rename_thread+  import sqlite3+  p=argparse.ArgumentParser(prog='adom-codex thread');sub=p.add_subparsers(dest='action',required=True)+  r=sub.add_parser('rename');r.add_argument('name');r.add_argument('--id');r.add_argument('--native-only',action='store_true',help='Skip Hydrogen label synchronization (used by Hydrogen itself)')+  l=sub.add_parser('list');l.add_argument('--limit',type=int,default=300)+  a=p.parse_args(sys.argv[2:])+  try:+   result=rename_thread(a.name,a.id) if a.action=='rename' else {'ok':True,'sessions':list_threads(limit=max(1,min(a.limit,1000)))}+   if a.action=='rename' and not a.native_only:+    control=Path.home()/'.adom/hydrogen-control-url'+    if control.exists():+     try:+      request=urllib.request.Request(control.read_text().strip().rstrip('/')+'/ai-threads/rename',data=json.dumps({'key':'codex:'+result['id'],'name':result['name']}).encode(),headers={'Content-Type':'application/json'})+      reply=json.load(urllib.request.urlopen(request,timeout=25))+      result['hydrogen_synced']=reply.get('ok') is True+     except (OSError,ValueError):result['hydrogen_synced']=False+   print(json.dumps(result,ensure_ascii=False));return+  except (OSError,ValueError,RuntimeError,TimeoutError,sqlite3.Error) as e:+   print(json.dumps({'ok':False,'error':str(e)}));raise SystemExit(1)  p=argparse.ArgumentParser();p.add_argument('command',choices=['context','serve','_serve']);p.add_argument('--print-url',action='store_true');p.add_argument('--port',type=int,default=47863);a=p.parse_args()  if a.command=='context':print(json.dumps(context(),indent=2));return  if a.command=='_serve':ThreadingHTTPServer(('127.0.0.1',a.port),Handler).serve_forever();return⋯ 24 unchanged lines ⋯   else:raise RuntimeError('Dashboard failed to start; inspect '+str(log/'dashboard.log'))  urlfile.write_text(url);print(url,flush=True) if __name__=='__main__':main()+--- a/install.py+++ b/install.py@@ -1,35 +1,37 @@⋯ 19 unchanged lines ⋯ block=f'''{a} ## Adom ecosystem entry point For Adom work, run `adom-codex context` and read `{skill}/SKILL.md` before choosing tools. Recheck dynamic target and board state on resume. For opening videos/files/folders, follow codex-adom-desktop-artifacts; for choosing verbs and background controls, follow codex-adom-bridge-workflows. For PCB routing, power pours or copper-ablation design, follow codex-adom-electrical-routing. Use existing Adom skills for task-specific guidance. Preserve user configuration, foreground preferences, and pinned development bridges.+For "name/rename this thread/tab xyz" or `/rename xyz`, run `adom-codex thread rename "xyz"`; it targets CODEX_THREAD_ID and verifies Codex's saved native name. Do not just acknowledge the name or change a display label. Codex supplies automatic names after the first prompt. {b}''' if (a in old)!=(b in old) or old.count(a)>1 or old.count(b)>1:raise RuntimeError('Malformed managed block; preserving AGENTS.md for review') if a in old:⋯ 7 unchanged lines ⋯ runtime_args=['--home',str(home)] if args.home else [] subprocess.run([sys.executable,str(dest/'runtime/manage.py'),'install',*runtime_args],check=True) print('OK: Codex ecosystem entry point, skills, CLI, dashboard and container integration installed. Start a new Codex session to load instructions; reload the editor to activate runtime/UI changes.')+--- a/runtime/manage.py+++ b/runtime/manage.py@@ -1,246 +1,262 @@⋯ 116 unchanged lines ⋯             if not declarations: raise ValueError('Renderer initializer signature changed')             w, role, disposal = declarations[-1].groups()             if w != m['w']: raise ValueError('Renderer initializer does not match startup call')-            replacement = (f'{w}.html=await this.getWebviewContent({w}),' + JS_BEGIN ++            replacement = (f'{w}.html=require({json.dumps(str(self.directory / "thread-names.cjs"))}).prepare(await this.getWebviewContent({w})),' + JS_BEGIN +                 f'require({json.dumps(str(self.directory / "webview.cjs"))}).watchRenderer({w},{role},this,{m["g"]},{disposal})' + JS_END)             patched = text[:m.start()] + replacement + text[m.end():]             if main.read_text() != text: raise ValueError('Extension is changing; retrying later')⋯ 2 unchanged lines ⋯             self.write_json(extension / '.adom-codex-patch.json',                             {'owner': 'adom/codex', 'original': m[0], 'replacement': replacement,                              'main': str(main.relative_to(extension.resolve()))})+        else:+            # Upgrade only our exact previous fragment. Never patch another writer's edit.+            record_path = extension / '.adom-codex-patch.json'+            record = json.loads(record_path.read_text())+            old = record['replacement']+            if record.get('owner') != 'adom/codex' or text.count(old) != 1:+                raise ValueError('Managed renderer fragment changed; retained for review')+            if '.prepare(await this.getWebviewContent(' not in old:+                start = re.match(r'([\w$]+)\.html=await this\.getWebviewContent\(\1\),', old)+                if not start: raise ValueError('Managed renderer assignment changed')+                w = start[1]+                replacement = (f'{w}.html=require({json.dumps(str(self.directory / "thread-names.cjs"))}).prepare(await this.getWebviewContent({w})),' + old[start.end():])+                atomic(main, text.replace(old, replacement, 1))+                record['replacement'] = replacement+                self.write_json(record_path, record)         css = (self.directory / 'composer.css').read_text()         styles = []         for path in (extension / 'webview/assets').glob('*.css'):⋯ 112 unchanged lines ⋯   if __name__ == '__main__': main()+--- a/runtime/webview.cjs+++ b/runtime/webview.cjs@@ -1,123 +1,125 @@⋯ 108 unchanged lines ⋯   // VS Code does not instantiate a restored hidden webview until it is shown.   const panel = role === 'panel' ? provider.findPanelByWebview(webview) : null;   if (!panel) { guard.start(); return; }+  require('./thread-names.cjs').watch(webview, panel, provider, onDispose);   const update = () => {     if (panel.visible) guard.start();     else if (guard.timeout != null) {⋯ 6 unchanged lines ⋯   disposed = onDispose(() => { changed.dispose(); disposed?.dispose(); guard.dispose(); });   update(); };+--- a/runtime/thread_names.py+++ b/runtime/thread_names.py@@ -0,0 +1,67 @@+"""Codex owns conversation names. Read its store; mutate only through its RPC API."""+import json+import os+from pathlib import Path+import re+import sqlite3+import time+from urllib.parse import quote++UUID = re.compile(r'^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$', re.I)+++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.+    dbs = sorted(home.glob('state_*.sqlite'),+                 key=lambda p: int(re.search(r'state_(\d+)', p.name)[1]))+    if not dbs:+        return []+    with sqlite3.connect('file:' + quote(str(dbs[-1].resolve())) + '?mode=ro',+                         uri=True, timeout=1) as db:+        cols = {r[1] for r in db.execute('pragma table_info(threads)')}+        title = "coalesce(nullif(trim(name),''),title)" if 'name' in cols else 'title'+        rows = db.execute(f'SELECT id,{title},cwd,updated_at FROM threads '+                          'WHERE archived=0 ORDER BY updated_at DESC LIMIT ?', (limit,))+        return [{'id': r[0], 'title': r[1], 'cwd': r[2],+                 'when': r[3] * 1000 if r[3] < 10**12 else r[3]} for r in rows]+++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:+        seq = 0++        def rpc(method, params):+            nonlocal seq+            seq += 1+            connection.send(json.dumps({'id': seq, 'method': method, 'params': params}))+            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 'error' in reply:+                        raise RuntimeError(str(reply['error']))+                    return reply['result']+            raise TimeoutError('Codex did not confirm the rename; read back before retrying.')++        rpc('initialize', {'clientInfo': {'name': 'adom-thread-names', 'version': '1'},+                          'capabilities': {'experimentalApi': True}})+        connection.send(json.dumps({'method': 'initialized'}))+        rpc('thread/name/set', {'threadId': thread_id, 'name': name})+        thread = rpc('thread/read', {'threadId': thread_id, 'includeTurns': False})['thread']+        if thread.get('name') != name:+            raise RuntimeError('Codex accepted the request but did not confirm the saved name.')+    return {'ok': True, 'id': thread_id, 'name': name, 'persisted': True,+            'source': 'codex', 'tab_verified': False}+--- a/runtime/thread-names.cjs+++ b/runtime/thread-names.cjs@@ -0,0 +1,110 @@+'use strict';+const {randomUUID, createHash} = require('node:crypto');+const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;++// The composer exposes the actual conversation ID, including in a panel whose URI is+// still /extension/panel/new. Observe that identity, never whichever tab is active.+function identityBridge() {+  let api, last;+  const acquire = window.acquireVsCodeApi;+  window.acquireVsCodeApi = function () { api = acquire(); return api; };+  function report() {+    const el = document.querySelector('[data-above-composer-conversation-id], [data-response-annotation-conversation]');+    const id = el && (el.getAttribute('data-above-composer-conversation-id') || el.getAttribute('data-response-annotation-conversation'));+    if (api && id && id !== last) { last = id; api.postMessage({type: 'adom-thread-identity', threadId: id}); }+  }+  document.addEventListener('DOMContentLoaded', () => {+    new MutationObserver(report).observe(document.body, {subtree: true, childList: true,+      attributes: true, attributeFilter: ['data-above-composer-conversation-id', 'data-response-annotation-conversation']});+    report();+  }, {once: true});+}++exports.prepare = function (html) {+  if (html.includes('/* adom-thread-identity */')) return html;+  const nonce = /<script\b[^>]*\bnonce=["']([^"']+)["']/.exec(html);+  if (!nonce) return html; // CSP/renderer changed: leave the upstream page intact.+  const script = `<script nonce="${nonce[1]}">/* adom-thread-identity */(${identityBridge.toString()})();</script>`;+  return html.replace(/<script\b/, script + '<script');+};++exports.watch = function (webview, panel, provider, onDispose) {+  const connection = provider.codexMcpConnection;+  if (!panel || !connection || typeof connection.registerProvider !== 'function') return;+  const route = provider.editorPanels?.get(panel)?.initialRoute || '';+  let current = /\/local\/([0-9a-f-]{36})(?:[/?#]|$)/i.exec(route)?.[1];+  // Adom gives every fresh tab a nonce URI. Preserve its UUID binding so restored+  // hidden tabs can acquire their true native title before their renderer is shown.+  // A bare /new is reusable, so it must NEVER inherit an earlier conversation.+  const identityKey = /\/extension\/panel\/new\?.+/.test(route)+    ? 'adom.codex.panel-identity.' + createHash('sha256').update(route).digest('hex') : null;+  let disposed = false, generation = 0;+  let desired;+  // Upstream also assigns its old preview asynchronously after opening the panel.+  // Keep those late assignments from undoing an already-confirmed native name.+  const ownTitle = Object.getOwnPropertyDescriptor(panel, 'title');+  let descriptor = ownTitle, prototype = Object.getPrototypeOf(panel);+  while (!descriptor && prototype) { descriptor = Object.getOwnPropertyDescriptor(prototype, 'title'); prototype = Object.getPrototypeOf(prototype); }+  let wrapped = false;+  if (descriptor?.get && descriptor?.set && (!ownTitle || ownTitle.configurable) && Object.isExtensible(panel)) {+    Object.defineProperty(panel, 'title', {configurable: true, enumerable: !!descriptor.enumerable,+      get() {return descriptor.get.call(panel);},+      set(value) {descriptor.set.call(panel, desired ?? value);}});+    wrapped = true;+  }+  const pending = new Map();+  const key = 'adom-thread-names-' + randomUUID();+  const apply = (id, name) => {+    if (!disposed && id === current && typeof name === 'string' && name.trim()) { desired = name; panel.title = name; }+  };+  const registration = connection.registerProvider(key, {+    onResult(message) {+      const request = pending.get(String(message.id));+      if (!request) return;+      pending.delete(String(message.id)); clearTimeout(request.timer);+      if (request.generation === generation && !message.error) {+        const thread = message.result?.thread;+        if (thread?.id === current) apply(current, thread.name);+      }+    },+    onNotification(message) {+      if (message.method === 'thread/name/updated' && message.params?.threadId === current) {+        ++generation; // A late thread/read must never undo a newer rename.+        apply(current, message.params.threadName ?? message.params.name);+      }+    },+  });+  function refresh() {+    if (disposed || !current) return;+    const id = randomUUID(), version = ++generation;+    const timer = setTimeout(() => pending.delete(id), 15000);+    timer.unref?.(); pending.set(id, {timer, generation: version});+    connection.sendRequest(key, id, 'thread/read', {threadId: current, includeTurns: false});+  }+  const messages = webview.onDidReceiveMessage(message => {+    if (message?.type !== 'adom-thread-identity' || !UUID.test(message.threadId || '')) return;+    if (message.threadId !== current) {+      current = message.threadId; desired = undefined;+      if (identityKey && provider.globalState?.update) {+        const id = current;+        Promise.resolve().then(() => provider.globalState.update(identityKey, id)).catch(() => {});+      }+      refresh();+    }+  });+  const changed = panel.onDidChangeViewState(() => { if (panel.visible) refresh(); });+  let dispose;+  dispose = onDispose(() => {+    disposed = true; registration.dispose(); messages.dispose(); changed.dispose(); dispose?.dispose();+    if (wrapped) { if (ownTitle) Object.defineProperty(panel, 'title', ownTitle); else delete panel.title; }+    for (const request of pending.values()) clearTimeout(request.timer);+    pending.clear();+  });+  refresh();+  if (!current && identityKey && provider.globalState?.get) {+    Promise.resolve().then(() => provider.globalState.get(identityKey)).then(id => {+      if (!disposed && !current && UUID.test(id || '')) { current = id; refresh(); }+    }).catch(() => {});+  }+};+--- a/skills/codex-adom/SKILL.md+++ b/skills/codex-adom/SKILL.md@@ -1,53 +1,71 @@⋯ 29 unchanged lines ⋯  `/status` in the Codex TUI shows it. From a script, or for another machine: `GET https://chatgpt.com/backend-api/wham/usage` with the access token and account id from `~/.codex/auth.json` (`Authorization: Bearer`, `ChatGPT-Account-Id`). It answers `rate_limit.primary_window.used_percent` and `reset_at`, `limit_reached`, the credits balance and `rate_limit_reset_credits`. No model runs. Never print the token. The script that reads every AI at once, and how to run it on each machine, is in the `hydrogen-ai-agents` skill, section Quota. +## Conversation names++Codex generates a short name after the first prompt. Adom uses that native name on+the editor tab; do not create another automatic title or replace it with the raw prompt.+When the user says "name this thread xyz", "rename this tab", or `/rename xyz`, run:++```bash+adom-codex thread rename "xyz"+```++This targets `CODEX_THREAD_ID`, writes through Codex's native `thread/name/set` API,+and verifies the saved name. For another conversation, use `--id <conversation UUID>`.+Never infer the target from the active tab. `adom-codex thread list` reads the native+names without changing any conversation. A persisted name and a visibly updated tab+are separate checks: `tab_verified:false` means the CLI verified only persistence.+Do not use temporary CSS or the Hydrogen-only label store as a successful rename.+ ## Focused follow-ups  For Codex Desktop installation or first-run setup, read⋯ 15 unchanged lines ⋯ For explicitly requested floating-copper retention and a Fusion ablation demonstration, also read `../codex-adom-ablation-routing/SKILL.md`.  For “Codex Astra, reproduce this Fusion demo”, read the package `docs/REPRODUCE-FUSION.md` (also on the adom/codex wiki). Confirm the active provider/model; discover the user’s desktop; distinguish a saved-plan replay from fresh Astra calculation. Do not assume prompt wording selects Astra.+--- a/tests/test_thread_names.py+++ b/tests/test_thread_names.py@@ -0,0 +1,65 @@+import json+import os+from pathlib import Path+import sqlite3+import sys+import tempfile+import unittest+from unittest.mock import patch++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'runtime'))+from thread_names import list_threads, rename_thread+import runtime++SID = '12345678-1234-1234-1234-123456789abc'+++class ThreadNamesTest(unittest.TestCase):+    def test_native_name_beats_preview_and_old_schema(self):+        with tempfile.TemporaryDirectory() as directory:+            for schema, name in [(9, 'stale'), (10, 'User name')]:+                with sqlite3.connect(str(Path(directory) / f'state_{schema}.sqlite')) as db:+                    db.execute('create table threads(id,name,title,cwd,updated_at,archived)')+                    db.execute('insert into threads values(?,?,?,?,?,0)', (SID, name, 'A very long original prompt', '/project', 100))+            self.assertEqual(list_threads(directory)[0]['title'], 'User name')+            self.assertEqual(list_threads(directory)[0]['when'], 100000)+            self.assertEqual(len(list(Path(directory).glob('state_*.sqlite'))), 2)++    def test_legacy_database_and_archived_threads(self):+        with tempfile.TemporaryDirectory() as directory:+            with sqlite3.connect(str(Path(directory) / 'state_5.sqlite')) as db:+                db.execute('create table threads(id,title,cwd,updated_at,archived)')+                db.execute('insert into threads values(?,?,?,?,0)', (SID, 'Generated title', '/', 100))+                db.execute('insert into threads values(?,?,?,?,1)', ('hidden', 'Archived', '/', 200))+            self.assertEqual([r['title'] for r in list_threads(directory)], ['Generated title'])++    def test_rename_verifies_native_readback_and_does_not_start_a_backend(self):+        class Connection:+            def __init__(self): self.reply = None; self.calls = []+            def __enter__(self): return self+            def __exit__(self, *args): pass+            def send(self, data):+                request = json.loads(data); self.calls.append(request)+                if 'id' not in request: return+                result = {'thread': {'id': SID, 'name': 'hello'}} if request['method'] == 'thread/read' else {}+                self.reply = json.dumps({'id': request['id'], 'result': result})+            def recv(self, **kwargs): return self.reply+        with tempfile.TemporaryDirectory() as directory:+            Path(directory, 'server.json').write_text(json.dumps({'pid': 1, 'socket': '/test/socket'}))+            connection = Connection()+            with patch.object(runtime, 'state_dir', return_value=Path(directory)), patch.object(runtime, 'process_matches', return_value=True), patch.object(runtime, 'unix_connect', return_value=connection):+                result = rename_thread('hello', SID)+            self.assertTrue(result['persisted'])+            self.assertFalse(result['tab_verified'])+            self.assertEqual(connection.calls[2]['method'], 'thread/name/set')+            self.assertEqual(connection.calls[2]['params'], {'threadId': SID, 'name': 'hello'})++    def test_no_guessing_or_invalid_names(self):+        with patch.dict(os.environ, {'CODEX_THREAD_ID': ''}):+            with self.assertRaises(ValueError): rename_thread('hello')+        for name in ['', 'line\nbreak', 'x' * 201]:+            with self.assertRaises(ValueError): rename_thread(name, SID)+++if __name__ == '__main__': unittest.main()+--- a/tests/test_thread_names.cjs+++ b/tests/test_thread_names.cjs@@ -0,0 +1,58 @@+'use strict';+const assert = require('node:assert/strict');+const {prepare, watch} = require('../runtime/thread-names.cjs');+const a = '12345678-1234-1234-1234-123456789abc';+const b = '87654321-1234-1234-1234-123456789abc';+const html = '<html><head><script nonce="ok" src="app.js"></script></head></html>';+assert.equal(prepare(prepare(html)), prepare(html));+assert.ok(prepare(html).indexOf('adom-thread-identity') < prepare(html).indexOf('src="app.js"'));+assert.equal(prepare('<html></html>'), '<html></html>');+function panel(route, globalState) {+  let handler, dispose;+  const calls = [], registrations = new Map();+  let title = 'Codex';+  const p = {get title() {return title;}, set title(value) {title = value;}, visible: true, onDidChangeViewState() {return {dispose() {}};}};+  const connection = {+    registerProvider(key, callbacks) {registrations.set(key, callbacks); return {dispose() {registrations.delete(key);}};},+    sendRequest(key, id, method, params) {calls.push({key, id, method, params});},+  };+  watch({onDidReceiveMessage(fn) {handler = fn; return {dispose() {}};}}, p,+    {codexMcpConnection: connection, editorPanels: new Map([[p, {initialRoute: route}]]), globalState},+    fn => {dispose = fn; return {dispose() {}};});+  return {p, calls, registrations, message: m => handler(m), dispose: () => dispose()};+}+const restored = panel('/local/' + a), fresh = panel('/extension/panel/new');+assert.equal(fresh.calls.length, 0);+fresh.message({type: 'adom-thread-identity', threadId: b});+assert.equal(fresh.calls[0].params.threadId, b);+const first = restored.calls[0], callbacks = restored.registrations.get(first.key);+callbacks.onNotification({method: 'thread/name/updated', params: {threadId: b, threadName: 'Wrong thread'}});+assert.equal(restored.p.title, 'Codex');+callbacks.onNotification({method: 'thread/name/updated', params: {threadId: a, threadName: 'User name'}});+callbacks.onResult({id: first.id, result: {thread: {id: a, name: 'Stale generated name'}}});+assert.equal(restored.p.title, 'User name');+restored.p.title = 'Late raw first prompt';+assert.equal(restored.p.title, 'User name');+assert.equal(fresh.p.title, 'Codex');+restored.dispose(); fresh.dispose();+assert.equal(restored.registrations.size, 0);+console.log('Passed: restored/new panel identity, rename events, stale reads, isolation, disposal and CSP bootstrap.');+(async () => {+  const saved = new Map();+  const state = {get: key => saved.get(key), update(key, value) {saved.set(key, value);}};+  const route = '/extension/panel/new?nonce=unique-tab';+  const initial = panel(route, state);+  initial.message({type: 'adom-thread-identity', threadId: a}); initial.dispose();+  const reopened = panel(route, state);+  await new Promise(resolve => setImmediate(resolve));+  assert.equal(reopened.calls[0].params.threadId, a);+  const generic = panel('/extension/panel/new', state);+  await new Promise(resolve => setImmediate(resolve));+  assert.equal(generic.calls.length, 0);+  const other = panel('/extension/panel/new?nonce=different-tab', state);+  await new Promise(resolve => setImmediate(resolve));+  assert.equal(other.calls.length, 0);+  reopened.dispose(); generic.dispose(); other.dispose();+  console.log('Passed: hidden nonce-tab restore retains identity; reusable/new resources never inherit another thread.');+})().catch(error => {console.error(error); process.exitCode = 1;});+--- a/tests/test_integration.py+++ b/tests/test_integration.py@@ -1,97 +1,117 @@⋯ 81 unchanged lines ⋯             manager.uninstall(isolated=True)             self.assertEqual(json.loads(manager.settings.read_text())[KEY], '/new/user/choice') +    def test_existing_renderer_patch_upgrades_and_uninstalls_exactly(self):+        with tempfile.TemporaryDirectory() as tmp:+            manager = Integration(Path(tmp))+            extension, original = self.extension(Path(tmp))+            manager.install(isolated=True)+            record_path = extension / '.adom-codex-patch.json'+            record = json.loads(record_path.read_text())+            new = record['replacement']+            prefix, rest = new.split('/* adom/codex renderer:begin */', 1)+            old = 'a.html=await this.getWebviewContent(a),/* adom/codex renderer:begin */' + rest+            main = extension / 'out/extension.js'+            main.write_text(main.read_text().replace(new, old))+            record['replacement'] = old+            record_path.write_text(json.dumps(record))+            manager.reconcile()+            self.assertIn('.prepare(await this.getWebviewContent(a))', main.read_text())+            manager.uninstall(isolated=True)+            self.assertEqual(main.read_text(), original)+     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)⋯ 7 unchanged lines ⋯   if __name__ == '__main__': unittest.main()+--- a/docs/THREAD-NAMES.md+++ b/docs/THREAD-NAMES.md@@ -0,0 +1,81 @@+# Native Codex thread names in Adom++Candidate source fix, not a published or deployed release.++Codex already generates a short name after the first prompt. Recent Codex engines+store it in `threads.name` in their native SQLite store; `threads.title` and+`session_index.jsonl` can contain older titles or raw prompt previews. Adom was+painting those previews onto the tab while VS Code's actual editor title remained+`Codex`. That explains why Ctrl+Tab still showed indistinguishable Codex entries.++## Ownership++- **adom/codex** owns the durable backend connection and its opt-in renderer+  integration. `adom-codex thread rename "hello"` uses `CODEX_THREAD_ID` (or explicit+  `--id`), sends `thread/name/set`, then verifies `thread/read`. No SQLite writes.+  It synchronizes Hydrogen's label when available; `--native-only` is the internal+  nonrecursive path used by Hydrogen. CLI output distinguishes saved name from+  visible-tab verification.+- Its renderer integration identifies each panel by the actual conversation ID,+  including the initially anonymous `/extension/panel/new`. It reads the native+  name and subscribes to `thread/name/updated`. It sets **WebviewPanel.title**,+  which changes VS Code's editor model and therefore Ctrl+Tab/Open Editors, rather+  than replacing DOM text. Stale reads and late upstream preview assignments may+  not undo a confirmed name. Listeners are removed when the panel closes.+- **adom-vscode** consumes the package's read-only native name list in its Codex+  Sessions view and `/codex/sessions`; its existing index/rollout reader remains a+  fallback for older packages. Native store changes refresh the visible sidebar.+- **Hydrogen** forwards Codex rename actions to the native command and returns+  success only after native readback. A successful native rename removes its old+  Codex alias, so it does not become a competing authority. Native history reads+  prefer `name` over `title`, with old-schema support.++The installed ecosystem instructions tell Codex to execute the command for+"name this thread xyz" and `/rename xyz`; an assistant acknowledgement is not a+rename. Automatic naming stays with Codex, so no extra title-generation model+call is introduced.++## Activation and remaining release checks++The renderer code activates when the extension host loads the new integration.+An editor reload is required for panels already running old code. Do not reload+other active conversations just to test this change. A custom user CLI remains+preserved; it may not provide the Adom native-name command.++Legacy Hydrogen-only aliases are retained until explicitly renamed through the+native path. A fleet release must decide and test a one-time migration of existing+aliases without overwriting later native user renames.++Before release, verify in a real supported Codex/VS Code pairing:++1. Open two new Codex panels. Prompt each with a different topic. Check each gets+   its native generated name and neither panel claims the other's ID.+2. Inspect the tab strip, **Ctrl+Tab**, and Open Editors: all show that same name.+3. Ask one conversation to name itself `hello`; rename the other through Hydrogen.+   Verify native RPC readback, native panel titles, sidebar and history agree.+4. Close/reopen both, then restart at a safe time. Check names and UUIDs persist.+5. Exercise rapid rename/navigation, a delayed initial preview and a delayed native+   read. A newer user name must win, and an active turn must continue.+6. Remove the temporary `adom-requested-thread-titles` CSS workaround before judging+   the result; a painted label does not satisfy any native-title check.++## Validation on 2026-11-15++Native live `thread/name/set` and fresh `thread/read` confirmed the two requested+names (`hello`, `ranch mhs software`). A real native notification confirmed the+payload is `{threadId, threadName}`. The panel integration is not live yet.++Focused Python tests cover native/legacy schema precedence, numeric schema+ordering, archive filtering, input validation and verified RPC writes. Node tests+cover panel identity, cross-panel isolation, rename notifications, stale replies,+late vendor title writes, disposal and nonce-preserving renderer bootstrap.+Integration tests cover upgrading the previous managed fragment and uninstalling+without overwriting other changes. The adom-vscode extension bundles successfully.++The existing reconnect test `test_same_active_turn_survives_three_proxy_replacements`+fails identically on the unmodified 0.1.38 runtime and candidate: expected+`turn is running`, received `sent 1000 (OK); no close frame received`. This change+does not modify runtime.py. The Hydrogen compile check could not run offline+because the `futures` dependency is not cached. Those are release limitations,+not passing checks.+

Comments

No comments yet.

Log in to comment.