fix: add web project folder picker and isolated HTML file previews

This commit is contained in:
Agent Workbench Dev
2026-11-02 08:54:31 +08:00
parent bfd2f213a5
commit 70ac4c40b5
28 changed files with 515 additions and 20 deletions
+18 -1
View File
@@ -18,6 +18,7 @@ import { companionGateway } from './companion-gateway.mjs';
import { inspectOperations } from './operations.mjs';
import { validateModelWaitSettings } from '../core/models/request-deadline.mjs';
import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs';
import { localDirectories } from './local-directories.mjs';
export function createSessionPublisher(clients) {
return session => {
@@ -80,7 +81,7 @@ return async (request, response) => {
response.setHeader('X-Frame-Options', 'DENY');
// Scripts and API requests belong to this workbench origin. Inline styles
// are limited to the existing React layout; model text never becomes HTML.
response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
const actualPort = getPort();
if (server && (!server.listening || server.address().port !== actualPort)) throw new Error('本地执行宿主已经变化,请重新连接工作台。');
const url = new URL(request.url, 'http://127.0.0.1:' + actualPort);
@@ -285,6 +286,22 @@ return async (request, response) => {
}
return json(response, runtime.projectIndexer().status(project));
}
if (method === 'GET' && route === '/api/local-directories') return json(response, await localDirectories(url.searchParams.get('path') || ''));
if (method === 'GET' && route === '/api/local-file-preview-access') return json(response, runtime.filePreviews?.access(url.searchParams.get('url') || '') || { allowed: false });
const filePreview = route.match(/^\/api\/projects\/([a-f0-9-]+)\/file-previews(?:\/([a-f0-9-]+))?$/);
if (filePreview) {
const project = store.project(filePreview[1]);
if (method === 'POST' && !filePreview[2]) {
const input = await body(request);
if (Object.keys(input).some(key => key !== 'path')) throw new Error('文件预览只接受项目相对路径。');
return json(response, await runtime.localFilePreviews().start(project, input.path), 201);
}
if (method === 'DELETE' && filePreview[2]) {
const input = await body(request);
if (Object.keys(input).length) throw new Error('关闭预览不接受额外字段。');
return json(response, runtime.filePreviews ? await runtime.filePreviews.close(project.id, filePreview[2]) : { closed: true });
}
}
const projectMatch = route.match(/^\/api\/projects\/([a-f0-9-]+)\/(files|file|inspection|code-index|code-query)$/);
if (method === 'GET' && projectMatch) {
const project = store.project(projectMatch[1]);
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.22.0';
export const APP_VERSION = '1.22.1';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+4 -2
View File
@@ -19,6 +19,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
if (server.workbenchHostAuthority?.stopping) throw new Error('Wait for the original host stop operation before upgrading.');
if (server.workbenchCompanion?.server || server.workbenchCompanion?.busy) throw new Error('Close the mobile companion gateway before upgrading; original tasks remain on the host.');
if (server.workbenchHostAuthority?.desktopWindows?.().count) throw new Error('Close the registered desktop windows before upgrading; the execution host remains running.');
if (runtime.filePreviews?.active.size || runtime.filePreviews?.pending) throw new Error('Close local HTML previews before upgrading.');
if (runtime.browsing?.active.size || runtime.previews?.active.size || runtime.evaluations?.active.size || runtime.environments?.active.size || runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active evaluations, environments, tasks, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.');
if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes before upgrading.');
const root = fs.realpathSync.native(path.resolve(appDirectory));
@@ -32,7 +33,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
importer: provider.hub?.importer ? Object.getPrototypeOf(provider.hub.importer) : null,
vault: provider.hub?.credentialVault ? Object.getPrototypeOf(provider.hub.credentialVault) : null };
const oldStoreProperties = { ...store };
const oldRuntimeProperties = { browsing: runtime.browsing, previews: runtime.previews, evaluations:runtime.evaluations, environments: runtime.environments, appDirectory: runtime.appDirectory, workers: runtime.workers, controlledEngines: runtime.controlledEngines, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
const oldRuntimeProperties = { filePreviews: runtime.filePreviews, browsing: runtime.browsing, previews: runtime.previews, evaluations:runtime.evaluations, environments: runtime.environments, appDirectory: runtime.appDirectory, workers: runtime.workers, controlledEngines: runtime.controlledEngines, checks: runtime.checks, deliveries: runtime.deliveries, codeIndex: runtime.codeIndex, changeSets: runtime.changeSets, contextPlans: runtime.contextPlans, workspaces: runtime.workspaces, research: runtime.research, engines: runtime.engines, browser: runtime.browser, taskPlans: runtime.taskPlans, projectMemories: runtime.projectMemories, taskCheckpoints: runtime.taskCheckpoints, skills: runtime.skills, mcp: runtime.mcp };
const oldUpdates = store.listeners('update');
const oldInputs = runtime.inputs;
const oldResumes = runtime.resumes;
@@ -49,7 +50,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
if (provider.hub.importer) Object.setPrototypeOf(provider.hub.importer, ConfigImporter.prototype);
if (provider.hub.credentialVault) Object.setPrototypeOf(provider.hub.credentialVault, CredentialVault.prototype);
}
runtime.appDirectory = root; runtime.previews = null; runtime.browsing = null; runtime.evaluations = null; runtime.environments = null; runtime.workers = null; runtime.controlledEngines = null; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
runtime.filePreviews = null; runtime.appDirectory = root; runtime.previews = null; runtime.browsing = null; runtime.evaluations = null; runtime.environments = null; runtime.workers = null; runtime.controlledEngines = null; runtime.checks = null; runtime.deliveries = null; runtime.codeIndex = null; runtime.changeSets = null; runtime.contextPlans = null; runtime.workspaces = null; runtime.research = null; runtime.engines = null; runtime.browser = null; runtime.taskPlans = null; runtime.projectMemories = null; runtime.taskCheckpoints = null; runtime.skills = null; runtime.mcp = null;
delete server.workbenchCompanion;
runtime.inputs = null;
runtime.resumes = null;
@@ -66,6 +67,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true
const authority = hostAuthority({ appDirectory: root, server, store, provider, runtime });
authority.initialize(); authority.refreshInstallation();
}
void oldRuntimeProperties.filePreviews?.stopAll();
return { version: APP_VERSION, pid: process.pid, hasKey: provider.hasKey(), projects: store.projects.length, sessions: store.sessions.size, appDirectory: root };
} catch (error) {
if (oldCompanion) server.workbenchCompanion = oldCompanion; else delete server.workbenchCompanion;
+35
View File
@@ -0,0 +1,35 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
const privateDirectory = /^(\.git|\.ssh|\.aws|\.azure|\.secrets|\.desktop-profile|System Volume Information|\$RECYCLE\.BIN)$/i;
const fail = message => Object.assign(new Error(message), { status: 400 });
// This user-facing, authenticated picker reads one directory at a time. It
// neither recursively scans the machine nor exposes a model filesystem tool.
export async function localDirectories(input = '') {
if (typeof input !== 'string' || input.length > 2000 || /[\x00-\x1f]/.test(input)) throw fail('文件夹路径无效。');
const requested = input || os.homedir();
if (!path.isAbsolute(requested) || process.platform === 'win32' && !/^[a-z]:[\\/]/i.test(requested)) throw fail('请输入本机文件夹的完整路径。');
let current;
try {
current = await fs.realpath(requested);
if (!(await fs.stat(current)).isDirectory()) throw fail('请选择文件夹。');
} catch (cause) { throw fail(cause.code === 'EACCES' || cause.code === 'EPERM' ? '没有权限打开此文件夹,请选择其他位置。' : '文件夹不存在或无法访问,请检查路径。'); }
const directories = [];
let scanned = 0, truncated = false;
try {
const directory = await fs.opendir(current);
for await (const entry of directory) {
if (++scanned > 4000 || directories.length >= 1000) { truncated = true; break; }
if (!entry.isDirectory() || entry.isSymbolicLink() || privateDirectory.test(entry.name)) continue;
directories.push({ name: entry.name, path: path.join(current, entry.name) });
}
} catch { throw fail('无法列出此文件夹,请选择其他位置或直接输入路径。'); }
directories.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN', { numeric: true }));
const candidates = [{ name: '用户文件夹', path: os.homedir() }, ...['Desktop', 'Documents', 'Downloads'].map((name, index) => ({ name: ['桌面', '文档', '下载'][index], path: path.join(os.homedir(), name) }))];
if (process.platform === 'win32') for (const drive of 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') candidates.push({ name: drive + ':', path: drive + ':\\' });
else candidates.push({ name: '文件系统', path: '/' });
const bookmarks = (await Promise.all(candidates.map(async item => { try { return (await fs.stat(item.path)).isDirectory() ? item : null; } catch { return null; } }))).filter(Boolean);
return { current, parent: path.dirname(current) === current ? null : path.dirname(current), directories, bookmarks, truncated };
}
+3 -1
View File
@@ -1,4 +1,5 @@
import { PreviewManager } from '../core/preview/preview-manager.mjs';
import { LocalFilePreviews } from '../core/preview/local-file-preview.mjs';
import { BrowsingManager } from '../core/browser/browsing-manager.mjs';
import { browsingToolDefinitions, browsingAction } from '../shared/contracts/browsing.mjs';
import { publicEnvironmentDiagnostic } from '../core/environment/environment-manager.mjs';
@@ -132,6 +133,7 @@ export class Runtime {
redact: value => this.provider.redact(value), projectBusy: (projectId, exceptId) => this.projectHasActivity(projectId, exceptId) }); }
previewManager() { return this.previews ??= new PreviewManager(this.store, { runtimeDirectory: this.appDirectory ? path.join(this.appDirectory, 'runtime') : null,
redact: value => this.provider.redact(value), projectBusy: projectId => this.projectHasActivity(projectId) }); }
localFilePreviews() { return this.filePreviews ??= new LocalFilePreviews(this.store); }
browsingManager() { return this.browsing ??= new BrowsingManager(this.store, { redact: value => this.provider.redact(value), workbenchOrigin: this.workbenchOrigin }); }
engineManager() {
return this.engines ??= new EngineManager(this.store, { appDirectory: this.appDirectory,
@@ -794,5 +796,5 @@ export class Runtime {
run.controller.abort(new Error('用户停止任务'));
await run.promise;
}
async stopAll() { await this.browsing?.stopAll(); await this.previews?.stopAll(); await this.evaluations?.stopAll(); await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.controlledEngines?.stopAll(); await this.environments?.stopAll(); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.mcp?.stopAll(); await this.taskPlans?.settle(); }
async stopAll() { await this.filePreviews?.stopAll(); await this.browsing?.stopAll(); await this.previews?.stopAll(); await this.evaluations?.stopAll(); await this.workers?.stopAll(); await Promise.all([...this.active.keys()].map(id => this.stop(id))); await this.controlledEngines?.stopAll(); await this.environments?.stopAll(); await this.checks?.stopAll(); await this.deliveries?.stopAll(); await this.changeSets?.stopAll(); await this.workspaces?.stopAll(); await this.research?.stopAll(); await this.engines?.stopAll(); await this.browser?.stopAll(); await this.mcp?.stopAll(); await this.taskPlans?.settle(); }
}