feat(memory): release Mnemo project bridge and schema2 recovery
Official contracts and Windows source CI / windows-source (push) Has been cancelled
Official contracts and Windows source CI / windows-source (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { REQUEST_LEDGER_MIGRATION } from '../src/core/storage/request-ledger-schema.mjs';
|
||||
|
||||
export function writeDataCompatibility(root) {
|
||||
const describe = name => { const bytes = fs.readFileSync(path.join(root, name)); return { path: name, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') }; };
|
||||
const declaration = { schemaVersion: 1, application: 'agent-workbench-database', readWriteSchemas: [1, 2], ledgerMigration: REQUEST_LEDGER_MIGRATION,
|
||||
sourceInputs: ['src/core/models/request-ledger.mjs', 'src/core/storage/state-database.mjs', 'src/core/storage/request-ledger-schema.mjs'].map(describe),
|
||||
bundles: ['dist-server/server.mjs', 'dist-server/hot-upgrade.mjs'].map(describe) };
|
||||
fs.writeFileSync(path.join(root, 'dist-server/data-compatibility.json'), JSON.stringify(declaration, null, 2) + '\n');
|
||||
return declaration;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { build } from 'esbuild';
|
||||
import fs from 'node:fs';
|
||||
import { writeDataCompatibility } from './build-data-compatibility.mjs';
|
||||
// Bundled CommonJS dependencies (QR PNG encoder) still import Node builtins.
|
||||
const nodeRequire = { js: "import { createRequire as __awbCreateRequire } from 'node:module'; const require = __awbCreateRequire(import.meta.url);" };
|
||||
fs.mkdirSync('dist-server', { recursive: true });
|
||||
@@ -16,4 +17,5 @@ await build({ entryPoints: ['src/desktop/main.mjs'], outfile: 'dist-desktop/main
|
||||
platform: 'node', target: 'node24', format: 'cjs', sourcemap: false, legalComments: 'eof' });
|
||||
await build({ entryPoints: ['src/desktop/preload.cjs'], outfile: 'dist-desktop/preload.cjs', bundle: true, external: ['electron'],
|
||||
platform: 'node', target: 'node24', format: 'cjs', sourcemap: false, legalComments: 'eof' });
|
||||
console.log('Server bundle built.');
|
||||
writeDataCompatibility(process.cwd());
|
||||
console.log('Server bundle and database compatibility declaration built.');
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { samePath } from '../src/core/desktop/file-state.mjs';
|
||||
|
||||
export function desktopLaunchCommand(appRoot, args) {
|
||||
const root = fs.realpathSync.native(appRoot), executablePath = desktopExecutableIdentity(root).path;
|
||||
// Packaged Electron loads resources/app itself; only the default Electron
|
||||
// runtime takes the compiled main program as a positional argument.
|
||||
const packaged = samePath(executablePath, path.join(root, 'desktop/AgentWorkbench.exe'));
|
||||
return { executablePath, args: [...(packaged ? [] : [path.join(root, 'dist-desktop/main.cjs')]), ...args] };
|
||||
}
|
||||
@@ -76,7 +76,8 @@ function sameTarget(target, file) {
|
||||
return target.title === displayName && target.url === 'file://' + displayName;
|
||||
}
|
||||
|
||||
export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRoot }) {
|
||||
export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRoot, rollbackInitialization = false }) {
|
||||
if (typeof rollbackInitialization !== 'boolean' || rollbackInitialization && !handlerRoot) throw new Error('Initialization rollback requires the source-bound current handler root.');
|
||||
const origin = localUrl(url), original = fs.realpathSync.native(currentRoot), next = fs.realpathSync.native(newRoot);
|
||||
const originalScript = path.join(original, 'dist-server', 'server.mjs');
|
||||
const upgradeScript = path.join(next, 'dist-server', 'hot-upgrade.mjs');
|
||||
@@ -145,7 +146,11 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
|
||||
if (captured.exceptionDetails || captured.result.value !== 'context-ready') throw new Error('Could not retain the existing runtime objects.');
|
||||
for (const breakpointId of breakpoints.splice(0)) await protocol.send('Debugger.removeBreakpoint', { breakpointId });
|
||||
await protocol.send('Debugger.resume'); paused = false; await probe;
|
||||
const expression = '(() => { try { const module = process.getBuiltinModule("module").createRequire(' + JSON.stringify(upgradeScript) + ')(' + JSON.stringify(upgradeScript) + '); return module.installUpgrade(globalThis.__awUpgradeContext, { appDirectory: ' + JSON.stringify(next) + ' }); } finally { delete globalThis.__awUpgradeContext; } })()';
|
||||
const restoreScript = rollbackInitialization ? path.join(fs.realpathSync.native(handlerRoot), 'dist-server/hot-upgrade.mjs') : null;
|
||||
const restore = restoreScript ? ' const restoreModule = process.getBuiltinModule("module").createRequire(' + JSON.stringify(restoreScript) + ')(' + JSON.stringify(restoreScript) + ');'
|
||||
+ ' restoreModule.rollbackUnchangedUpgrade(globalThis.__awUpgradeContext, { appDirectory: ' + JSON.stringify(fs.realpathSync.native(handlerRoot)) + ' });' : '';
|
||||
const expression = '(() => { try { const module = process.getBuiltinModule("module").createRequire(' + JSON.stringify(upgradeScript) + ')(' + JSON.stringify(upgradeScript) + ');' + restore
|
||||
+ ' return module.installUpgrade(globalThis.__awUpgradeContext, { appDirectory: ' + JSON.stringify(next) + ' }); } finally { delete globalThis.__awUpgradeContext; } })()';
|
||||
const upgraded = await protocol.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
|
||||
if (upgraded.exceptionDetails) throw new Error('Runtime upgrade failed: ' + (upgraded.exceptionDetails.exception?.description ?? upgraded.exceptionDetails.text));
|
||||
const result = upgraded.result.value;
|
||||
|
||||
@@ -7,7 +7,7 @@ import { chromium, _electron } from 'playwright';
|
||||
import { expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench, compatibleFixture, completion, call, until } from '../tests/helpers.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { advancedArguments, advancedSchema, schemaFixtureTools } from '../tests/fixtures/schema-mcp-server.mjs';
|
||||
import { openWorkbenchTool } from './ui-navigation.mjs';
|
||||
@@ -45,7 +45,7 @@ try {
|
||||
const reservation = net.createServer(); await new Promise(resolve => reservation.listen(0, '127.0.0.1', resolve)); const port = reservation.address().port; await new Promise(resolve => reservation.close(resolve)); assert.notEqual(port, 4318);
|
||||
controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path, args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application = await _electron.launch({ ...desktopLaunchCommand(appRoot, ['--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']), cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page); await window.evaluate(win => win.showInactive());
|
||||
} else { host = await launchWorkbench(t, f.data, {}, { appRoot }); browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage(); }
|
||||
assert.notEqual(new URL(host.url).port, '4318'); page.on('pageerror', error => errors.push(error.message));
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
// Explicit new synthetic-host verification. Never discovers a credential or
|
||||
// production service; no real model or engineering task is used.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { MnemoBridge } from '../src/core/memory/mnemo-bridge.mjs';
|
||||
import { MnemoClient, digest, contextDigest, entryRef } from '../src/core/memory/mnemo-protocol.mjs';
|
||||
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
|
||||
|
||||
const args = process.argv.slice(2), option = name => args[args.indexOf(name) + 1];
|
||||
const requestedCases = args.includes('--cases') ? new Set(option('--cases').split(',')) : null;
|
||||
if (!args.includes('--connection') || !args.includes('--output')) throw new Error('Use --connection <new synthetic connection.private.json> --output <new evidence directory>.');
|
||||
const connectionPath = path.resolve(option('--connection')), output = path.resolve(option('--output'));
|
||||
const c = JSON.parse(fs.readFileSync(connectionPath, 'utf8'));
|
||||
assert.equal(c.syntheticOnly, true); assert.equal(new URL(c.origin).hostname, '127.0.0.1'); assert.ok(c.directory && connectionPath === path.join(c.directory, 'connection.private.json'));
|
||||
fs.mkdirSync(output, { recursive: false });
|
||||
const sha = b => createHash('sha256').update(b).digest('hex');
|
||||
const redact = value => typeof value === 'string' ? value.split(c.fixtureToken).join('[SYNTHETIC_TOKEN]') : Array.isArray(value) ? value.map(redact)
|
||||
: value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).filter(([k]) => !['token', 'fixtureToken', 'providerToken'].includes(k)).map(([k, v]) => [k, redact(v)])) : value;
|
||||
const write = (name, value) => fs.writeFileSync(path.join(output, name), JSON.stringify(redact(value), null, 2));
|
||||
const store = new Store(path.join(output, 'data')), provider = new Provider(); provider.setKey('');
|
||||
const runtime = new Runtime(store, provider), hub = provider.modelHub(store), bridge = runtime.mnemoBridge();
|
||||
const member = hub.upsert({ name: 'Mnemo 本机合成接收器', model: 'mnemo-joint-fixture', baseUrl: c.providerBaseUrl + '/v1', protocol: 'chat-completions', requiresKey: true, apiKey: c.providerToken, streaming: false });
|
||||
hub.select({ type: 'connection', id: member.id });
|
||||
const controls = [], cases = [], runs = [], originalArtifacts = new Map();
|
||||
async function control(route, body) {
|
||||
const response = await fetch(c.origin + '/__fixture/control/' + route, { method: body === undefined ? 'GET' : 'POST',
|
||||
headers: { Authorization: 'Bearer ' + c.fixtureToken, 'Content-Type': 'application/json' }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), redirect: 'error' });
|
||||
const result = await response.json(); controls.push({ route, request: body ?? null, status: response.status, result: redact(result) });
|
||||
assert.ok(response.ok, 'Synthetic control ' + route + ': ' + JSON.stringify(redact(result))); return result;
|
||||
}
|
||||
async function fixture(label, { enabled = true, content = '合成项目约定:保存中文与换行。\n只用于本机联合验收。', expiresAt = null } = {}) {
|
||||
const projectRoot = path.join(output, 'projects', label + '-' + randomUUID()); fs.mkdirSync(projectRoot, { recursive: true });
|
||||
fs.writeFileSync(path.join(projectRoot, 'README.md'), '# New synthetic project ' + label + '\n');
|
||||
const project = store.addProject(projectRoot), sourceSession = store.createSession(project.id, label + ' 来源');
|
||||
const memory = await runtime.memoryManager().create(sourceSession, { title: label + ' 来源', content, ...(expiresAt ? { expiresAt } : {}) });
|
||||
let auth = null;
|
||||
if (enabled) {
|
||||
const view = await bridge.view(project.id);
|
||||
auth = await control('bind', { producerId: view.producerId, projectId: project.id, projectName: label, requestKey: randomUUID(), confirmed: true });
|
||||
await bridge.configure(project.id, { enabled: true, baseUrl: c.origin, bindingId: auth.binding.id, token: auth.token, expectedRevision: 0 });
|
||||
}
|
||||
return { project, projectRoot, sourceSession, memory, auth };
|
||||
}
|
||||
async function action(f, value, memory = f.memory) {
|
||||
const view = await bridge.view(f.project.id), source = view.sources.find(s => s.memoryId === memory.id);
|
||||
return bridge.changeSource(f.project.id, memory.id, { action: value, confirmed: true, expectedDigest: source.confirmationDigest });
|
||||
}
|
||||
async function execute(f, label, query = f.memory.title) {
|
||||
const session = store.createSession(f.project.id, label + ' 新会话'); runtime.start(session.id, query);
|
||||
const active = runtime.active.get(session.id); if (active) await active.promise;
|
||||
const run = store.core.run.get(session.runId), plans = [...store.core.context_plan.values()].filter(p => p.runId === run.id);
|
||||
for (const plan of plans) verifyPlanEvidence(store, session, plan);
|
||||
const attempts = hub.ledger.page({ limit: 10000 }).items.filter(a => a.runId === run.id);
|
||||
const observations = await control('observations');
|
||||
const physical = observations.physical.filter(row => attempts.some(a => a.status !== 'rejected' && (a.upstreamResponse?.requestId === row.physicalRequestId
|
||||
|| !a.upstreamResponse?.requestId && a.requestSha256 === row.bodySha256 && row.receivedAt >= a.startedAt && row.receivedAt <= (a.finishedAt ?? '9999'))));
|
||||
// A negative selection alone is insufficient: the original task must really
|
||||
// reach the controlled receiver, including its failed/unknown responses.
|
||||
assert.ok(observations.physical.some(row => row.captureStatus === 'captured' && row.receivedAt >= run.startedAt), 'No physical receiver observation for this Run');
|
||||
for (const row of physical) {
|
||||
assert.equal(row.captureStatus, 'captured');
|
||||
const filename = row.bodyFile ?? row.artifactPath ?? row.path;
|
||||
const candidates = [filename, path.join(c.directory, 'physical-' + String(row.sequence).padStart(4, '0') + '.body.json')].filter(Boolean);
|
||||
const source = candidates.map(v => path.resolve(c.directory, v)).find(v => v.startsWith(path.resolve(c.directory) + path.sep) && fs.existsSync(v));
|
||||
assert.ok(source, 'Actual physical bytes are missing');
|
||||
const bytes = fs.readFileSync(source); assert.equal(sha(bytes), row.bodySha256);
|
||||
fs.copyFileSync(source, path.join(output, path.basename(source))); row.capturedBody = JSON.parse(bytes); row.localBodyFile = path.basename(source);
|
||||
const matches = attempts.filter(a => a.status !== 'rejected' && (a.upstreamResponse?.requestId === row.physicalRequestId
|
||||
|| !a.upstreamResponse?.requestId && a.requestSha256 === row.bodySha256 && row.receivedAt >= a.startedAt && row.receivedAt <= (a.finishedAt ?? '9999')));
|
||||
assert.equal(matches.length, 1); const attempt = matches[0]; assert.equal(attempt.requestSha256, row.bodySha256);
|
||||
const plan = plans.find(p => p.id === attempt.requestId); assert.ok(plan);
|
||||
const dispatch = plan.mnemoDispatches?.find(d => d.wireAttemptId === attempt.wireAttemptId);
|
||||
if (plan.mnemoMemoryArtifactId) { assert.ok(dispatch); assert.equal(dispatch.wireRequestSha256, row.bodySha256); }
|
||||
}
|
||||
assert.equal([...store.core.tool.values()].filter(t => t.runId === run.id).length, 0);
|
||||
const result = { label, projectId: f.project.id, sessionId: session.id, taskId: session.taskId, runId: run.id, sessionStatus: session.status, plans: structuredClone(plans), attempts, physical: structuredClone(physical) };
|
||||
runs.push(result); write('runs.json', runs);
|
||||
for (const artifact of store.core.artifact.values()) if (!originalArtifacts.has(artifact.id)) originalArtifacts.set(artifact.id, { artifact: structuredClone(artifact), sha256: sha(store.artifactStore.readBytes(artifact)) });
|
||||
return result;
|
||||
}
|
||||
function selected(result) { return result.plans.at(-1)?.mnemoSelectedRefs ?? []; }
|
||||
function hasRemote(result) { return result.physical.some(p => JSON.stringify(p.capturedBody).includes('mnemo_project_memory')); }
|
||||
async function sample(id, action) {
|
||||
if (requestedCases && !requestedCases.has(id)) return;
|
||||
const startedAt = new Date().toISOString();
|
||||
try { const evidence = await action(); cases.push({ id, status: 'passed', startedAt, finishedAt: new Date().toISOString(), evidence }); console.log(id + ' passed'); }
|
||||
catch (cause) { cases.push({ id, status: 'failed', startedAt, finishedAt: new Date().toISOString(), error: cause.stack }); console.log(id + ' failed: ' + cause.message); }
|
||||
write('cases.json', cases); write('controls.json', controls);
|
||||
if (args.includes('--fail-fast') && cases.at(-1).status === 'failed') throw new Error(id + ' failed; preserving this immutable run.');
|
||||
}
|
||||
try {
|
||||
await sample('N01', async () => { const f = await fixture('N01', { enabled: false }), before = await control('observations'), r = await execute(f, 'N01');
|
||||
const after = await control('observations'); assert.equal(before.bridge.length, after.bridge.length); assert.equal(hasRemote(r), false); assert.equal(r.physical.length, 1); return r.runId; });
|
||||
await sample('N02', async () => { const f = await fixture('N02'); await action(f, 'confirm'); const r = await execute(f, 'N02'); assert.equal(selected(r).length, 1); assert.equal(hasRemote(r), true); return r.runId; });
|
||||
await sample('N03', async () => { const f = await fixture('N03'), r = await execute(f, 'N03'); assert.equal(selected(r).length, 0); assert.equal(hasRemote(r), false); return r.runId; });
|
||||
await sample('N04', async () => { const f = await fixture('N04'); await action(f, 'candidate'); const r = await execute(f, 'N04'); assert.equal(selected(r).length, 0); assert.equal(hasRemote(r), false); return r.runId; });
|
||||
await sample('N05', async () => { const f = await fixture('N05'); await action(f, 'confirm'); const a = await execute(f, 'N05-old');
|
||||
const m = store.core.memory.get(f.memory.id); m.content = '已明确更正的新合成约定。'; m.updatedAt = new Date().toISOString(); store.putRecord('memory', f.sourceSession, m, 'memory.synthetic_revision');
|
||||
await action(f, 'confirm'); const b = await execute(f, 'N05-new'); assert.ok(selected(b)[0].sequence > selected(a)[0].sequence); assert.ok(JSON.stringify(b.physical[0].capturedBody).includes(m.content)); return [a.runId, b.runId]; });
|
||||
await sample('N06', async () => { const f = await fixture('N06'); await action(f, 'confirm'); await execute(f, 'N06-before'); runtime.memoryManager().archive(f.sourceSession, f.memory.id);
|
||||
const r = await execute(f, 'N06-after'); assert.equal(hasRemote(r), false); assert.equal((await bridge.view(f.project.id)).sources[0].state, 'archived'); return r.runId; });
|
||||
await sample('N07', async () => { const expiresAt = new Date(Date.now() + 20000).toISOString(), f = await fixture('N07', { expiresAt }); await action(f, 'confirm');
|
||||
const r = await execute(f, 'N07'), p = r.plans.at(-1), doc = JSON.parse(store.artifactStore.read(store.core.artifact.get(p.mnemoRecallArtifactId)));
|
||||
assert.equal(selected(r).length, 1); assert.ok(Date.parse(doc.snapshot.expiresAt) <= Date.parse(expiresAt)); return r.runId; });
|
||||
await sample('N08', async () => { const f = await fixture('N08'); await action(f, 'confirm'); const old = await execute(f, 'N08-old'); await action(f, 'delete');
|
||||
const state = store.storage.meta('mnemoProjectMemoryBridge').projects[f.project.id]; assert.ok(state.events.every(e => e.input.memory === null && e.attempts.every(a => !a.request?.memory)));
|
||||
const renewal = await control('renew', { bindingId: f.auth.binding.id, requestKey: randomUUID(), confirmed: true }), view = await bridge.view(f.project.id);
|
||||
await bridge.configure(f.project.id, { enabled: true, expectedRevision: view.connection.revision, token: renewal.token }); await assert.rejects(action(f, 'confirm'), { code: 'PROJECT_SOURCE_DELETED' });
|
||||
const r = await execute(f, 'N08-deleted'); assert.equal(hasRemote(r), false); return [old.runId, r.runId]; });
|
||||
await sample('N09', async () => { const f = await fixture('N09'); await action(f, 'confirm'); const deletion = await control('delete-source', { bindingId: f.auth.binding.id, sourceId: f.memory.id, confirmed: true });
|
||||
assert.equal(deletion.externalDeleted, false); await bridge.lookupSource(f.project.id, f.memory.id); assert.equal((await bridge.view(f.project.id)).sources[0].state, 'deleted'); const r = await execute(f, 'N09'); assert.equal(hasRemote(r), false); return r.runId; });
|
||||
await sample('N10', async () => { const f = await fixture('N10'); await action(f, 'confirm'); await control('fault', { target: 'recall', mode: 'revoke_after_recall' });
|
||||
const r = await execute(f, 'N10'); assert.equal(r.plans.length, 2); assert.equal(r.plans[0].mnemoDispatches[0].status, 'not_dispatched'); assert.equal(hasRemote(r), false); assert.equal(r.physical.length, 1); return r.runId; });
|
||||
await sample('N11', async () => { const f = await fixture('N11'); await action(f, 'confirm'); const old = await bridge.context(f.sourceSession, '项目');
|
||||
const oldClient = bridge.client(bridge.state(), f.project.id), renewal = await control('renew', { bindingId: f.auth.binding.id, requestKey: randomUUID(), confirmed: true });
|
||||
await assert.rejects(oldClient.validate(old.snapshot, old.manifest)); const view = await bridge.view(f.project.id);
|
||||
await bridge.configure(f.project.id, { enabled: true, expectedRevision: view.connection.revision, token: renewal.token }); const r = await execute(f, 'N11'); assert.equal(selected(r).length, 1);
|
||||
const doc = JSON.parse(store.artifactStore.read(store.core.artifact.get(r.plans.at(-1).mnemoRecallArtifactId))); assert.notEqual(doc.snapshot.grantId, old.snapshot.grantId); return r.runId; });
|
||||
await sample('N12', async () => { const f = await fixture('N12'); await action(f, 'confirm'); const original = bridge.beforePhysical.bind(bridge); let once = true;
|
||||
bridge.beforePhysical = async (...a) => { if (once) { once = false; await new Promise(resolve => setTimeout(resolve, 31000)); } return original(...a); };
|
||||
try { const r = await execute(f, 'N12'); assert.equal(r.plans.length, 2); assert.equal(hasRemote(r), false); return r.runId; } finally { bridge.beforePhysical = original; } });
|
||||
for (const [id, mutation] of [['N13', f => { const m = store.core.memory.get(f.memory.id); m.content += '\n召回后改版。'; m.updatedAt = new Date().toISOString(); store.putRecord('memory', f.sourceSession, m, 'memory.synthetic_revision'); }],
|
||||
['N14', f => fs.appendFileSync(path.join(f.projectRoot, 'README.md'), '\nSource changed after recall.\n')]]) {
|
||||
await sample(id, async () => { const f = await fixture(id); await action(f, 'confirm'); const original = bridge.beforePhysical.bind(bridge); let once = true;
|
||||
bridge.beforePhysical = async (...a) => { if (once) { once = false; mutation(f); } return original(...a); };
|
||||
try { const r = await execute(f, id); assert.equal(hasRemote(r), false); assert.equal(r.plans.length, 2); return r.runId; } finally { bridge.beforePhysical = original; } });
|
||||
}
|
||||
await sample('N15', async () => { const a = await fixture('N15-a'), b = await fixture('N15-b', { enabled: false }); await action(a, 'confirm'); const view = await bridge.view(b.project.id);
|
||||
await assert.rejects(bridge.configure(b.project.id, { enabled: true, baseUrl: c.origin, bindingId: a.auth.binding.id, token: a.auth.token, expectedRevision: view.connection.revision }));
|
||||
const r = await execute(b, 'N15'); assert.equal(hasRemote(r), false); return r.runId; });
|
||||
await sample('N16', async () => { const f = await fixture('N16'); await control('fault', { target: 'sync', mode: 'drop_after_commit' }); const before = await control('observations');
|
||||
const v = await action(f, 'confirm'), source = v.sources[0]; assert.equal(source.syncStatus, 'unknown');
|
||||
const saved = structuredClone(store.storage.meta('mnemoProjectMemoryBridge').projects[f.project.id].sources[f.memory.id].event);
|
||||
assert.equal(saved.input.memory.content, f.memory.content); assert.equal(saved.requestKey, source.requestKey); write('N16-original-unknown.json', saved);
|
||||
await bridge.lookupSource(f.project.id, f.memory.id); const restored = await bridge.view(f.project.id); assert.equal(restored.sources[0].syncStatus, 'committed'); assert.equal(restored.sources[0].requestKey, source.requestKey);
|
||||
const after = await control('observations'); const syncs = values => values.filter(v => String(v.path ?? v.route ?? '').split('?')[0].endsWith('/sync') || v.operation === 'sync');
|
||||
assert.equal(syncs(after.bridge).length - syncs(before.bridge).length, 1);
|
||||
const r = await execute(f, 'N16'); assert.equal(selected(r).length, 1); return r.runId; });
|
||||
await sample('N17', async () => { const f = await fixture('N17'); await action(f, 'confirm'); const state = bridge.state(), e = state.projects[f.project.id].sources[f.memory.id].event, client = bridge.client(state, f.project.id);
|
||||
const altered = structuredClone(e.input); altered.memory.content += ' changed'; await assert.rejects(client.sync(altered));
|
||||
const lower = structuredClone(e.input); lower.requestKey = randomUUID(); await assert.rejects(client.sync(lower)); const r = await execute(f, 'N17'); assert.equal(selected(r).length, 1); return r.runId; });
|
||||
await sample('N18', async () => { const ids = [];
|
||||
for (const [target, mode] of [['recall', 'content_corruption'], ['validate', 'invalid_json'], ['validate', 'wrong_validation']]) {
|
||||
const f = await fixture('N18-' + mode); await action(f, 'confirm'); await control('fault', { target, mode }); const r = await execute(f, 'N18-' + mode); assert.equal(hasRemote(r), false); assert.equal(r.physical.length, 1); ids.push(r.runId);
|
||||
} return ids; });
|
||||
await sample('N19', async () => { const f = await fixture('记忆子集A');
|
||||
const second = await runtime.memoryManager().create(f.sourceSession, { title: '记忆子集B', content: '第二条合成约定,供规划器整条选择。' });
|
||||
await action(f, 'confirm'); await action(f, 'confirm', second); const view = await bridge.view(f.project.id);
|
||||
await bridge.configure(f.project.id, { enabled: true, expectedRevision: view.connection.revision, selectionLimit: 1 });
|
||||
const r = await execute(f, 'N19', '记忆子集'), p = r.plans.at(-1), recall = JSON.parse(store.artifactStore.read(store.core.artifact.get(p.mnemoRecallArtifactId))), doc = JSON.parse(store.artifactStore.read(store.core.artifact.get(p.mnemoMemoryArtifactId)));
|
||||
assert.equal(recall.entries.length, 2); assert.equal(doc.entries.length, 1); assert.notEqual(p.mnemoRecallContextDigest, p.mnemoSelectedContextDigest);
|
||||
assert.equal(p.mnemoSelectedContextDigest, contextDigest(doc.entries)); assert.deepEqual(p.mnemoSelectedRefs, doc.entries.map(entryRef));
|
||||
assert.ok(JSON.stringify(r.physical[0].capturedBody).includes('mnemo_project_memory')); return r.runId; });
|
||||
await sample('N20', async () => { const f = await fixture('N20', { content: '完整本地正文。'.repeat(1900) }), original = f.memory.content; await assert.rejects(action(f, 'confirm'));
|
||||
const r = await execute(f, 'N20'); assert.equal(hasRemote(r), false); assert.ok(JSON.stringify(r.physical[0].capturedBody).includes(original)); assert.equal(store.core.memory.get(f.memory.id).content, original);
|
||||
assert.equal(r.physical[0].capturedBody.max_tokens, undefined); return r.runId; });
|
||||
await sample('N21', async () => { const f = await fixture('N21'); await action(f, 'confirm'); await control('fault', { target: 'provider', mode: 'drop_after_receipt' });
|
||||
const r = await execute(f, 'N21'); assert.equal(r.attempts.length, 1); assert.equal(r.attempts[0].status, 'unknown'); assert.equal(r.plans.at(-1).mnemoDispatches[0].status, 'unknown'); return r.runId; });
|
||||
await sample('N22', async () => { const f = await fixture('N22'); await action(f, 'confirm');
|
||||
const originalConfig = structuredClone(store.config), second = hub.upsert({ name: '本机SSE变体', model: 'mnemo-joint-fixture-sse', baseUrl: c.providerBaseUrl + '/v1', protocol: 'chat-completions', requiresKey: true, apiKey: c.providerToken, streaming: true });
|
||||
const pool = hub.pool({ name: '显式合成两尝试', members: [{ connectionId: member.id }, { connectionId: second.id }], strategy: 'round-robin', maxAttempts: 2, sticky: false });
|
||||
hub.select({ type: 'pool', id: pool.id }); store.saveConfig({ capacityMode: 'model' });
|
||||
try {
|
||||
await control('fault', { target: 'provider', mode: 'http_error' }); const r = await execute(f, 'N22');
|
||||
assert.equal(r.attempts.length, 2); assert.equal(r.physical.length, 2); assert.deepEqual(r.attempts.map(a => a.status).sort(), ['completed', 'failed']);
|
||||
assert.equal(r.plans.at(-1).mnemoDispatches.length, 2); assert.notEqual(r.attempts[0].wireAttemptId, r.attempts[1].wireAttemptId);
|
||||
assert.ok(r.plans.at(-1).mnemoDispatches.every(d => d.validationArtifactId && d.wireRequestSha256));
|
||||
assert.equal(r.attempts.filter(a => a.usageStatus === 'reported').length, 1); return r.runId;
|
||||
} finally { store.saveConfig(originalConfig); hub.select({ type: 'connection', id: member.id }); }
|
||||
});
|
||||
await sample('N23', async () => { const f = await fixture('N23'); await action(f, 'confirm'); const oldState = structuredClone(store.storage.meta('mnemoProjectMemoryBridge')); await action(f, 'delete');
|
||||
store.storage.transaction(() => store.storage.setMeta('mnemoProjectMemoryBridge', oldState)); const restored = new MnemoBridge(store), view = await restored.view(f.project.id);
|
||||
assert.equal(view.connection.hasToken, false); assert.equal(view.sources[0].state, 'deleted'); assert.ok(store.storage.meta('mnemoProjectMemoryBridge').projects[f.project.id].events.every(e => e.input.memory === null));
|
||||
const renewal = await control('renew', { bindingId: f.auth.binding.id, requestKey: randomUUID(), confirmed: true }); await restored.configure(f.project.id, { enabled: true, expectedRevision: view.connection.revision, token: renewal.token });
|
||||
await assert.rejects(restored.changeSource(f.project.id, f.memory.id, { action: 'confirm', confirmed: true, expectedDigest: view.sources[0].confirmationDigest }), { code: 'PROJECT_SOURCE_DELETED' });
|
||||
// Runtime retains its own old credential revision; it cannot reuse it after restore.
|
||||
const r = await execute(f, 'N23'); assert.equal(hasRemote(r), false); return r.runId; });
|
||||
await sample('N24', async () => { const f = await fixture('N24'); await action(f, 'candidate'); const a = await execute(f, 'N24-candidate'); await action(f, 'confirm');
|
||||
const b = await execute(f, 'N24-confirmed'); assert.equal(hasRemote(a), false); assert.equal(selected(b)[0].sequence, 2); return [a.runId, b.runId]; });
|
||||
} finally {
|
||||
try {
|
||||
for (const value of originalArtifacts.values()) assert.equal(sha(store.artifactStore.readBytes(value.artifact)), value.sha256, 'Original request/artifact drift');
|
||||
write('original-artifacts.json', [...originalArtifacts.entries()].map(([id, value]) => ({ id, sha256: value.sha256, kind: value.artifact.kind })));
|
||||
write('final-observations.json', await control('observations')); write('controls.json', controls);
|
||||
write('result.json', { at: new Date().toISOString(), instanceId: c.instanceId, connectionFileRead: connectionPath, cases, runs: runs.map(r => ({ label: r.label, runId: r.runId })),
|
||||
artifactCount: originalArtifacts.size, sourceVersion: store.config.version ?? null, realModelCalls: 0, productionAccessed: false,
|
||||
notClaimed: ['real model quality', 'autonomous delivery', 'Purge benefit', 'global provider compatibility', 'long-term validation'], pending: ['N25'] });
|
||||
} finally { await runtime.stopAll(); store.close(); }
|
||||
}
|
||||
if (cases.some(c => c.status !== 'passed')) process.exitCode = 1;
|
||||
console.log(JSON.stringify({ output, passed: cases.filter(c => c.status === 'passed').length, failed: cases.filter(c => c.status === 'failed').length }));
|
||||
@@ -0,0 +1,172 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { X509Certificate } from 'node:crypto';
|
||||
import { chromium, _electron } from 'playwright';
|
||||
import { expect } from 'playwright/test';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { launchWorkbench, until } from '../tests/helpers.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { openWorkbenchTool } from './ui-navigation.mjs';
|
||||
import { verifyPlanEvidence } from '../src/core/context/request-plan.mjs';
|
||||
|
||||
if (process.argv.includes('--help')) { console.log('node scripts/verify-mnemo-ui.mjs --app-root <independent candidate> --connection <new synthetic connection.private.json> --output <new evidence directory> [--desktop]'); process.exit(0); }
|
||||
const args = process.argv.slice(2), opt = name => { assert.ok(args.includes(name)); return args[args.indexOf(name) + 1]; };
|
||||
const appRoot = fs.realpathSync.native(opt('--app-root')), output = path.resolve(opt('--output')), desktop = args.includes('--desktop');
|
||||
const c = JSON.parse(fs.readFileSync(path.resolve(opt('--connection')))); assert.equal(c.syntheticOnly, true); assert.equal(new URL(c.origin).hostname, '127.0.0.1');
|
||||
fs.mkdirSync(output); const data = path.join(output, 'data'), projectRoot = path.join(output, 'project'); fs.mkdirSync(projectRoot);
|
||||
fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Newly owned UI fixture\n');
|
||||
const store = new Store(data), project = store.addProject(projectRoot), session = store.createSession(project.id, '记忆桥原生界面验收');
|
||||
const provider = new Provider(); provider.setKey(''); const hub = provider.modelHub(store);
|
||||
const connection = hub.upsert({ name: '新本机合成接收器', model: 'mnemo-joint-ui', baseUrl: c.providerBaseUrl + '/v1', requiresKey: true }); hub.select({ type: 'connection', id: connection.id });
|
||||
// Only the new controlled provider capability is re-entered explicitly below.
|
||||
store.close();
|
||||
const checks = [], screenshots = [], errors = [], blocked = [], disposers = [], t = { after: callback => disposers.push(callback) };
|
||||
let host, controller, browser, application, page, window, relay, mobileContext, result;
|
||||
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const mark = text => { checks.push(text); console.log('PASS ' + text); };
|
||||
const secretValues = [c.fixtureToken];
|
||||
const clean = input => { let text = JSON.stringify(input); for (const token of secretValues) if (token) text = text.split(token).join('[SYNTHETIC_TOKEN]'); return JSON.parse(text); };
|
||||
async function control(route, body) {
|
||||
const r = await fetch(c.origin + '/__fixture/control/' + route, { method: body === undefined ? 'GET' : 'POST', headers: { Authorization: 'Bearer ' + c.fixtureToken, 'Content-Type': 'application/json' },
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }), redirect: 'error' }); const value = await r.json(); assert.ok(r.ok); return value;
|
||||
}
|
||||
async function resize(width, height = 960) {
|
||||
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(w => innerWidth === w, width)); }
|
||||
else await page.setViewportSize({ width, height });
|
||||
}
|
||||
async function shot(name, anchor, target = page) {
|
||||
if (anchor) await anchor.scrollIntoViewIfNeeded(); await target.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
assert.ok(await target.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'Page must fit the viewport');
|
||||
const filename = path.join(output, name + '.png'); let capture = 'playwright';
|
||||
if (window && target === page) {
|
||||
const picture = await window.evaluate(async win => { const [width, height] = win.getContentSize(); const image = await win.capturePage({ x: 0, y: 0, width, height }, { stayHidden: true, stayAwake: true });
|
||||
return { data: image.toPNG().toString('base64'), hidden: !win.isVisible(), empty: image.isEmpty(), size: image.getSize() }; });
|
||||
assert.equal(picture.hidden, true); assert.equal(picture.empty, false); fs.writeFileSync(filename, Buffer.from(picture.data, 'base64')); capture = 'native-hidden-electron';
|
||||
} else await target.screenshot({ path: filename, scale: 'css' });
|
||||
screenshots.push({ file: path.basename(filename), sha256: sha(fs.readFileSync(filename)), capture, width: await target.evaluate(() => innerWidth) });
|
||||
}
|
||||
async function memoryPanel() { await openWorkbenchTool(page, '项目记忆'); const dialog = page.getByRole('dialog', { name: '项目记忆', exact: true }); await expect(dialog).toBeVisible(); return dialog; }
|
||||
async function execute(label) {
|
||||
await page.keyboard.press('Escape'); const before = await control('observations');
|
||||
await page.getByRole('textbox', { name: '任务内容', exact: true }).fill(label);
|
||||
await page.getByRole('button', { name: '发送任务', exact: true }).click();
|
||||
await until(async () => { const s = await host.api('/sessions/' + session.id); return s.runId && s.status === 'completed' && (s.messages ?? []).some(m => m.role === 'user' && m.content === label); }, 45000);
|
||||
const current = await host.api('/sessions/' + session.id), attempts = await host.api('/model-center/attempts?limit=100'), after = await control('observations');
|
||||
assert.equal(after.physical.length, before.physical.length + 1); const physical = after.physical.at(-1), attempt = attempts.items.find(a => a.upstreamResponse?.requestId === physical.physicalRequestId);
|
||||
assert.ok(attempt); assert.equal(attempt.runId, current.runId); assert.equal(attempt.requestSha256, physical.bodySha256);
|
||||
fs.copyFileSync(path.join(c.directory, physical.bodyFile), path.join(output, physical.bodyFile));
|
||||
return { session: current, physical, attempt };
|
||||
}
|
||||
try {
|
||||
if (desktop) {
|
||||
const socket = http.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
controller = new HostController({ appRoot, dataRoot: data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
application = await _electron.launch({ ...desktopLaunchCommand(appRoot, ['--app-root', appRoot, '--data-root', data, '--node', process.execPath, '--port', String(port), '--hidden-window']),
|
||||
cwd: appRoot, env: projectEnvironment({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page);
|
||||
} else { host = await launchWorkbench(t, data, {}, { appRoot }); browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage(); }
|
||||
assert.notEqual(new URL(host.url).port, '4318');
|
||||
page.setDefaultTimeout(15000); page.on('pageerror', cause => errors.push(cause.message));
|
||||
await page.route('**/*', route => { const url = new URL(route.request().url()); if (url.origin === new URL(host.url).origin || ['data:', 'blob:'].includes(url.protocol)) return route.continue(); blocked.push(url.origin); return route.abort(); });
|
||||
const saved = (await host.api('/model-center')).connections.find(v => v.id === connection.id);
|
||||
await host.api('/model-center/connections', { ...saved, apiKey: c.providerToken });
|
||||
await page.addInitScript(({ projectId, sessionId }) => { localStorage.setItem('awb-project', projectId); localStorage.setItem('awb-session', sessionId); }, { projectId: project.id, sessionId: session.id });
|
||||
await resize(1280); await page.goto(host.url); await page.waitForLoadState('networkidle');
|
||||
let dialog = await memoryPanel(); const editor = dialog.locator('.memory-editor');
|
||||
await editor.getByLabel('标题', { exact: true }).fill('引航合成记忆'); await editor.getByLabel('内容', { exact: true }).fill('引航合成记忆:这是新本机来源的完整中文正文。\n保留换行和来源修订,不代表真实工程已交付。');
|
||||
await editor.getByRole('button', { name: '保存记忆', exact: true }).click(); await expect(dialog.locator('.memory-card')).toContainText('引航合成记忆');
|
||||
const bridge = dialog.getByRole('region', { name: 'Mnemo 项目记忆桥', exact: true }); await bridge.locator('summary').first().click();
|
||||
await expect(bridge).toContainText('默认关闭'); await shot('bridge-default-off-1280', bridge);
|
||||
const view = await host.api('/projects/' + project.id + '/memory-bridge'), auth = await control('bind', { producerId: view.producerId, projectId: project.id, projectName: '新界面合成项目', requestKey: randomUUID(), confirmed: true });
|
||||
secretValues.push(auth.token);
|
||||
await bridge.getByLabel('Mnemo 根地址', { exact: true }).fill(c.origin); await bridge.getByLabel('项目绑定 ID', { exact: true }).fill(auth.binding.id);
|
||||
await bridge.getByLabel('本次项目凭据', { exact: true }).fill(auth.token); await bridge.getByLabel('启用本项目记忆桥', { exact: true }).check();
|
||||
await bridge.getByRole('button', { name: '保存连接', exact: true }).click(); await expect(bridge).toContainText('本次已连接'); await expect(bridge.getByLabel('本次项目凭据', { exact: true })).toHaveValue('');
|
||||
await bridge.getByRole('button', { name: /引航合成记忆/ }).click();
|
||||
const review = bridge.locator('.mnemo-review'), fullRevision = review.locator('details').filter({ hasText: '查看完整来源修订与摘要' });
|
||||
await fullRevision.locator('summary').click();
|
||||
const displayed = JSON.parse(await fullRevision.locator('pre').innerText()), currentView = await host.api('/projects/' + project.id + '/memory-bridge');
|
||||
assert.deepEqual(displayed, currentView.sources[0].review); assert.equal(sha(JSON.stringify(displayed)), currentView.sources[0].confirmationDigest);
|
||||
await shot('full-source-revision-1280', fullRevision); await fullRevision.locator('summary').click();
|
||||
await expect(bridge.getByRole('button', { name: '确认并共享', exact: true })).toBeDisabled();
|
||||
await bridge.getByLabel('我已核对以上完整来源修订', { exact: true }).check(); await bridge.getByRole('button', { name: '提交候选', exact: true }).click();
|
||||
await expect(bridge.locator('.mnemo-sources')).toContainText('候选 · 未确认'); await shot('candidate-1280', bridge.locator('.mnemo-review'));
|
||||
await bridge.getByLabel('我已核对以上完整来源修订', { exact: true }).check(); await bridge.getByRole('button', { name: '确认并共享', exact: true }).click();
|
||||
await expect(bridge.locator('.mnemo-sources')).toContainText('已确认 · 修订 2');
|
||||
await page.reload(); await page.waitForLoadState('networkidle'); dialog = await memoryPanel();
|
||||
const reloaded = dialog.getByRole('region', { name: 'Mnemo 项目记忆桥', exact: true }); await reloaded.locator('summary').first().click(); await expect(reloaded).toContainText('本次已连接');
|
||||
await resize(390, 844); await reloaded.getByRole('button', { name: /引航合成记忆/ }).click(); await shot('confirmed-source-390', reloaded.locator('.mnemo-review'));
|
||||
mark('Real form saves a default-off connection, explicit candidate and exact full confirmation; refresh and 390px retain revision without showing credentials');
|
||||
await resize(1280); const first = await execute('引航合成记忆');
|
||||
await page.reload(); await page.waitForLoadState('networkidle'); await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
|
||||
const context = page.getByLabel('请求上下文', { exact: true }), receipt = context.locator('.mnemo-plan-receipt');
|
||||
await expect(receipt).toBeVisible(); await receipt.locator('summary').click(); await expect(receipt).toContainText('已收到响应'); await expect(receipt).toContainText('来源序号 2');
|
||||
await shot('physical-receipt-1280', receipt); await receipt.getByRole('button', { name: '查看整条选入记忆', exact: true }).click();
|
||||
const artifact = page.getByRole('dialog', { name: '执行结果工件', exact: true }); await expect(artifact.locator('pre')).toContainText('mnemo-authorized-project-memory'); await expect(artifact.locator('pre')).toContainText('引航合成记忆');
|
||||
await shot('selected-artifact-1280', artifact); await page.keyboard.press('Escape'); await resize(390, 844);
|
||||
// Responsive layout closes the inspector; reopen its actual narrow entry.
|
||||
await page.getByRole('button', { name: '查看任务记录', exact: true }).click(); await expect(receipt).toBeVisible();
|
||||
await shot('physical-receipt-390', receipt); await page.keyboard.press('Escape');
|
||||
mark('Same physical request ID/SHA and Task/Run are bound to full selected source and per-attempt validation; desktop and narrow receipts open original artifacts');
|
||||
|
||||
// Actual companion gateway over certificate-verified HTTPS, with a loopback
|
||||
// browser relay; no OS certificate installation or TLS bypass.
|
||||
const status = await host.api('/companion'); assert.ok(status.addresses.length, 'Owned private interface required for companion');
|
||||
const reservation = http.createServer(); await new Promise(resolve => reservation.listen(0, status.addresses[0].address, resolve)); const port = reservation.address().port; await new Promise(resolve => reservation.close(resolve));
|
||||
const gateway = await host.api('/companion/start', { address: status.addresses[0].address, port });
|
||||
const bootstrap = await (await fetch(host.url + '/api/bootstrap')).json();
|
||||
const certResponse = await fetch(host.url + '/api/companion/certificate', { headers: { 'X-Workbench-Token': bootstrap.token } }); assert.ok(certResponse.ok);
|
||||
const ca = new X509Certificate(Buffer.from(await certResponse.arrayBuffer())).toString();
|
||||
const pairing = await host.api('/companion/pair', { projectIds: [project.id], permissions: { observe: true, approve: false, stop: false }, expiresInHours: 1 });
|
||||
const target = new URL(gateway.origin); let cookie = '';
|
||||
relay = http.createServer((request, response) => {
|
||||
const forwarded = https.request(new URL(request.url, target), { method: request.method, headers: { Host: target.host, Origin: target.origin, Connection: 'close', ...(cookie ? { Cookie: cookie } : {}),
|
||||
...(request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {}) }, ca, servername: '' }, incoming => {
|
||||
if (incoming.headers['set-cookie']?.length) cookie = incoming.headers['set-cookie'][0].split(';')[0]; const headers = { ...incoming.headers }; delete headers['set-cookie']; response.writeHead(incoming.statusCode, headers); incoming.pipe(response);
|
||||
}); forwarded.on('error', cause => { errors.push('Synthetic TLS relay: ' + cause.code); if (!response.headersSent) response.writeHead(503); response.end(); }); request.pipe(forwarded);
|
||||
});
|
||||
await new Promise(resolve => relay.listen(0, '127.0.0.1', resolve));
|
||||
if (!browser) browser = await chromium.launch({ channel: 'msedge', headless: true });
|
||||
mobileContext = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }); const mobile = await mobileContext.newPage(); mobile.on('pageerror', cause => errors.push(cause.message));
|
||||
await mobile.goto('http://127.0.0.1:' + relay.address().port + '/#pair=' + new URLSearchParams(new URL(pairing.url).hash.slice(1)).get('pair'));
|
||||
await mobile.getByLabel('设备名称', { exact: true }).fill('本机记忆回执窄屏'); await mobile.getByRole('button', { name: '连接这台电脑', exact: true }).click();
|
||||
await expect(mobile.getByRole('heading', { name: '项目任务', exact: true })).toBeVisible(); await mobile.getByRole('button').filter({ hasText: '记忆桥原生界面验收' }).click();
|
||||
const mobileReceipt = mobile.locator('.mnemo-plan-receipt'); await expect(mobileReceipt).toBeVisible(); await mobileReceipt.locator('summary').click();
|
||||
await expect(mobileReceipt).toContainText(first.session.runId); await expect(mobileReceipt).toContainText('来源序号 2'); await expect(mobileReceipt).toContainText('已收到响应');
|
||||
await shot('companion-same-run-390', mobileReceipt, mobile);
|
||||
assert.equal((await mobile.locator('body').innerText()).includes(auth.token), false); assert.equal((await mobile.locator('body').innerText()).includes(projectRoot), false);
|
||||
mark('Actual project-authorized companion projection shows the same Run/source/revision/physical outcome through certificate-verified HTTPS; physical iPhone remains untested');
|
||||
|
||||
await page.keyboard.press('Escape'); dialog = await memoryPanel(); const lastBridge = dialog.getByRole('region', { name: 'Mnemo 项目记忆桥', exact: true }); await lastBridge.locator('summary').first().click();
|
||||
await control('revoke', { bindingId: auth.binding.id }); await resize(1280); const second = await execute('引航合成记忆撤权后的新请求');
|
||||
assert.equal(fs.readFileSync(path.join(output, second.physical.bodyFile), 'utf8').includes('"mnemo_project_memory"'), false);
|
||||
await page.reload(); await page.waitForLoadState('networkidle'); await page.getByRole('button', { name: '查看任务记录', exact: true }).click();
|
||||
const invalid = page.getByLabel('请求上下文', { exact: true }).locator('.mnemo-plan-receipt'); await invalid.locator('summary').click(); await expect(invalid).toContainText('服务拒绝');
|
||||
await shot('unavailable-original-task-1280', invalid);
|
||||
await mobile.reload(); await expect(mobile.getByRole('heading', { name: '项目任务', exact: true })).toBeVisible(); await mobile.getByRole('button').filter({ hasText: '记忆桥原生界面验收' }).click();
|
||||
await mobile.locator('.mnemo-plan-receipt').last().locator('summary').click(); await expect(mobile.locator('.mnemo-plan-receipt').last()).toContainText('0 条选入'); await shot('companion-unavailable-390', mobile.locator('.mnemo-plan-receipt').last(), mobile);
|
||||
mark('Revoked bridge is omitted with a visible reason while the original task still completes once; previous receipt stays available');
|
||||
fs.writeFileSync(path.join(output, 'requests.json'), JSON.stringify(clean({ first, second }), null, 2));
|
||||
assert.equal(errors.length, 0); assert.equal(blocked.length, 0);
|
||||
result = { success: true, appRoot, actualElectron: desktop, checks, screenshots, errors, blocked, projectId: project.id, sessionId: session.id, runIds: [first.session.runId, second.session.runId],
|
||||
realModelCalls: 0, realKeysRead: 0, productionAccessed: false, companionHttpsVerified: true, physicalIPhoneVerified: false };
|
||||
} catch (cause) {
|
||||
if (page) { await shot('failure').catch(() => {}); fs.writeFileSync(path.join(output, 'failure-dom.txt'), await page.locator('body').innerText().catch(() => '')); }
|
||||
result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, errors, blocked, error: cause.stack, realModelCalls: 0, productionAccessed: false };
|
||||
} finally {
|
||||
if (mobileContext) await mobileContext.close(); if (relay) await new Promise(resolve => { relay.closeAllConnections(); relay.close(resolve); });
|
||||
if (application) await application.close(); if (browser) await browser.close();
|
||||
await host?.api('/companion/close', {}).catch(() => {});
|
||||
if (controller && await controller.health()) await controller.stop(); await host?.close?.();
|
||||
for (const dispose of disposers.reverse()) await dispose();
|
||||
fs.writeFileSync(path.join(output, 'result.json'), JSON.stringify(clean(result), null, 2));
|
||||
}
|
||||
console.log(JSON.stringify({ output, success: result.success, error: result.error })); if (!result.success) process.exitCode = 1;
|
||||
@@ -9,7 +9,7 @@ import { expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { catalogModel } from '../src/shared/contracts/model-catalog.mjs';
|
||||
import { openWorkbenchTool } from './ui-navigation.mjs';
|
||||
@@ -95,9 +95,8 @@ try {
|
||||
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
const executable = desktopExecutableIdentity(appRoot).path;
|
||||
application = await _electron.launch({ executablePath: executable, args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot,
|
||||
'--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application = await _electron.launch({ ...desktopLaunchCommand(appRoot, ['--app-root', appRoot,
|
||||
'--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']), cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); });
|
||||
application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page); await window.evaluate(win => win.showInactive());
|
||||
|
||||
@@ -10,7 +10,7 @@ import { fixture, launchWorkbench, until, completion } from '../tests/helpers.mj
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { openWorkbenchTool } from './ui-navigation.mjs';
|
||||
|
||||
@@ -85,9 +85,8 @@ try {
|
||||
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
const executable = desktopExecutableIdentity(appRoot).path;
|
||||
application = await _electron.launch({ executablePath: executable, args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot,
|
||||
'--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application = await _electron.launch({ ...desktopLaunchCommand(appRoot, ['--app-root', appRoot,
|
||||
'--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']), cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); });
|
||||
application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page); await window.evaluate(win => win.showInactive());
|
||||
|
||||
@@ -8,7 +8,7 @@ import { expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { usageSamples, usageModelId, cacheUsageFixture } from '../tests/fixtures/cache-usage-model.mjs';
|
||||
import { openWorkbenchTool } from './ui-navigation.mjs';
|
||||
@@ -93,8 +93,8 @@ try {
|
||||
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
app = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
|
||||
args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'],
|
||||
app = await _electron.launch({ ...desktopLaunchCommand(appRoot,
|
||||
['--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']),
|
||||
cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
app.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); app.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await app.firstWindow(); window = await app.browserWindow(page); await window.evaluate(win => win.showInactive());
|
||||
|
||||
@@ -10,7 +10,7 @@ import { fixture, launchWorkbench, until, completion, call } from '../tests/help
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { modelSnapshot } from '../src/shared/contracts/execution.mjs';
|
||||
import { credentialHeader } from '../src/shared/contracts/model-request-contract.mjs';
|
||||
@@ -130,8 +130,8 @@ try {
|
||||
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
|
||||
args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'],
|
||||
application = await _electron.launch({ ...desktopLaunchCommand(appRoot,
|
||||
['--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']),
|
||||
cwd: appRoot, env: projectEnvironment({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 });
|
||||
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page);
|
||||
|
||||
@@ -10,7 +10,7 @@ import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { catalogModel } from '../src/shared/contracts/model-catalog.mjs';
|
||||
import { modelSnapshot } from '../src/shared/contracts/execution.mjs';
|
||||
@@ -115,8 +115,8 @@ try {
|
||||
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
|
||||
args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application = await _electron.launch({ ...desktopLaunchCommand(appRoot,
|
||||
['--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']), cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page);
|
||||
} else {
|
||||
|
||||
@@ -11,7 +11,7 @@ import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Runtime } from '../src/server/runtime.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { openWorkbenchTool } from './ui-navigation.mjs';
|
||||
|
||||
@@ -54,8 +54,8 @@ try {
|
||||
const server = net.createServer(); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const port = server.address().port; await new Promise(resolve => server.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path, args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot,
|
||||
'--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application = await _electron.launch({ ...desktopLaunchCommand(appRoot, ['--app-root', appRoot,
|
||||
'--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']), cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page); await window.evaluate(win => win.showInactive());
|
||||
} else { host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318'); }
|
||||
browser = await chromium.launch({ channel: 'msedge', headless: true }); if (!page) page = await browser.newPage();
|
||||
|
||||
@@ -10,7 +10,7 @@ import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { Store } from '../src/server/store.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { modelSnapshot } from '../src/shared/contracts/execution.mjs';
|
||||
import { credentialHeader } from '../src/shared/contracts/model-request-contract.mjs';
|
||||
@@ -117,8 +117,8 @@ try {
|
||||
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
application = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
|
||||
args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 });
|
||||
application = await _electron.launch({ ...desktopLaunchCommand(appRoot,
|
||||
['--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']), cwd: appRoot, env: projectEnvironment({ AGENT_WORKBENCH_API_KEY: '' }), timeout: 60000 });
|
||||
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page);
|
||||
} else {
|
||||
|
||||
@@ -9,7 +9,7 @@ import { expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { desktopLaunchCommand } from './desktop-launch.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { usageSamples, usageModelId, cacheUsageFixture } from '../tests/fixtures/cache-usage-model.mjs';
|
||||
import { historicalAttempts, inspectExport, hash } from '../tests/fixtures/request-ledger-data.mjs';
|
||||
@@ -74,8 +74,8 @@ async function start() {
|
||||
if (!port) { const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); port = socket.address().port; await new Promise(resolve => socket.close(resolve)); }
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
app = await _electron.launch({ executablePath: desktopExecutableIdentity(appRoot).path,
|
||||
args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'],
|
||||
app = await _electron.launch({ ...desktopLaunchCommand(appRoot,
|
||||
['--app-root', appRoot, '--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window']),
|
||||
cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
app.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); }); app.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await app.firstWindow(); window = await app.browserWindow(page); await window.evaluate(win => win.showInactive());
|
||||
|
||||
Reference in New Issue
Block a user