Files
Agent-Workbench/src/core/preview/preview-manager.mjs
T

167 lines
14 KiB
JavaScript

import { unrestricted } from '../../shared/contracts/execution-policy.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { nodeEnvironmentBinding, environmentHash as hash, environmentConflict as conflict, fileIdentity } from '../environment/environment-inspector.mjs';
import { previewPlanSeal as seal, PREVIEW_LIVE, assertPreviewsResolved } from '../../shared/contracts/preview.mjs';
import { assertWorkspacesResolved, projectWorkspaceIdentity } from '../../shared/contracts/workspaces.mjs';
import { assertChangeSetsResolved } from '../../shared/contracts/change-sets.mjs';
import { assertMcpResolved } from '../tools/mcp-contract.mjs';
import { workerForSession } from '../../shared/contracts/workers.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
import { inspectProject } from '../project-inspector.mjs';
import { safePath } from '../../server/files.mjs';
import { projectEnvironment } from '../process-environment.mjs';
import { runOwnedCommand } from '../owned-command.mjs';
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
import { previewListeners, samplePreview } from './listener.mjs';
const at = () => new Date().toISOString();
const delay = (ms, signal) => new Promise(resolve => {
const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); };
const timer = setTimeout(done, ms); signal?.addEventListener('abort', done, { once: true }); if (signal?.aborted) done();
});
export class PreviewManager {
constructor(store, { runtimeDirectory = null, redact = String, projectBusy = () => false, readyTimeoutMs = 30000 } = {}) {
Object.assign(this, { store, runtimeDirectory, redact, projectBusy, readyTimeoutMs }); this.active = new Map();
}
projectLive(id) { return [...this.store.core.preview_job.values()].some(job => job.projectId === id && PREVIEW_LIVE.has(job.status)); }
projectActive(id) { return [...this.active.values()].some(value => value.projectId === id && value.job.status !== 'ready'); }
isActive(id) { return [...this.active.values()].some(value => value.sessionId === id && value.job.status !== 'ready'); }
artifact(session, runId, value, kind) {
const artifact = this.store.artifactStore.write(session, this.store.owned('run', runId, session.id),
typeof value === 'string' ? this.redact(value) : JSON.parse(this.redact(JSON.stringify(value))), { kind });
this.store.core.artifact.set(artifact.id, artifact); return artifact;
}
idle(session) {
if ([...this.active.values()].some(value => value.projectId === session.projectId)) throw conflict('所属预览尚在运行或准备中,请先停止。');
assertWorkspacesResolved(this.store, session.projectId, { includePrepared: true });
assertChangeSetsResolved(this.store, session.projectId, { includePrepared: true }); assertMcpResolved(this.store, session.projectId);
assertPreviewsResolved(this.store, session.projectId, { includeReady: true });
if (this.projectBusy(session.projectId) || workerForSession(this.store, session)) throw conflict('请在没有执行或协作的独立项目任务中启动预览。');
if (!session.taskId || !session.runId) throw conflict('先建立任务,再创建所属预览。');
}
async plan(session, input = {}) {
if (!input || Array.isArray(input) || Object.keys(input).some(key => key !== 'port') || input.port !== undefined && (!Number.isSafeInteger(input.port) || input.port < 1024 || input.port > 65535)) throw conflict('预览计划只接受1024到65535的本机端口。');
this.idle(session); const project = this.store.project(session.projectId);
if (!project.workspace) throw conflict('请先创建并打开工作台管理的独立工作区。');
await verifyWorkspaceProject(this.store, project);
const node = nodeEnvironmentBinding(project, { runtimeDirectory: this.runtimeDirectory });
if (node?.status !== 'ready' || node.installed.status !== 'verified') throw conflict('请先诊断并准备可完整核验的项目依赖。');
const manifest = JSON.parse(fs.readFileSync(safePath(project, 'package.json'), 'utf8'));
if (manifest.scripts?.dev?.trim() !== 'vite') throw conflict('首批预览支持dev脚本为vite的工程;其它命令需单独核验。');
const cli = fileIdentity(safePath(project, 'node_modules/vite/bin/vite.js'), 1024 * 1024);
const port = input.port ?? 5173;
if ((await previewListeners(port)).length) throw conflict('所选端口已有监听,不能接管;请选择其它端口。');
const inspection = await inspectProject(project); if (!inspection.scope.complete) throw conflict('工程来源未能完整核验。');
this.idle(session);
const plan = { schemaVersion: 1, id: randomUUID(), sessionId: session.id, projectId: project.id, taskId: session.taskId, runId: session.runId,
root: project.root, workspace: projectWorkspaceIdentity(project), nodeIdentity: node.identity, sourceFingerprint: inspection.sourceFingerprint,
cli, script: manifest.scripts.dev, invocation: { executable: node.runtime.node.path, args: [cli.path, '--host', '127.0.0.1', '--port', String(port), '--strictPort', '--clearScreen', 'false'] },
port, url: 'http://127.0.0.1:' + port + '/', timeoutMs: unrestricted(this.store) ? 0 : 8 * 60 * 60 * 1000, status: 'planned', createdAt: at() };
plan.fingerprint = hash(seal(plan)); const artifact = this.artifact(session, plan.runId, seal(plan), 'preview-plan');
plan.artifactId = artifact.id; plan.artifactSha256 = artifact.sha256;
return this.store.putRecord('preview_plan', session, plan, 'preview.planned');
}
own(session, id, fingerprint) {
const plan = this.store.owned('preview_plan', id, session.id);
if (plan.taskId !== session.taskId || plan.runId !== session.runId || fingerprint !== plan.fingerprint || hash(seal(plan)) !== fingerprint) throw conflict('预览计划的Task、Run或输入已变化。');
const artifact = this.store.owned('artifact', plan.artifactId, session.id);
if (artifact.sha256 !== plan.artifactSha256 || this.store.artifactStore.read(artifact) !== this.redact(JSON.stringify(seal(plan)))) throw conflict('预览原计划工件无法核对。');
return plan;
}
async start(session, id, fingerprint, { approved = false } = {}) {
if (approved !== true) throw conflict('请先核对工作区、Vite配置代码和原命令并明确批准。');
this.idle(session); const plan = this.own(session, id, fingerprint);
if (plan.status !== 'planned') throw conflict('预览计划已使用,不重放原启动。');
// Reserve before asynchronous source verification, including calls from
// another session. A rejected verification does not consume the plan.
const job = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: plan.taskId, runId: plan.runId,
planId: plan.id, planFingerprint: fingerprint, status: 'queued', url: plan.url, port: plan.port, createdAt: at(), requiresVerification: false, logExcerpt: '' };
const active = { job, sessionId: session.id, projectId: session.projectId, controller: new AbortController(), promise: null };
this.active.set(job.id, active);
try {
const project = this.store.project(session.projectId); await verifyWorkspaceProject(this.store, project);
if (hash(projectWorkspaceIdentity(project)) !== hash(plan.workspace) || nodeEnvironmentBinding(project, { runtimeDirectory: this.runtimeDirectory })?.identity !== plan.nodeIdentity
|| hash(fileIdentity(plan.cli.path)) !== hash(plan.cli) || (await inspectProject(project)).sourceFingerprint !== plan.sourceFingerprint) throw conflict('预览来源、工作区、命令或实际依赖已变化,请重新创建计划。');
this.own(session, id, fingerprint);
if (active.controller.signal.aborted) throw conflict('预览启动已停止。');
if ((await previewListeners(plan.port)).length) throw conflict('端口在审批后被其它进程占用,未接管。');
plan.status = 'consumed'; plan.jobId = job.id;
job.status = 'starting'; job.startedAt = at();
const approval = { id: randomUUID(), kind: 'preview', previewPlanId: plan.id, taskId: plan.taskId, runId: plan.runId, status: 'approved', createdAt: at(), resolvedAt: at() };
session.approvals.push(approval); job.approvalId = approval.id;
this.store.putRecord('preview_job', session, job, 'preview.starting');
active.promise = this.execute(session, plan, active);
return { job, promise: active.promise };
} catch (error) { this.active.delete(job.id); throw error; }
}
async watch(session, plan, active) {
const { job, controller } = active, deadline = Date.now() + this.readyTimeoutMs;
while (!controller.signal.aborted && this.active.has(job.id) && job.status === 'starting') {
try {
if (job.process?.pid) {
const listeners = await previewListeners(plan.port);
if (listeners.length) {
const tree = await readOwnedProcessTree(job.process);
if (!tree.supported || !tree.root || listeners.some(value => value.address !== '127.0.0.1:' + plan.port || !tree.processes.some(process => process.pid === value.pid))) {
throw Object.assign(new Error('监听地址或进程不属于原预览,不接管该页面。'), { ownershipFailure: true });
}
const page = await samplePreview(plan.url, controller.signal);
if (controller.signal.aborted || job.status !== 'starting') return;
job.readiness = { ...page, listeners, processes: tree.processes };
const artifact = this.artifact(session, job.runId, job.readiness, 'preview-readiness'); job.readinessArtifactId = artifact.id;
job.status = 'ready'; job.readyAt = at(); job.summary = '所属Vite服务已就绪;可以继续修改源码并观察页面更新。';
this.store.save(session, { type: 'preview.ready', detail: { recordId: job.id } }); return;
}
}
} catch (error) {
job.readinessError = this.redact(error.message);
if (error.ownershipFailure) { job.startFailure = job.readinessError; controller.abort(); return; }
}
if (Date.now() > deadline) { job.startFailure = '预览未在30秒内通过所属监听及首页核验。' + (job.readinessError ?? ''); controller.abort(); return; }
await delay(700, controller.signal);
}
}
async execute(session, plan, active) {
const { job, controller } = active; let logTimer;
const save = () => this.store.save(session, { type: 'preview.progress', detail: { recordId: job.id } });
const running = runOwnedCommand(plan.invocation, { cwd: plan.root, env: projectEnvironment(plan.invocation.executable), signal: controller.signal,
timeoutMs: plan.timeoutMs, onSpawn: info => { job.process = { ...info }; save(); },
onOutput: (stream, value) => { job.logExcerpt = (job.logExcerpt + '[' + stream + '] ' + this.redact(value)).slice(-16000); if (!logTimer) logTimer = setTimeout(() => { logTimer = null; save(); }, 750); } });
const watching = this.watch(session, plan, active);
try {
const result = await running; clearTimeout(logTimer); job.result = { ...result, stdout: undefined, stderr: undefined }; job.process = result.process ?? job.process;
job.status = result.status === 'unknown' ? 'unknown' : job.startFailure ? 'failed' : controller.signal.aborted ? 'stopped' : result.status === 'passed' ? 'exited' : 'failed';
job.requiresVerification = job.status === 'unknown'; job.finishedAt = at();
job.summary = job.startFailure ?? (job.status === 'stopped' ? '所属预览进程已停止,原日志保留。' : job.status === 'unknown' ? '原预览进程结束状态待核对,不自动重启。' : '开发服务已退出,见原退出码和日志。');
const artifact = this.artifact(session, job.runId, '[stdout]\n' + result.stdout + '\n[stderr]\n' + result.stderr, 'preview-log'); job.logArtifactId = artifact.id;
this.store.save(session, { type: 'preview.finished', detail: { recordId: job.id } }); return job;
} catch (error) {
// This promise outlives the HTTP startup request. Retain failed evidence
// as an explicit unknown rather than leaving an unhandled rejection.
clearTimeout(logTimer); controller.abort();
job.status = 'unknown'; job.requiresVerification = true; job.finishedAt = at();
job.error = this.redact(error.message); job.summary = '预览结束证据未能完整保存,请核对原进程和日志;不会自动重启。';
try { this.store.save(session, { type: 'preview.evidence_failed', detail: { recordId: job.id } }); }
catch (failure) { job.persistenceError = this.redact(failure.message); }
return job;
} finally { this.active.delete(job.id); await watching; }
}
async stop(sessionId, id = null) {
if (id) this.store.owned('preview_job', id, sessionId);
const values = [...this.active.entries()].filter(([key, value]) => value.sessionId === sessionId && (!id || id === key));
for (const [, active] of values) { active.job.status = 'stopping'; active.controller.abort(); this.store.save(this.store.session(sessionId), { type: 'preview.stopping' }); }
await Promise.all(values.map(([, value]) => value.promise));
}
async reconcile(session, id, fingerprint) {
const job = this.store.owned('preview_job', id, session.id);
if (!job.requiresVerification || job.reconciliation || fingerprint !== job.planFingerprint) throw conflict('原预览待核对身份已变化。');
if (job.process) { const tree = await readOwnedProcessTree(job.process); if (!tree.supported || tree.processes.length) throw conflict('原预览进程仍存在或无法核对,保留现场;不会按历史PID结束进程。'); }
else throw conflict('缺少原进程身份,不能确认原服务已结束。');
job.reconciliation = { at: at(), result: 'original_processes_absent' }; this.store.save(session, { type: 'preview.reconciled' }); return job;
}
async stopAll() { await Promise.all([...new Set([...this.active.values()].map(value => value.sessionId))].map(id => this.stop(id))); }
}