main
John Lauer Preserve existing Codex nonce panel identity before activation 4b85a6a
'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)
    ? '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);
    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;
        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] || 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.
  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';
      bindings.save(route, current);
      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(() => {});
  }
};