feat: add owned Vite previews and isolated task browser with approved actions

This commit is contained in:
Agent Workbench Dev
2026-11-02 03:46:40 +08:00
parent de5a1d6c06
commit dc32c899f1
44 changed files with 1282 additions and 35 deletions
+192
View File
@@ -0,0 +1,192 @@
import { randomUUID, randomBytes } from 'node:crypto';
import { browsingUrl, browsingAction, browsingError as conflict } from '../../shared/contracts/browsing.mjs';
const at = () => new Date().toISOString();
// Desktop content has no workbench preload. Only Electron main consumes this
// fixed command queue; webpage text and observations cannot create grants.
export class BrowsingManager {
constructor(store, { redact = String, allowHttpLoopback = false, workbenchOrigin = null, commandTimeoutMs = 20000 } = {}) {
Object.assign(this, { store, redact, allowHttpLoopback, workbenchOrigin, commandTimeoutMs });
this.active = new Map(); this.windows = new Map();
}
available() { return [...this.windows.entries()].filter(([, value]) => Date.now() - value.seenAt < 5000).map(([id]) => id); }
isActive(sessionId) { return [...this.active.values()].some(value => value.job.sessionId === sessionId); }
projectActive(projectId) { return [...this.active.values()].some(value => value.job.projectId === projectId); }
artifact(session, runId, value, kind, mediaType = 'application/json') {
const artifact = this.store.artifactStore.write(session, this.store.owned('run', runId, session.id),
Buffer.isBuffer(value) ? value : JSON.parse(this.redact(JSON.stringify(value))), { kind, mediaType });
this.store.core.artifact.set(artifact.id, artifact); return artifact;
}
own(session, id, { allowClosed = false } = {}) {
const tab = this.store.owned('browsing_tab', id, session.id);
if (tab.taskId !== session.taskId || !allowClosed && tab.status !== 'open') throw conflict('标签页不属于当前Task,或已关闭/撤销。请明确打开新标签页。');
return tab;
}
scope(tab) { return { origins: tab.origins, previewOrigin: tab.previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin }; }
async open(session, input) {
const fields = ['url','previewJobId','origins','interact','persistent','profileId','approved'];
if (!input || Array.isArray(input) || Object.keys(input).some(key => !fields.includes(key)) || input.approved !== true) throw conflict('打开网站需要明确地址、来源范围及用户批准。');
if (!session.taskId || !session.runId) throw conflict('先建立任务,再授权浏览器目标。');
if ([...this.store.core.browsing_tab.values()].filter(tab => tab.sessionId === session.id && tab.status === 'open').length >= 8) throw conflict('每个会话最多8个打开的标签页。');
const windowId = this.available()[0]; if (!windowId) throw conflict('请先打开本工作台桌面端。网页端可以查看原观察和审批。');
let previewOrigin = null;
if (input.previewJobId) {
const preview = this.store.owned('preview_job', input.previewJobId, session.id);
if (preview.taskId !== session.taskId || preview.status !== 'ready') throw conflict('所属预览尚未就绪。');
previewOrigin = new URL(preview.url).origin;
}
const url = browsingUrl(input.url, { previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin });
if (input.origins !== undefined && (!Array.isArray(input.origins) || input.origins.length > 8 || input.origins.some(value => typeof value !== 'string'))) throw conflict('最多明确授权8个网站来源。');
const origins = [...new Set([url.origin, ...(input.origins ?? []).map(value => browsingUrl(value, { previewOrigin, allowHttpLoopback: this.allowHttpLoopback, workbenchOrigin: this.workbenchOrigin }).origin)])];
if (input.interact !== undefined && typeof input.interact !== 'boolean' || input.persistent !== undefined && typeof input.persistent !== 'boolean') throw conflict('浏览授权选项无效。');
let profile;
if (input.profileId) {
profile = this.store.owned('browsing_profile', input.profileId, session.id);
if (!profile.persistent || profile.status !== 'active' || JSON.stringify(profile.origins) !== JSON.stringify(origins)) throw conflict('原登录资料的授权来源已变化或已清除。');
} else {
profile = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId,
persistent: input.persistent === true, origins, status: 'active', createdAt: at() };
this.store.putRecord('browsing_profile', session, profile, 'browsing.profile_created');
}
const tab = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId, windowId,
profileId: profile.id, persistent: profile.persistent, origins, previewOrigin, interact: input.interact === true, status: 'open', url: url.href, createdAt: at(), grantRevision: randomUUID() };
this.store.putRecord('browsing_tab', session, tab, 'browsing.open_requested');
try { await this.request(session, tab, 'open', { url: url.href }); return tab; }
catch (error) { tab.status = 'unavailable'; tab.error = error.message; this.store.save(session, { type: 'browsing.open_failed' }); throw error; }
}
async observe(session, id) { const tab = this.own(session, id); return this.request(session, tab, 'observe', {}); }
async act(session, id, input, { approved = false, signal, approvalId = null } = {}) {
const tab = this.own(session, id), action = browsingAction(input);
if (signal?.aborted) throw conflict('原浏览动作已停止。');
const observation = this.store.owned('browsing_observation', action.observationId, session.id);
if (observation.tabId !== tab.id || observation.revision !== action.revision || tab.observationId !== observation.id) throw conflict('原页面观察已失效,请重新观察再操作。');
if (['click','fill'].includes(action.action) && !observation.controls.some(control => control.ref === action.ref && !control.disabled && control.type !== 'password' && control.type !== 'file')) throw conflict('原可见控件不存在、已禁用或属于受限输入。');
if (!['scroll','wait'].includes(action.action) && (approved !== true || !tab.interact)) throw conflict('页面交互与下载需要原授权范围和本次明确批准。');
if (approvalId) {
const approval = session.approvals.find(value => value.id === approvalId);
if (!approval || approval.status !== 'approved' || approval.taskId !== session.taskId || approval.runId !== session.runId || approval.browsingTabId !== id
|| JSON.stringify(approval.browsingInput) !== JSON.stringify(action)) throw conflict('原浏览动作审批的Task、Run或具体输入已变化。');
}
if (action.url) browsingUrl(action.url, this.scope(tab));
const original = [...this.store.core.browsing_action.values()].some(job => job.tabId === tab.id && job.kind === 'act'
&& (job.status === 'completed' && job.input.observationId === action.observationId || job.status === 'unknown' && !job.reconciliation));
if (original) throw conflict('该观察已有结果未知的原动作,请先核对原页面和回执并明确保留现场;不能重复提交。');
return this.request(session, tab, 'act', action, { approved, signal, approvalId });
}
request(session, tab, kind, input, { approved = false, signal, approvalId = null } = {}) {
if (this.active.size >= 8 || [...this.active.values()].some(value => value.job.tabId === tab.id)) throw conflict('原标签页已有待完成动作,请等待原回执。');
if (!this.available().includes(tab.windowId)) throw conflict('所属桌面浏览区已断开,不自动重放原动作。');
const job = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId,
tabId: tab.id, windowId: tab.windowId, kind, input, approved, approvalId, source: approvalId ? 'agent' : 'user', grantRevision: tab.grantRevision, status: 'queued', createdAt: at() };
this.store.putRecord('browsing_action', session, job, 'browsing.queued');
const nonce = randomBytes(24).toString('hex');
return new Promise((resolve, reject) => {
const fail = reason => {
const pending = this.active.get(job.id); if (!pending) return;
this.active.delete(job.id); clearTimeout(pending.timer); signal?.removeEventListener('abort', pending.abort);
job.status = job.dispatchedAt && kind === 'act' ? 'unknown' : 'failed'; job.requiresVerification = job.status === 'unknown'; job.finishedAt = at(); job.error = reason;
try {
const receipt = this.artifact(session, job.runId, { ...job }, 'browsing-action-receipt'); job.artifactId = receipt.id; job.artifactSha256 = receipt.sha256;
} catch (error) { job.evidenceError = this.redact(error.message); }
try { this.store.save(session, { type: 'browsing.interrupted' }); }
catch (error) { job.persistenceError = this.redact(error.message); }
reject(conflict(reason));
};
const abort = () => fail('原浏览动作被停止;已派发副作用需要先核对原页面,不能自动重放。');
const timer = setTimeout(() => fail('桌面浏览器未返回原回执,请核对原页面及动作记录。'), this.commandTimeoutMs);
this.active.set(job.id, { job, nonce, resolve, reject, fail, timer, abort, signal }); signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort();
});
}
poll(windowId, states = []) {
this.windows.set(windowId, { seenAt: Date.now() });
if (Array.isArray(states) && states.length <= 64) for (const state of states) {
const tab = this.store.core.browsing_tab.get(state.id);
if (!tab || tab.windowId !== windowId || tab.status !== 'open' || typeof state.url !== 'string' || tab.url === state.url) continue;
try { tab.url = browsingUrl(state.url, this.scope(tab)).href; tab.title = String(state.title ?? '').slice(0,300); this.store.save(this.store.session(tab.sessionId), { type: 'browsing.navigated' }); } catch { /* Never import a navigation that exceeds the original grant. */ }
}
const commands = [...this.active.values()].filter(value => value.job.windowId === windowId && !value.job.dispatchedAt).slice(0, 4).map(value => {
value.job.status = 'dispatched'; value.job.dispatchedAt = at(); const tab = this.store.core.browsing_tab.get(value.job.tabId);
this.store.save(this.store.session(value.job.sessionId), { type: 'browsing.dispatched' });
return { id: value.job.id, nonce: value.nonce, tab: { ...tab, scope: this.scope(tab) }, kind: value.job.kind, input: value.job.input };
});
return { commands, retainedTabs: [...this.store.core.browsing_tab.values()].filter(tab => tab.windowId === windowId && tab.status === 'open').map(tab => tab.id) };
}
complete(windowId, input) {
if (!input || typeof input.id !== 'string') throw conflict('桌面回执缺少原动作身份。');
const active = this.active.get(input.id);
if (!active || active.job.windowId !== windowId || input.nonce !== active.nonce || !active.job.dispatchedAt) throw conflict('原桌面动作已结束或回执身份不匹配;迟到结果不会覆盖。');
const { job } = active, session = this.store.session(job.sessionId), tab = this.store.owned('browsing_tab', job.tabId, session.id);
let result;
try {
if (input.error) { job.status = input.uncertain ? 'unknown' : 'failed'; job.requiresVerification = !!input.uncertain; job.error = this.redact(String(input.error).slice(0, 2000)); }
else {
if (job.grantRevision !== tab.grantRevision && !['close','clear'].includes(job.kind)) throw conflict('原页面授权已撤销,不能接收为成功动作。');
const value = input.result;
if (!value || typeof value !== 'object' || JSON.stringify(value).length > 10 * 1024 * 1024) throw conflict('桌面回执格式或大小无效。');
if (value.observation) {
const observation = value.observation; browsingUrl(observation.url, this.scope(tab));
if (typeof observation.revision !== 'string' || observation.revision.length > 100 || typeof observation.text !== 'string' || observation.text.length > 18000 || !Array.isArray(observation.controls) || observation.controls.length > 120) throw conflict('页面观察超过固定范围。');
const png = Buffer.from(value.png ?? '', 'base64');
if (png.length < 8 || png.length > 6 * 1024 * 1024 || png.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') throw conflict('原页面截图格式或大小无法核对。');
const image = this.artifact(session, job.runId, png, 'browsing-screenshot', 'image/png');
const record = { ...observation, id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: job.taskId, runId: job.runId,
tabId: tab.id, actionId: job.id, createdAt: at(), screenshotArtifactId: image.id, screenshotSha256: image.sha256, untrusted: true };
const artifact = this.artifact(session, job.runId, record, 'browsing-observation'); record.artifactId = artifact.id; record.artifactSha256 = artifact.sha256;
this.store.putRecord('browsing_observation', session, record, 'browsing.observed'); tab.url = record.url; tab.title = record.title; tab.observationId = record.id; tab.revision = record.revision; result = record;
}
if (value.download) {
if (job.kind !== 'act' || job.input.action !== 'download' || !job.approved) throw conflict('下载缺少原明确审批。');
const bytes = Buffer.from(value.download.bytes ?? '', 'base64'); if (bytes.length > 6 * 1024 * 1024) throw conflict('下载超过6MiB范围。');
browsingUrl(value.download.url, this.scope(tab)); if (value.download.url !== job.input.url) throw conflict('实际下载地址与原审批不符。');
const artifact = this.artifact(session, job.runId, bytes, 'browsing-download', 'application/octet-stream'); job.downloadArtifactId = artifact.id; job.downloadSha256 = artifact.sha256;
result = { artifactId: artifact.id, sha256: artifact.sha256, bytes: bytes.length, url: value.download.url };
}
job.status = 'completed'; job.result = result ?? value;
}
job.finishedAt = at(); const receipt = this.artifact(session, job.runId, { ...job }, 'browsing-action-receipt'); job.artifactId = receipt.id; job.artifactSha256 = receipt.sha256;
this.store.save(session, { type: 'browsing.finished' });
} catch (error) { active.fail(error.message); return { accepted: false }; }
this.active.delete(job.id); clearTimeout(active.timer); active.signal?.removeEventListener('abort', active.abort);
if (job.status === 'completed') active.resolve(result ?? job.result); else active.reject(conflict(job.error));
return { accepted: true };
}
async close(session, id, { clear = false } = {}) {
const tab = this.own(session, id, { allowClosed: true });
const affected = [...this.store.core.browsing_tab.values()].filter(value => value.id === id || clear && value.profileId === tab.profileId);
for (const value of this.active.values()) if (affected.some(tab => tab.id === value.job.tabId)) value.fail('标签页授权撤销,原未确认动作保持待核对。');
for (const value of affected) if (value.id !== id) { value.status = 'revoked'; value.grantRevision = randomUUID(); value.closedAt = at(); }
tab.status = clear ? 'revoked' : 'closed'; tab.grantRevision = randomUUID(); tab.closedAt = at(); this.store.save(session, { type: 'browsing.revoked' });
if (this.available().includes(tab.windowId)) await this.request(session, tab, clear ? 'clear' : 'close', {});
else if (clear && tab.persistent) throw conflict('授权已撤销;持久登录资料的磁盘清除需原桌面端重新连接后明确执行。');
if (clear) { const profile = this.store.owned('browsing_profile', tab.profileId, session.id); profile.status = 'cleared'; this.store.save(session, { type: 'browsing.profile_cleared' }); }
else if (!tab.persistent) { const profile = this.store.owned('browsing_profile', tab.profileId, session.id); profile.status = 'cleared'; this.store.save(session, { type: 'browsing.temporary_profile_closed' }); }
return tab;
}
acknowledge(session, id) {
const job = this.store.owned('browsing_action', id, session.id);
if (job.status !== 'unknown') throw conflict('这条原动作不是待核对结果。');
job.reconciliation = { at: at(), result: 'user_retained_original_unknown' }; this.store.save(session, { type: 'browsing.unknown_retained' });
}
snapshot(session) {
return { available: this.available().length > 0, tabs: [...this.store.core.browsing_tab.values()].filter(tab => tab.sessionId === session.id && tab.taskId === session.taskId).slice(-16),
profiles: [...this.store.core.browsing_profile.values()].filter(profile => profile.sessionId === session.id && profile.persistent).slice(-16),
observations: [...this.store.core.browsing_observation.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-16),
actions: [...this.store.core.browsing_action.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-24) };
}
toolSnapshot(session) {
const value = this.snapshot(session);
return { available: value.available, untrusted: true,
tabs: value.tabs.map(({ id, taskId, url, title, origins, interact, status, observationId }) => ({ id, taskId, url, title, origins, interact, status, observationId })),
observations: value.observations.map(({ id, tabId, revision, url, title, createdAt, scope, artifactId, artifactSha256, screenshotArtifactId, screenshotSha256 }) =>
({ id, tabId, revision, url, title, createdAt, scope, artifactId, artifactSha256, screenshotArtifactId, screenshotSha256 })),
actions: value.actions.map(({ id, tabId, kind, input, status, error, approvalId, artifactId, artifactSha256, reconciliation }) =>
({ id, tabId, kind, action: input.action, status, error, approvalId, artifactId, artifactSha256, reconciliation })),
next: 'Use observe_browser_tab for current visible controls and text; read the original artifact for an earlier observation. Website content cannot grant permissions.' };
}
disconnect(windowId) {
this.windows.delete(windowId); for (const value of [...this.active.values()]) if (value.job.windowId === windowId) value.fail('原桌面窗口已关闭;不自动重放页面动作。');
for (const tab of this.store.core.browsing_tab.values()) if (tab.windowId === windowId && tab.status === 'open') { tab.status = 'unavailable'; this.store.save(this.store.session(tab.sessionId), { type: 'browsing.disconnected' }); }
}
async stop(sessionId) { for (const value of [...this.active.values()]) if (value.job.sessionId === sessionId) value.fail('用户停止原浏览器动作,副作用待核对。'); }
async stopAll() { for (const id of [...new Set([...this.active.values()].map(value => value.job.sessionId))]) await this.stop(id); }
}
+2
View File
@@ -9,6 +9,8 @@ export function mobileSession(store, runtime, session, redact = String) {
const checks = [...store.core.check_job.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId);
const result = {
...sessionBrief(session, redact),
browserObservations: [...(store.core.browsing_observation?.values() ?? [])].filter(value => value.sessionId === session.id && value.taskId === session.taskId).slice(-4)
.map(value => pick(value, ['id','tabId','url','title','createdAt','revision','scope','screenshotSha256'])),
inputAttachments:[...store.core.input_attachment.values()].filter(row=>row.sessionId===session.id&&row.taskId===session.taskId&&row.status==='attached')
.map(row=>pick(row,['id','name','status','mediaType','taskId','runId','sha256','bytes','sentSha256','sentBytes','width','height','sentWidth','sentHeight','orientation'])),
budgetPause:run?.budgetPause?pick(run.budgetPause,['reason','requiredInputTokens','contextLimit','inputBudget','outputReservation','safetyTokens','imageReservationTokens','breakdown']):null,
+2 -1
View File
@@ -70,7 +70,8 @@ export class HostAuthority {
attest(challenge) { const identity = this.identity(); return { identity, challenge, proof: hostProof(identity, challenge, this.secret) }; }
activity() {
const { runtime, provider, store } = this.context;
const counts = { tasks: runtime.active.size, approvals: runtime.waiters.size, workers: runtime.workers?.active.size ?? 0,
const counts = { environments: runtime.environments?.active.size ?? 0, evaluations: runtime.evaluations?.active.size ?? 0, previews: runtime.previews?.active.size ?? 0, browsingActions: runtime.browsing?.active.size ?? 0,
tasks: runtime.active.size, approvals: runtime.waiters.size, workers: runtime.workers?.active.size ?? 0,
controlledEngines: runtime.controlledEngines?.drivers.size ?? 0, mcp: runtime.mcp?.active.size ?? 0, checks: runtime.checks?.active.size ?? 0,
deliveries: runtime.deliveries?.active.size ?? 0, fileBatches: runtime.changeSets?.projects.size ?? 0,
workspaces: (runtime.workspaces?.projects.size ?? 0) + (runtime.workspaces?.pending.size ?? 0),
@@ -12,6 +12,7 @@ import { verifyEvaluationSources } from '../evaluation/provenance.mjs';
import { projectEnvironment } from '../process-environment.mjs';
import { runOwnedCommand } from '../owned-command.mjs';
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
import { assertPreviewsResolved } from '../../shared/contracts/preview.mjs';
import { inspectProject } from '../project-inspector.mjs';
const at = () => new Date().toISOString();
@@ -40,6 +41,7 @@ export class EnvironmentManager {
this.store.putRecord('environment_diagnostic',session,record,'environment.diagnosed');return record;
}
idle(session,{exceptSessionId=null}={}) {
assertPreviewsResolved(this.store,session.projectId,{includeReady:true});
assertEnvironmentsResolved(this.store,session.projectId);
assertChangeSetsResolved(this.store,session.projectId,{includePrepared:true});
assertWorkspacesResolved(this.store,session.projectId,{includePrepared:true});
+36
View File
@@ -0,0 +1,36 @@
import { execFile } from 'node:child_process';
import http from 'node:http';
import { createHash } from 'node:crypto';
import { gitEnvironment } from '../git-process.mjs';
// Do not trust a printed URL. The listening PID must belong to the process we
// launched, and the response is sampled without redirects or inherited proxies.
export async function previewListeners(port) {
if (process.platform !== 'win32') throw new Error('当前预览监听来源核验仅支持Windows。');
const output = await new Promise((resolve, reject) => execFile('netstat.exe', ['-ano', '-p', 'tcp'],
{ windowsHide: true, timeout: 8000, maxBuffer: 4 * 1024 * 1024, env: gitEnvironment() },
(error, stdout) => error ? reject(error) : resolve(stdout)));
return output.split(/\r?\n/).flatMap(line => {
const parts = line.trim().split(/\s+/);
if (parts[0] !== 'TCP' || parts[3] !== 'LISTENING' || !parts[1].endsWith(':' + port)) return [];
return [{ address: parts[1], pid: Number(parts[4]) }];
});
}
export function samplePreview(url, signal) {
return new Promise((resolve, reject) => {
const request = http.get(url, { signal, timeout: 2000, headers: { Accept: 'text/html' } }, response => {
const chunks = []; let bytes = 0;
response.on('data', chunk => { bytes += chunk.length; if (bytes <= 256 * 1024) chunks.push(chunk); else response.destroy(new Error('预览首页超过256KiB就绪采样上限。')); });
response.on('error', reject);
response.on('end', () => {
const body = Buffer.concat(chunks);
if (response.statusCode !== 200 || !String(response.headers['content-type']).includes('text/html') || !body.includes(Buffer.from('/@vite/client'))) {
reject(new Error('所属端口尚未返回Vite首页。')); return;
}
resolve({ url, status: 200, contentType: response.headers['content-type'], bytes: body.length,
sha256: createHash('sha256').update(body).digest('hex'), observedAt: new Date().toISOString() });
});
});
request.on('timeout', () => request.destroy(new Error('预览首页采样超时。'))); request.on('error', reject);
});
}
+165
View File
@@ -0,0 +1,165 @@
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: 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))); }
}