← Commit history

Merge PR #494: Use native Codex titles in Ctrl+Tab and restore conversation identity (native-thread-titles -> main) merge

John Lauer ·2824405acc · ·parents 98b0cac, 74a1165

Showing changes introduced by the merge (against its first parent).

15 files changed +665−3
README.md+4
@@ -133,3 +133,7 @@ Version 0.1.35 gives OpenAI's newest models to fresh installs too. The newest-en ### Skip the repeated IDE walkthrough  Version 0.1.23 opens new Codex editor tabs directly at the prompt. The default ships through Hydrogen’s existing Codex package dependency; it preserves sign-in and permission prompts. See [diagnosis and verification](docs/CODEX-WALKTHROUGH.md). Already-open walkthrough tabs should be closed and reopened.++## Native thread names (0.1.39)++Codex automatic titles and explicit renames now update the actual VS Code editor title, including Ctrl+Tab. Ask Codex to name the thread or run `adom-codex thread rename "Load tests"`. New nonce tabs retain their conversation identity through reloads. [Behavior, compatibility and activation](docs/THREAD-NAMES.md).
adom_codex.py+21
@@ -83,6 +83,27 @@ class Handler(SimpleHTTPRequestHandler):   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
docs/THREAD-NAMES.mdadded+87
@@ -0,0 +1,87 @@+# Codex thread names in Adom++Codex owns the conversation name. Adom displays it through VS Code's native+`WebviewPanel.title`, so the tab strip, Ctrl+Tab and Open Editors use the same+editor model. No DOM title replacement is required for managed Codex panels.++## Automatic and explicit names++Codex generates a short title after the first prompt. Depending on the engine,+that title lives in `threads.title`, while an explicit rename may be stored in+`threads.name`. Explicit names take precedence. The integration never substitutes+a huge raw first prompt while automatic naming is pending.++When the user asks to name this thread, execute:++```bash+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.+`--native-only` is the internal nonrecursive path used by Hydrogen. Output clearly+separates native persistence from visible-tab verification.++`adom-codex thread list` is read-only and supports current and older native stores.++## Panel identity and restore++New panels begin without a conversation UUID. A CSP-preserving bootstrap observes+the current composer's actual UUID and binds only that panel. A fresh nonce grants+only the injected bootstrap permission; the existing script sources and all other+security-policy directives remain intact.++Adom-created tabs have unique nonce resources. Their UUID bindings persist in the+extension's own global state. Restored nonce tabs use the saved `/local/<UUID>`+route so they reopen the actual conversation, not an empty chat carrying an old+name. A reusable bare `/new` never inherits an old conversation's identity.++The native name is read on open and updated by native name notifications. A single+shared, event-driven metadata watcher handles renames from a different app-server+or a user-selected native engine. It reads only names for open panels, at most once+per second during native-store changes; it never reads transcripts or calls a+model. Confirmed cross-process changes are mirrored to that panel's Codex UI.++Late reads and vendor preview assignments cannot overwrite a newer confirmed name.+Subscriptions and watchers are removed when panels close. If an unknown upstream+startup shape cannot be identified safely, the original renderer is retained.+Both older method-based and current function-based Codex HTML builders are supported.++## Related owners++The paired adom-vscode change consumes the native-name list in its Codex Sessions+view and `/codex/sessions`, retaining the legacy fallback for older/absent packages.+The paired Hydrogen change forwards rename to the native command, requires readback+before success, clears its competing alias only on success, and reads native names+in History. Those components have separate release/deployment states.++Existing Hydrogen-only aliases are preserved until the user explicitly renames+through the native path. They are not silently migrated over a potentially newer+native name. In the updated Hydrogen path, a confirmed rename clears the alias.++## Validation and activation++On 2026-11-15 the integration was tested in an isolated code-server 4.137.0 / VS Code+1.137.0 editor with Codex 26.1111.21308 and a real headless Chromium renderer:++- Native `window.tabGroups` labels and the actual Ctrl+Tab picker showed the saved+  conversation names, without a DOM/CSS override.+- A first prompt received Codex's automatic short title on the native editor tab.+- A rename made by an independent backend updated the open panel's native label.+- An editor reload preserved names and reopened the nonce panel's actual UUID.+- Existing managed fragments upgraded and uninstalled without replacing user edits.++Focused tests cover current/legacy schemas, identity isolation, numeric DB versions,+archive handling, native readback, generated titles, cross-process store changes,+CSP handling, stale replies, late previews, nonce restoration and disposal.++The existing backend reconnection fixture fails identically on unmodified 0.1.38+and this source (expected `turn is running`, received `sent 1000 (OK); no close+frame received`). `runtime.py` is unchanged. A full Hydrogen Rust build was not+available in the test workspace; that companion PR remains separately validated.++Installing stages renderer changes for the next extension-host load. Existing+panels require an editor reload. Do not interrupt active conversations just to+activate it. Preserve a custom CLI and the user's selected engine. Already-running+AI conversations do not automatically reload their instruction catalogs.
install.py+1
@@ -20,6 +20,7 @@ a='<!-- adom/codex:begin -->';b='<!-- adom/codex:end -->' 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:
package.json+1−1
@@ -4,7 +4,7 @@   "type": "app",   "title": "Codex",   "brief": "Codex in Adom Hydrogen: ecosystem setup, dock dashboard and live engineering demos.",-  "version": "0.1.38",+  "version": "0.1.39",   "description": "Codex in Adom Hydrogen with reusable CAD routing, electrical review, copper-ablation and narrated video skills, plus verified KiCad and Fusion demo progressions.",   "org": "adom",   "needs_sudo": false,
runtime/manage.py+19−2
@@ -105,7 +105,9 @@ class Integration:         if not main.is_relative_to(extension.resolve()): raise ValueError('Extension entry point escapes directory')         text = main.read_text()         # Match the semantic call site and capture minifier-generated names.-        pattern = r'(?P<w>[\w$]+)\.html=await this\.getWebviewContent\((?P=w)\),(?P<g>[\w$]+)\.start\(\)(?=\}onPanelReady\()'+        pattern = (r'(?P<w>[\w$]+)\.html=(?P<content>await (?:this\.getWebviewContent\((?P=w)\)'+                   r'|[\w$]+\(this\.extensionUri,(?P=w),this\.webviewMetaTags\((?P=w)\)\)))'+                   r',(?P<g>[\w$]+)\.start\(\)(?=\}onPanelReady\()')         matches = list(re.finditer(pattern, text))         if JS_BEGIN not in text:             if len(matches) != 1:@@ -117,7 +119,7 @@ class Integration:             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=await require({json.dumps(str(self.directory / "thread-names.cjs"))}).prepareForProvider({m["content"]},this),' + 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')@@ -126,6 +128,21 @@ class Integration:             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 '.prepareForProvider(' not in old:+                start = re.match(r'([\w$]+)\.html=(await (?:this\.getWebviewContent\(\1\)|[\w$]+\(this\.extensionUri,\1,this\.webviewMetaTags\(\1\)\))),', old)+                if not start: raise ValueError('Managed renderer assignment changed')+                w = start[1]+                replacement = (f'{w}.html=await require({json.dumps(str(self.directory / "thread-names.cjs"))}).prepareForProvider({start[2]},this),' + 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'):
runtime/name-store.cjsadded+48
@@ -0,0 +1,48 @@+'use strict';+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const {execFile} = require('node:child_process');++// More than one Codex backend may use the same home (including a user-selected+// native engine). Native notifications do not cross those processes. Watch only+// store changes, then read names for OPEN panels, never transcripts or model output.+const listeners = new Set();+let watcher, timer, busy = false, again = false, lastRead = 0;+function schedule() {+  if (!listeners.size || timer) return;+  if (busy) {again = true; return;}+  timer = setTimeout(read, Math.max(100, 1000 - (Date.now() - lastRead)));+  timer.unref?.();+}+function read() {+  timer = undefined;+  const ids = [...new Set([...listeners].map(item => item.id()).filter(Boolean))];+  if (!ids.length) return;+  busy = true; lastRead = Date.now();+  execFile('python3', [path.join(__dirname, 'thread_names.py'), JSON.stringify(ids)],+    {timeout: 4000, maxBuffer: 256 * 1024}, (error, stdout) => {+      busy = false;+      if (!error) {+        try {const names = JSON.parse(stdout); for (const item of listeners) item.changed(names[item.id()]);}+        catch (_) { /* a locked/changed store must never break the editor */ }+      }+      if (again) {again = false; schedule();}+    });+}+exports.subscribe = function (id, changed) {+  const item = {id, changed}; listeners.add(item);+  if (!watcher) {+    try {+      watcher = fs.watch(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'), (_event, file) => {+        if (/^state_\d+\.sqlite(?:-wal)?$/.test(String(file))) schedule();+      });+      watcher.unref?.(); watcher.on('error', () => {});+    } catch (_) { /* native notifications remain available */ }+  }+  schedule();+  return {refresh: schedule, dispose() {+    listeners.delete(item);+    if (!listeners.size) {watcher?.close(); watcher = undefined; clearTimeout(timer); timer = undefined; again = false;}+  }};+};
runtime/thread-names.cjsadded+159
@@ -0,0 +1,159 @@+'use strict';+const {randomUUID, createHash, randomBytes} = require('node:crypto');+const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;+function identityKeyFor(route) {+  return /\/extension\/panel\/new\?.+/.test(route)+    ? 'adom.codex.panel-identity.' + createHash('sha256').update(route).digest('hex') : null;+}++// 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]') || document.querySelector('[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 existing = /<script\b[^>]*\bnonce=["']([^"']+)["']/.exec(html);+  let nonce = existing?.[1];+  if (!nonce) {+    // Newer Codex uses only external scripts. Grant only this one fresh nonce,+    // keeping every existing CSP directive/source unchanged (never unsafe-inline).+    const meta = /<meta\b[^>]*http-equiv=["']Content-Security-Policy["'][^>]*>/i.exec(html);+    const content = meta && /\bcontent=(["'])(.*?)\1/i.exec(meta[0]);+    if (!content || !/(^|;)\s*script-src\s/.test(content[2])) return html;+    nonce = randomBytes(16).toString('base64');+    const policy = content[2].replace(/(^|;)(\s*script-src\s)/, `$1$2'nonce-${nonce}' `);+    html = html.replace(meta[0], meta[0].replace(content[0], `content=${content[1]}${policy}${content[1]}`));+  }+  const script = `<script nonce="${nonce}">/* adom-thread-identity */(${identityBridge.toString()})();</script>`;+  return html.replace(/<script\b/, script + '<script');+};++exports.prepareForProvider = async function (html, provider) {+  const meta = /<meta\b[^>]*name=["']initial-route["'][^>]*>/i.exec(html);+  const content = meta && /\bcontent=(["'])(.*?)\1/i.exec(meta[0]);+  if (content) {+    const route = content[2].replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');+    const key = identityKeyFor(route);+    if (key && provider.globalState?.get) {+      try {+        let timer;+        let id;+        try {+          id = await Promise.race([provider.globalState.get(key), new Promise(resolve => {+            timer = setTimeout(() => resolve(undefined), 2000); timer.unref?.();+          })]);+        } finally {clearTimeout(timer);}+        if (UUID.test(id || '')) html = html.replace(meta[0], meta[0].replace(content[0], `content="/local/${id}"`));+      } catch (_) { /* leave an unidentifiable new panel intact */ }+    }+  }+  return exports.prepare(html);+};++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 = identityKeyFor(route);+  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 store = require('./name-store.cjs').subscribe(() => current, name => {+    if (typeof name === 'string' && name.trim() && name !== desired) {+      ++generation; apply(current, name);+      // Mirror the confirmed native-store change into this panel's Codex UI too;+      // another backend's notification never reaches this extension connection.+      provider.sendMessageToPanel?.(panel, {type: 'mcp-notification', hostId: 'local',+        method: 'thread/name/updated', params: {threadId: current, threadName: 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;+        // A second app-server may retain an old in-memory name. Once a store+        // change confirmed a newer one, a focus-time read must not revert it.+        if (thread?.id === current && (!desired || thread.name === desired)) apply(current, thread.name);+        store.refresh();+      }+    },+    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) {+      const previous = current;+      current = message.threadId; desired = undefined;+      if (previous) panel.title = 'Codex';+      if (identityKey && provider.globalState?.update) {+        const id = current;+        Promise.resolve().then(() => provider.globalState.update(identityKey, id)).catch(() => {});+      }+      refresh();+      store.refresh();+    }+  });+  const changed = panel.onDidChangeViewState(() => { if (panel.visible) refresh(); });+  let dispose;+  dispose = onDispose(() => {+    disposed = true; store.dispose(); 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(() => {});+  }+};
runtime/thread_names.pyadded+93
@@ -0,0 +1,93 @@+"""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 native_names(thread_ids, home=None):+    """Small metadata-only query for open panels, including old/archived conversations."""+    ids = [value for value in thread_ids if isinstance(value, str) and UUID.fullmatch(value)]+    if not ids: return {}+    home = Path(home or os.environ.get('CODEX_HOME', Path.home() / '.codex'))+    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:+        columns = {row[1] for row in db.execute('pragma table_info(threads)')}+        name_column = 'name' if 'name' in columns else 'NULL'+        title_column = 'title' if 'title' in columns else 'NULL'+        rows = db.execute(f'select id,{name_column},{title_column} from threads where id in (' + ','.join('?' for _ in ids) + ')', ids)+        result = {}+        for sid, name, title in rows:+            if isinstance(name, str) and name.strip(): result[sid] = name+            # Current Codex writes automatic titles into `title`, explicit renames+            # into `name`. Do not promote a huge raw prompt while naming is pending.+            elif isinstance(title, str) and title.strip() and len(title.strip()) <= 80 and '\n' not in title:+                result[sid] = title.strip()+        return result+++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}+++if __name__ == '__main__':+    import sys+    print(json.dumps(native_names(json.loads(sys.argv[1]))))
runtime/webview.cjs+1
@@ -109,6 +109,7 @@ exports.watchRenderer = function (webview, role, provider, guard, onDispose) {   // 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) {
skills/codex-adom/SKILL.md+17
@@ -30,6 +30,23 @@ An explicit path planner is not automatically a general autorouter. Label copied  `/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
tests/test_integration.py+31
@@ -82,6 +82,37 @@ class PackageLifecycle(unittest.TestCase):             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('.prepareForProvider(await this.getWebviewContent(a),this)', main.read_text())+            manager.uninstall(isolated=True)+            self.assertEqual(main.read_text(), original)++    def test_current_vendor_renderer_function_signature(self):+        with tempfile.TemporaryDirectory() as tmp:+            manager = Integration(Path(tmp))+            extension, _ = self.extension(Path(tmp))+            main = extension / 'out/extension.js'+            original = 'class Provider{async initializeWebview(a,b,c,d){a.html=await BuildPage(this.extensionUri,a,this.webviewMetaTags(a)),z.start()}onPanelReady(){}}'+            main.write_text(original)+            manager.install(isolated=True)+            self.assertIn('.prepareForProvider(await BuildPage(this.extensionUri,a,this.webviewMetaTags(a)),this)', 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)
tests/test_name_store.cjsadded+36
@@ -0,0 +1,36 @@+'use strict';+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const {execFileSync} = require('node:child_process');+const home = fs.mkdtempSync(path.join(os.tmpdir(), 'adom-name-store-'));+const id = '12345678-1234-1234-1234-123456789abc';+process.env.CODEX_HOME = home;+function write(name, create = false) {+  execFileSync('python3', ['-c', `import sqlite3,sys+with sqlite3.connect(sys.argv[1]) as db:+ if sys.argv[4]=='yes':+  db.execute('create table threads(id,name)')+  db.execute('insert into threads values(?,?)',(sys.argv[2],sys.argv[3]))+ else: db.execute('update threads set name=? where id=?',(sys.argv[3],sys.argv[2]))`,+  path.join(home, 'state_5.sqlite'), id, name, create ? 'yes' : 'no']);+}+(async () => {+  write('Alpha', true);+  const {subscribe} = require('../runtime/name-store.cjs');+  let seen = [];+  const subscription = subscribe(() => id, name => seen.push(name));+  async function until(name) {+    const deadline = Date.now() + 6000;+    while (!seen.includes(name) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 50));+    assert.ok(seen.includes(name), 'did not observe ' + name);+  }+  try {+    await until('Alpha');+    write('Beta'); // An independent process writes metadata, with no RPC notification.+    await until('Beta');+    assert.equal(seen.at(-1), 'Beta');+  } finally {subscription.dispose(); fs.rmSync(home, {recursive: true, force: true});}+  console.log('Passed: independent-process native-name writes update open-panel subscribers.');+})().catch(error => {console.error(error); process.exitCode = 1;});
tests/test_thread_names.cjsadded+68
@@ -0,0 +1,68 @@+'use strict';+const assert = require('node:assert/strict');+const {prepare, prepareForProvider, 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>');+const modern = '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'self\' https://*.vscode-cdn.net; style-src \'self\';"><script type="module" src="app.js"></script>';+const prepared = prepare(modern);+assert.ok(prepared.includes('adom-thread-identity'));+assert.ok(/script-src 'nonce-[^']+' 'self' https:\/\/\*\.vscode-cdn.net;/.test(prepared));+assert.ok(prepared.includes("style-src 'self';"));+assert.ok(!prepared.includes('unsafe-inline'));+assert.equal(prepare(prepared), prepared);+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 restoredHTML = await prepareForProvider('<meta name="initial-route" content="'+route+'">'+html, {globalState: state});+  assert.ok(restoredHTML.includes('content="/local/'+a+'"'));+  const freshHTML = await prepareForProvider('<meta name="initial-route" content="/extension/panel/new?nonce=other">'+html, {globalState: state});+  assert.ok(freshHTML.includes('content="/extension/panel/new?nonce=other"'));+  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;});
tests/test_thread_names.pyadded+79
@@ -0,0 +1,79 @@+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, native_names+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)++    def test_native_name_query_includes_only_requested_ids_and_never_raw_preview(self):+        with tempfile.TemporaryDirectory() as directory:+            with sqlite3.connect(str(Path(directory) / 'state_5.sqlite')) as db:+                db.execute('create table threads(id,name,title)')+                db.execute('insert into threads values(?,?,?)', (SID, 'Saved name', 'Long first prompt'))+                db.execute('insert into threads values(?,?,?)', ('87654321-1234-1234-1234-123456789abc', None, 'Do not show this raw preview ' * 8))+            self.assertEqual(native_names([SID, '87654321-1234-1234-1234-123456789abc', 'bad'], directory), {SID: 'Saved name'})++    def test_current_engine_automatic_title_without_explicit_name(self):+        with tempfile.TemporaryDirectory() as directory:+            with sqlite3.connect(str(Path(directory) / 'state_5.sqlite')) as db:+                db.execute('create table threads(id,name,title)')+                db.execute('insert into threads values(?,?,?)', (SID, None, 'Explain voltage versus current'))+            self.assertEqual(native_names([SID], directory), {SID: 'Explain voltage versus current'})+++if __name__ == '__main__': unittest.main()