/** 本地云函数契约回归;全部使用内存数据,不访问远程。 */ import { readFileSync } from 'node:fs'; import vm from 'node:vm'; import assert from 'node:assert/strict'; import { test } from 'node:test'; const scope = vm.createContext({}); vm.runInContext(readFileSync(new URL('../cloud/functions/fmodeagent-status.js', import.meta.url), 'utf8'), scope); const record = (id, fields) => ({ id, get: key => fields[key] }); const owner = { id: 'owner' }; const agent = (fields = {}) => record('a1', { user: owner, agentId: 'agent-node-app-a1', ...fields }); const binding = () => record('b1', { agentMxId: '@a1:fmode.cn', roomId: '!room', accessToken: 'never-return-this' }); const index = (status = 'ready') => ({ bindings: { 'owner:agent-node-app-a1': binding() }, jobs: { 'owner:a1': record('j1', { status }) }, }); test('真实心跳过期时,重命名改 updatedAt 不能把离线容器判在线', () => { const fields = { heartbeatAt: new Date(Date.now() - 86400000) }; const a = { ...record('a1', fields), updatedAt: new Date(), toJSON: () => ({ status: 'offline' }) }; const out = scope._agentJSON(a, {}); assert.ok(out.heartbeatAgeSec >= 86400); const projected = scope._withAppReadiness(agent({ channels: { matrixConfig: { channelState: 'connected' } } }), out, index()); assert.equal(projected.status, 'offline'); }); test('已完成交付与接入绑定独立于原始 offline;不泄漏绑定凭据', () => { const out = scope._withAppReadiness(agent(), { status: 'offline', heartbeatAgeSec: 10 }, index()); assert.equal(out.provisioned, true); assert.equal(out.matrixReady, true); assert.equal(out.channels.matrixConfig.userId, '@a1:fmode.cn'); assert.equal(out.status, 'offline'); // 只有绑定不能宣称实时在线 assert.equal(out.channels.matrixConfig.channelState, undefined); assert.equal(JSON.stringify(out).includes('never-return-this'), false); assert.equal(JSON.stringify(out).includes('!room'), false); }); test('有绑定、正在开通不等于已交付', () => { assert.equal(scope._withAppReadiness(agent(), {}, index('provisioning')).provisioned, false); }); test('其他用户的相同容器标识不能提供准入', () => { const out = scope._withAppReadiness(agent({ user: { id: 'other' } }), {}, index()); assert.equal(out.matrixReady, false); assert.equal(out.provisioned, false); }); test('初始 offline 只有真实 connected 上报及新鲜心跳才能投影 idle', () => { const a = agent({ channels: { matrixConfig: { channelState: 'connected' } } }); assert.equal(scope._withAppReadiness(a, { status: 'offline', heartbeatAgeSec: 30 }, index()).status, 'idle'); assert.equal(scope._withAppReadiness(a, { status: 'offline', heartbeatAgeSec: 5000 }, index()).status, 'offline'); assert.equal(scope._withAppReadiness(a, { status: 'stopped', heartbeatAgeSec: 30 }, index()).status, 'stopped'); }); test('没有新任务的历史接入兼容;只有空记录不能准入', () => { const emptyIndex = { bindings: {}, jobs: {} }; assert.equal(scope._withAppReadiness(agent({ channels: { matrix: true } }), {}, emptyIndex).provisioned, true); assert.equal(scope._withAppReadiness(agent(), {}, emptyIndex).provisioned, false); }); const provisionScope = vm.createContext({}); vm.runInContext(readFileSync(new URL('../cloud/functions/fmode-provisioning.js', import.meta.url), 'utf8'), provisionScope); test('阶段已完成后不再把该阶段旧 running 当作当前进度', () => { const steps = [ { stage: 'prepare', status: 'running' }, { stage: 'prepare', status: 'ok' }, { stage: 'copy', status: 'running' }, { stage: 'copy', status: 'ok' }, ]; assert.equal(provisionScope._currentStep(steps).status, 'ok'); assert.equal(provisionScope._currentStep(steps).stage, 'copy'); steps.push({ stage: 'configure', status: 'running' }); assert.equal(provisionScope._currentStep(steps).stage, 'configure'); }); test('延迟到达的 running 不能覆盖同次尝试已确认完成的阶段', () => { const steps = [{ stage: 'verify', status: 'ok' }, { stage: 'verify', status: 'running' }]; assert.equal(provisionScope._currentStep(steps).status, 'ok'); }); function probeFixture() { let sent = 0; let events = [{ event_id: '$probe', type: 'm.room.message', sender: '@owner:fmode.cn' }]; const fields = { attempts: 1 }; const job = { ...record('job-1', fields), set: (k, v) => { fields[k] = v; }, save: async () => {} }; const prov = { roomId: '!bound', userMxId: '@owner:fmode.cn', agentMxId: '@a1:fmode.cn', accessToken: 'fixture' }; provisionScope.fetch = async (url, init) => { if (init?.method === 'PUT') { sent++; assert.match(url, /fmode-ready-job-1-1$/); assert.equal(JSON.parse(init.body)['m.mentions'].user_ids[0], prov.agentMxId); return { ok: true, json: async () => ({ event_id: '$probe' }) }; } return { ok: true, json: async () => ({ chunk: events }) }; }; return { job, prov, sent: () => sent, events: value => { events = value; } }; } test('只有建号、房间和心跳,尚无真实回复不能通过收发核验;轮询不重复发探针', async () => { const f = probeFixture(); assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), false); assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), false); assert.equal(f.sent(), 1); }); test('目标 sender 的实际回复与对应结束反应才通过,历史消息及其他 sender 不算', async () => { const f = probeFixture(); await provisionScope._probeRoundtrip(f.job, f.prov); const reply = { event_id: '$reply', type: 'm.room.message', sender: f.prov.agentMxId, content: { msgtype: 'm.text', body: '在线' } }; const done = { event_id: '$done', type: 'm.reaction', sender: f.prov.agentMxId, content: { 'm.relates_to': { rel_type: 'm.annotation', key: '✅', event_id: '$probe' } } }; const root = { event_id: '$probe' }; f.events([done, reply, root]); assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), true); f.events([{ ...done, sender: '@other:fmode.cn' }, reply, root]); assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), false); f.events([done, root, reply]); assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), false); }); test('探针超过最近消息窗口时按事件上下文恢复验证', async () => { const f = probeFixture(); await provisionScope._probeRoundtrip(f.job, f.prov); f.events([]); const original = provisionScope.fetch; provisionScope.fetch = async (url, init) => url.includes('/context/') ? { ok: true, json: async () => ({ event: { event_id: '$probe' }, events_after: [ { event_id: '$reply', type: 'm.room.message', sender: f.prov.agentMxId, content: { msgtype: 'm.text', body: '在线' } }, { event_id: '$done', type: 'm.reaction', sender: f.prov.agentMxId, content: { 'm.relates_to': { rel_type: 'm.annotation', key: '✅', event_id: '$probe' } } }, ] }), } : original(url, init); assert.equal(await provisionScope._probeRoundtrip(f.job, f.prov), true); });