← Commit history

Merge PR #496: Preserve existing Codex nonce tabs through their first activation reload (preserve-existing-nonce-panel -> main) merge

John Lauer ·6728deea46 · ·parents af979bd, 4b85a6a

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

10 files changed +152−7
README.md+1−1
@@ -134,6 +134,6 @@ Version 0.1.35 gives OpenAI's newest models to fresh installs too. The newest-en  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)+## Native thread names (0.1.40)  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+5−1
@@ -86,13 +86,17 @@ 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+  from panel_bindings import bind_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)+  b=sub.add_parser('bind');b.add_argument('--resource',required=True);b.add_argument('--id')   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':result=rename_thread(a.name,a.id)+   elif a.action=='bind':result=bind_thread(a.resource,a.id)+   else:result={'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():
docs/THREAD-NAMES.md+12−1
@@ -36,10 +36,21 @@ only the injected bootstrap permission; the existing script sources and all othe 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>`+extension's own global state and an atomic per-resource identity record. 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. +For an existing nonce tab opened before this integration was loaded, bind its+verified resource and native conversation before the first activation reload:++```bash+adom-codex thread bind --id <UUID> --resource '<exact openai-codex nonce URI>'+```++This preserves the old panel's actual conversation without needing a live patched+renderer to seed its state. The command validates the native conversation and+supports the URI encoding used by VS Code. Never guess another tab's binding.+ 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
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.39",+  "version": "0.1.40",   "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/panel-bindings.cjsadded+32
@@ -0,0 +1,32 @@+'use strict';+const fs = require('node:fs'), path = require('node:path'), os = require('node:os');+const {createHash, randomUUID} = require('node:crypto');+const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;+function normalized(route) {+  const match = /^\/extension\/panel\/new\?(.+)$/.exec(route);+  if (!match) return null;+  try {const query = decodeURIComponent(match[1]); return /^(?:adom|nonce)=[A-Za-z0-9_.:-]{1,128}$/.test(query) ? '/extension/panel/new?' + query : null;}+  catch (_) {return null;}+}+function location(route) {+  const canonical = normalized(route); if (!canonical) return null;+  const home = fs.realpathSync(process.env.CODEX_HOME || path.join(os.homedir(), '.codex'));+  const digest = value => createHash('sha256').update(value).digest('hex');+  const base = process.env.ADOM_CODEX_BINDINGS_DIR || path.join(os.homedir(), '.local/state/adom/codex-integration/panel-bindings');+  return {canonical, file: path.join(base, digest(home), digest(canonical) + '.json')};+}+exports.read = route => {+  try {const target = location(route); if (!target) return; const record = JSON.parse(fs.readFileSync(target.file, 'utf8')); if (record.route === target.canonical && UUID.test(record.threadId || '')) return record.threadId;}+  catch (_) { /* absent bindings retain the normal new-panel behavior */ }+};+exports.save = (route, threadId) => {+  let temporary;+  try {+    if (!UUID.test(threadId || '')) return;+    const target = location(route); if (!target) return;+    fs.mkdirSync(path.dirname(target.file), {recursive: true, mode: 0o700});+    temporary = target.file + '.' + randomUUID() + '.tmp';+    fs.writeFileSync(temporary, JSON.stringify({route: target.canonical, threadId}), {mode: 0o600});+    fs.renameSync(temporary, target.file);+  } catch (_) {if (temporary) try {fs.unlinkSync(temporary);} catch (_) {} }+};
runtime/panel_bindings.pyadded+37
@@ -0,0 +1,37 @@+"""Preserve a verified conversation behind an existing Adom nonce editor resource."""+import hashlib+import json+import os+from pathlib import Path+import re+import sqlite3+from urllib.parse import urlsplit, unquote, quote+import uuid+++def bind_thread(resource, thread_id=None):+    from thread_names import UUID+    thread_id = thread_id or os.environ.get('CODEX_THREAD_ID', '')+    if not UUID.fullmatch(thread_id): raise ValueError('A conversation UUID is required')+    uri = urlsplit(resource)+    query = unquote(uri.query)+    if uri.scheme != 'openai-codex' or uri.netloc != 'route' or uri.path != '/extension/panel/new' or not re.fullmatch(r'(?:adom|nonce)=[A-Za-z0-9_.:-]{1,128}', query):+        raise ValueError('Pass the exact existing Adom nonce editor resource; bare /new cannot be bound safely')+    route = uri.path + '?' + query+    home = Path(os.environ.get('CODEX_HOME', Path.home() / '.codex')).resolve()+    dbs = sorted(home.glob('state_*.sqlite'), key=lambda p: int(re.search(r'state_(\d+)', p.name)[1]))+    if not dbs: raise RuntimeError('Codex has no native conversation store')+    with sqlite3.connect('file:' + quote(str(dbs[-1])) + '?mode=ro', uri=True, timeout=1) as db:+        if not db.execute('select 1 from threads where id=?', (thread_id,)).fetchone():+            raise ValueError('That conversation is not present in this Codex home')+    base = Path(os.environ.get('ADOM_CODEX_BINDINGS_DIR', Path.home() / '.local/state/adom/codex-integration/panel-bindings'))+    directory = base / hashlib.sha256(str(home).encode()).hexdigest()+    directory.mkdir(parents=True, exist_ok=True, mode=0o700)+    file = directory / (hashlib.sha256(route.encode()).hexdigest() + '.json')+    temporary = file.with_name(file.name + '.' + uuid.uuid4().hex + '.tmp')+    try:+        temporary.write_text(json.dumps({'route': route, 'threadId': thread_id}) + '\n')+        temporary.chmod(0o600)+        temporary.replace(file)+    finally: temporary.unlink(missing_ok=True)+    return {'ok': True, 'id': thread_id, 'resource': resource, 'bound': True}
runtime/thread-names.cjs+6−2
@@ -1,5 +1,6 @@ 'use strict'; const {randomUUID, createHash, randomBytes} = require('node:crypto');+const bindings = require('./panel-bindings.cjs'); 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)@@ -48,7 +49,9 @@ exports.prepareForProvider = async function (html, provider) {   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) {+    const migrated = bindings.read(route);+    if (migrated) html = html.replace(meta[0], meta[0].replace(content[0], `content="/local/${migrated}"`));+    else if (key && provider.globalState?.get) {       try {         let timer;         let id;@@ -68,7 +71,7 @@ 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];+  let current = /\/local\/([0-9a-f-]{36})(?:[/?#]|$)/i.exec(route)?.[1] || bindings.read(route);   // 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.@@ -134,6 +137,7 @@ exports.watch = function (webview, panel, provider, onDispose) {       const previous = current;       current = message.threadId; desired = undefined;       if (previous) panel.title = 'Codex';+      bindings.save(route, current);       if (identityKey && provider.globalState?.update) {         const id = current;         Promise.resolve().then(() => provider.globalState.update(identityKey, id)).catch(() => {});
skills/codex-adom/SKILL.md+11
@@ -47,6 +47,17 @@ names without changing any conversation. A persisted name and a visibly updated 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. +Before reloading a workspace with an already-open pre-integration Codex nonce tab,+preserve its verified conversation identity:++```bash+adom-codex thread bind --id <conversation UUID> --resource '<exact openai-codex nonce URI>'+```++Match the exact tab resource and conversation first; never bind by an assumed active+tab or a stale tab index. The command verifies the native conversation exists and+saves only its URI-to-UUID association. It rejects reusable bare `/new` resources.+ ## Focused follow-ups  For Codex Desktop installation or first-run setup, read
tests/test_panel_bindings.pyadded+40
@@ -0,0 +1,40 @@+import json+import os+from pathlib import Path+import sqlite3+import subprocess+import sys+import tempfile+import unittest+from unittest.mock import patch++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / 'runtime'))+from panel_bindings import bind_thread+SID = '12345678-1234-1234-1234-123456789abc'+++class Bindings(unittest.TestCase):+    def test_existing_nonce_binding_roundtrips_between_cli_and_renderer(self):+        with tempfile.TemporaryDirectory() as directory:+            home = Path(directory)+            with sqlite3.connect(str(home / 'state_5.sqlite')) as db:+                db.execute('create table threads(id)')+                db.execute('insert into threads values(?)', (SID,))+            env = dict(os.environ, CODEX_HOME=str(home), ADOM_CODEX_BINDINGS_DIR=str(home / 'bindings'))+            with patch.dict(os.environ, env):+                result = bind_thread('openai-codex://route/extension/panel/new?adom%3D1234567', SID)+            self.assertTrue(result['bound'])+            script = "console.log(require(process.argv[1]).read('/extension/panel/new?adom=1234567'))"+            result = subprocess.run(['node', '-e', script, str(ROOT / 'runtime/panel-bindings.cjs')], env=env, capture_output=True, text=True, check=True)+            self.assertEqual(result.stdout.strip(), SID)+            records = list((home / 'bindings').glob('*/*.json'))+            self.assertEqual(len(records), 1)+            self.assertEqual(records[0].stat().st_mode & 0o777, 0o600)++    def test_reusable_and_unrelated_resources_are_refused(self):+        for resource in ['openai-codex://route/extension/panel/new', 'https://example.com/extension/panel/new?adom=123', 'openai-codex://route/local/'+SID]:+            with self.assertRaises(ValueError): bind_thread(resource, SID)+++if __name__ == '__main__': unittest.main()
tests/test_thread_names.cjs+7−1
@@ -1,5 +1,8 @@ 'use strict'; const assert = require('node:assert/strict');+const fs = require('node:fs'), os = require('node:os'), path = require('node:path');+const testBindings = fs.mkdtempSync(path.join(os.tmpdir(), 'adom-panel-bindings-'));+process.env.ADOM_CODEX_BINDINGS_DIR = testBindings; const {prepare, prepareForProvider, watch} = require('../runtime/thread-names.cjs'); const a = '12345678-1234-1234-1234-123456789abc'; const b = '87654321-1234-1234-1234-123456789abc';@@ -57,6 +60,9 @@ console.log('Passed: restored/new panel identity, rename events, stale reads, is   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"'));+  require('../runtime/panel-bindings.cjs').save('/extension/panel/new?adom=legacy-123', b);+  const migratedHTML = await prepareForProvider('<meta name="initial-route" content="/extension/panel/new?adom%3Dlegacy-123">'+html, {});+  assert.ok(migratedHTML.includes('content="/local/'+b+'"'));   const generic = panel('/extension/panel/new', state);   await new Promise(resolve => setImmediate(resolve));   assert.equal(generic.calls.length, 0);@@ -65,4 +71,4 @@ console.log('Passed: restored/new panel identity, rename events, stale reads, is   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;});+})().catch(error => {console.error(error); process.exitCode = 1;}).finally(() => fs.rmSync(testBindings, {recursive:true, force:true}));