// 隔离执行公开 GitCode 正文组件;只读本地脚本,不访问用户会话或修改线上页面。
// 用法:node scripts/verify_gitcode_body_lifecycle.cjs /tmp/DO8DXMXQ.js
const fs = require('node:fs');
const vm = require('node:vm');
const assert = require('node:assert/strict');
const { createHash } = require('node:crypto');

const bundlePath = process.argv[2];
if (!bundlePath) throw new Error('请传入公开 GitCode 正文脚本的本地路径');
const bundle = fs.readFileSync(bundlePath, 'utf8');
function extract(start, end) {
  const begin = bundle.indexOf(start);
  const finish = bundle.indexOf(end, begin);
  assert.ok(begin >= 0 && finish > begin, `公开脚本结构已变化:${start}`);
  return bundle.slice(begin, finish);
}
function replaceOnce(source, before, after) {
  assert.equal(source.split(before).length, 2, `预期恰好一个修改点:${before}`);
  return source.replace(before, after);
}
const parentSource = extract('Ai=fe(', ',Mi=Object.assign').slice(3);
const childSource = extract('ga=fe(', ',va=Object.assign').slice(3);
const streamSource = extract('const Lt=', 'function jt(');
const statusNames = ['启动中', '运行中', '未分配'];

function candidateParent() {
  const source = replaceOnce(parentSource, 'e(p)===e(le).Starting?',
    'e(p)===e(le).Starting&&e(Re)?');
  return replaceOnce(source, 'const Me=G.status??le.Stopped;',
    'const Me=[le.Starting,le.Running,le.Stopped].includes(G.status)?G.status:p.value;');
}

function makeContext(extra = {}) {
  const hooks = [];
  const node = (type, props, children) => ({ type, props, children });
  const sandbox = {
    console, Date, Math, Object, String, Number, Map, Set, Array, Promise, JSON, Error,
    AbortController, TextDecoder, TextEncoder, Uint8Array,
    document: { hidden: true, addEventListener() {}, removeEventListener() {} },
    window: undefined, navigator: undefined,
    fe: options => options,
    v: value => ({ value }), V: getter => ({ get value() { return getter(); } }),
    ye: () => ({ atomT: key => key, locale: { value: 'zh' } }),
    cn: () => ({ isLogin: true }), dn: () => ({ theme: { value: 'black' } }),
    rt: () => ({ add() {} }), me() {}, Oe() {}, Ve() {}, Ft() {}, Pt: value => value,
    tn: callback => hooks.push(callback),
    e: value => value && typeof value === 'object' && 'value' in value ? value.value : value,
    c() {}, y: node, t: node, ce: node, $: node, N: () => null,
    l: String, He: value => value, ee: callback => callback,
    le: { Starting: 0, Running: 1, Stopped: 2 },
    _a: 'ChatShell', Gt: 'StoppedPanel', Ee: 'Fragment',
    ma: () => [{ title: 'assistant' }], ua: () => 'new conversation',
    Ze: '/model-agent/api/v1', Jo: 'MessageList', da: 'Composer',
    lt: (items, callback) => items.map(callback),
    setTimeout: () => 1, clearTimeout() {}, clearInterval() {},
    Dt: () => 1, Ut: value => value,
    ...extra,
  };
  // 未展开的图标、样式和弹窗只作为虚拟节点标识;不执行其副作用。
  const context = new Proxy(sandbox, {
    get(target, key) { return key in target ? target[key] : String(key); },
  });
  sandbox.globalThis = context;
  vm.createContext(context);
  return { context, hooks };
}
function contains(tree, type) {
  if (!tree || typeof tree !== 'object') return false;
  if (Array.isArray(tree)) return tree.some(item => contains(item, type));
  return tree.type === type || contains(tree.children, type);
}
const tick = () => new Promise(resolve => setImmediate(resolve));

async function probe(candidate) {
  let detail;
  let parentCode = parentSource;
  let childCode = childSource;
  if (candidate) {
    // 仅在内存验证候选修改,不生成或注入替换用的线上脚本。
    parentCode = candidateParent();
    childCode = replaceOnce(childCode, 's.agentStatus===e(le).Stopped?',
      's.agentStatus===e(le).Stopped&&!e(We)&&!(e(Ce)?.messages?.length)?');
  }
  parentCode = replaceOnce(parentCode, 'return Oe(()=>{document.addEventListener("fullscreenchange",Xe)',
    'globalThis.probe={poll:Ke};return Oe(()=>{document.addEventListener("fullscreenchange",Xe)');
  const parent = makeContext({ Te: async () => ({ data: detail }) });
  vm.runInContext(`var Parent=${parentCode};`, parent.context);
  const parentRender = parent.context.Parent.setup({ sectionId: 'test', className: '' });

  let config;
  const child = makeContext({ In: options => {
    config = options;
    return { generating: { value: true }, generatingSessionIdSet: { value: new Set(['existing']) },
      awaitingConfirmation: { value: false }, sendMessage() {}, sendConfirmation() {}, stopGeneration() {} };
  } });
  vm.runInContext(`var Chat=${childCode};`, child.context);
  const props = { agentStatus: 1, containerType: 'cpu', moAgentId: 'same-container' };
  const childRender = child.context.Chat.setup(props);
  config.activeSessionId.value = 'existing';

  let signal;
  let pendingRead;
  const stream = makeContext({ fetch: async (_url, options) => {
    signal = options.signal;
    return { ok: true, body: { getReader: () => ({ read: () => new Promise((resolve, reject) => {
      pendingRead = resolve;
      signal.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })), { once: true });
    }) }) } };
  } });
  vm.runInContext(streamSource, stream.context);
  const service = stream.context.In({
    ...config, agentAppendPrompt: { value: '' }, agentName: { value: 'assistant' },
  });
  const sending = service.sendMessage('/verify Qwen3-8B A2');
  await tick();
  const send = async content => {
    pendingRead({ done: false, value: new TextEncoder().encode(
      `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n`,
    ) });
    await tick();
  };
  await send('正在执行 /verify...\n\n第一段真实输出');
  const stages = [];
  let ownerMounted = true;
  for (const status of [1, 2, 0, 1]) {
    detail = { status, version: '0.2.1', mo_fix_agent_id: 'same-container' };
    await parent.context.probe.poll();
    props.agentStatus = status;
    const mounted = contains(parentRender({}, []), 'ChatShell');
    if (ownerMounted && !mounted) {
      for (const dispose of stream.hooks) dispose();
      ownerMounted = false;
      await tick();
    }
    stages.push({ status: statusNames[status], chatMounted: mounted,
      messagesVisible: ownerMounted && mounted && contains(childRender({}, []), 'MessageList'),
      streamAborted: signal.aborted });
    if (candidate) await send(`\n${statusNames[status]}期间继续接收的真实分片`);
  }
  if (candidate) {
    assert.ok(stages.every(stage => stage.messagesVisible && !stage.streamAborted));
    pendingRead({ done: true });
  } else {
    assert.deepEqual(stages.map(stage => stage.messagesVisible), [true, false, false, false]);
    assert.equal(signal.aborted, true);
  }
  await sending;
  const messages = config.messages.value.existing;
  assert.ok(messages.at(-1).content.startsWith('正在执行 /verify...\n\n第一段真实输出'));
  if (candidate) {
    assert.ok(messages.at(-1).content.includes('启动中期间继续接收的真实分片'));
    assert.equal(messages.at(-1).status, 'done');
  }
  return stages;
}

async function probeMissingStatus(candidate) {
  let detail;
  const source = replaceOnce(candidate ? candidateParent() : parentSource,
    'return Oe(()=>{document.addEventListener("fullscreenchange",Xe)',
    'globalThis.probe={poll:Ke,status:p};return Oe(()=>{document.addEventListener("fullscreenchange",Xe)');
  const parent = makeContext({ Te: async () => ({ data: detail }) });
  vm.runInContext(`var Parent=${source};`, parent.context);
  parent.context.Parent.setup({ sectionId: 'test', className: '' });
  detail = { status: 1, version: '0.2.1', mo_fix_agent_id: 'same-container' };
  await parent.context.probe.poll();
  assert.equal(parent.context.probe.status.value, 1);
  detail = { version: '0.2.1', mo_fix_agent_id: 'same-container' };
  await parent.context.probe.poll();
  assert.equal(parent.context.probe.status.value, candidate ? 1 : 2);
  return statusNames[parent.context.probe.status.value];
}

async function probeDraftUnmount() {
  let config;
  let service;
  let signal;
  let pendingRead;
  const child = makeContext({
    Te: async () => ({ data: { conversation_id: 'persisted-session' } }),
    fetch: async (_url, options) => {
      signal = options.signal;
      return { ok: true, body: { getReader: () => ({ read: () => new Promise((resolve, reject) => {
        pendingRead = resolve;
        signal.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })), { once: true });
      }) }) } };
    },
  });
  vm.runInContext(streamSource, child.context);
  const realIn = child.context.In;
  child.context.In = options => {
    config = options;
    service = realIn(options);
    return service;
  };
  vm.runInContext(`var Chat=${childSource};`, child.context);
  const props = { agentStatus: 1, containerType: 'cpu', moAgentId: 'same-container' };
  child.context.Chat.setup(props);
  assert.ok(config.activeSessionId.value.startsWith('draft_'));
  const sending = service.sendMessage('/verify Qwen3-8B A2');
  await tick();
  assert.equal(config.activeSessionId.value, 'persisted-session');
  const send = async content => {
    pendingRead({ done: false, value: new TextEncoder().encode(
      `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n`,
    ) });
    await tick();
  };
  await send('正在执行 /verify...\n\n第一段真实输出');
  const oldOwner = config;
  const beforeUnmount = oldOwner.messages.value['persisted-session'].at(-1).content;
  for (const dispose of child.hooks) dispose();
  await tick();
  // draft 升级后只删掉旧 ID,未把控制器登记到新 ID:卸载后请求仍在旧组件内运行。
  assert.equal(signal.aborted, false);
  child.context.Chat.setup(props);
  const newOwner = config;
  newOwner.activeSessionId.value = 'persisted-session';
  await send('\n第二段仍被旧组件接收');
  assert.ok(oldOwner.messages.value['persisted-session'].at(-1).content.includes('第二段仍被旧组件接收'));
  assert.equal(newOwner.messages.value['persisted-session'], undefined);
  pendingRead({ done: true });
  await sending;
  assert.equal(oldOwner.messages.value['persisted-session'].at(-1).status, 'done');
  return { containerIdChanged: false, beforeUnmount, streamContinuedAfterUnmount: !signal.aborted,
    newOwnerReceivedOutput: Boolean(newOwner.messages.value['persisted-session']),
    finalStatusInOldOwner: oldOwner.messages.value['persisted-session'].at(-1).status };
}

(async () => {
  const original = await probe(false);
  const candidate = await probe(true);
  console.log(JSON.stringify({
    sourceSha256: createHash('sha256').update(bundle).digest('hex'),
    scope: '原始组件渲染及流读取;Vue、HTTP、容器状态为隔离替身,非线上验证',
    missingStatus: { original: await probeMissingStatus(false), candidate: await probeMissingStatus(true) },
    promotedDraftUnmount: await probeDraftUnmount(),
    original, candidate,
  }, null, 2));
})().catch(error => { console.error(error); process.exitCode = 1; });