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
+13 -5
View File
@@ -1,4 +1,6 @@
import { EmbeddedBrowserPanel } from './EmbeddedBrowserPanel';
import { ProjectDirectoryPicker } from './ProjectDirectoryPicker';
import { HtmlFilePreview } from './HtmlFilePreview';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Activity, Brain, ClipboardCheck, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Puzzle, Search, Server as ModelServer, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react';
import type { Bootstrap, Change, Config, ModelSelection, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types';
@@ -46,6 +48,7 @@ export default function App() {
const [filter, setFilter] = useState('');
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
const [openFile, setOpenFile] = useState<OpenFile | null>(null);
const [fileMode, setFileMode] = useState<'source' | 'preview'>('source');
const [fileLoading, setFileLoading] = useState(false);
const [fileLine, setFileLine] = useState<number | null>(null);
const [fileNotice, setFileNotice] = useState('');
@@ -78,6 +81,9 @@ export default function App() {
const [settingsBusy, setSettingsBusy] = useState(false);
const [projectOpen, setProjectOpen] = useState(false);
const [projectInput, setProjectInput] = useState('');
const [directoryPickerOpen, setDirectoryPickerOpen] = useState(false);
const [projectBusy, setProjectBusy] = useState(false);
const [projectError, setProjectError] = useState('');
const [toast, setToast] = useState('');
const [researchOpen, setResearchOpen] = useState(false);
const [reaOpen, setReaOpen] = useState(false);
@@ -270,13 +276,15 @@ export default function App() {
finally { setSending(false); }
}
async function openProject() {
if (!projectInput.trim()) return;
if (!projectInput.trim() || projectBusy) return;
setProjectBusy(true); setProjectError('');
try {
const project = await api<Project>('/projects', { root: projectInput.trim() });
setProjects(previous => [project, ...previous.filter(item => item.id !== project.id)]);
await chooseProject(project.id); setProjectOpen(false); setProjectInput('');
notify('已打开项目 ' + project.name);
} catch (error) { failure(error); }
} catch (error) { setProjectError(error instanceof Error ? error.message : '打开项目失败。'); }
finally { setProjectBusy(false); }
}
async function acceptDesktopProject(project: Project) {
setProjects(previous => [project, ...previous.filter(item => item.id !== project.id)]);
@@ -295,7 +303,7 @@ export default function App() {
try {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(relative));
if (fileRequest.current === request && selectedProjectRef.current === targetProject) {
setOpenFile(file); setDraft(file.content);
setOpenFile(file); setDraft(file.content); setFileMode(!location && /\.html?$/i.test(file.path) ? 'preview' : 'source');
if (location && file.sha256 !== location.expectedSha256) setFileNotice('文件在索引后已变化,已打开当前内容。请回到索引刷新后重新定位。');
else if (location && location.line >= 1 && location.line <= file.content.split('\n').length) setFileLine(location.line);
}
@@ -608,7 +616,7 @@ export default function App() {
onDoubleClick={()=>setInspectorWidth(null)}
onKeyDown={event=>{const width=event.currentTarget.parentElement!.getBoundingClientRect().width;if(event.key==='ArrowLeft'||event.key==='ArrowRight'){event.preventDefault();resizeInspector(width+(event.key==='ArrowLeft'?32:-32));}else if(event.key==='Home'){event.preventDefault();resizeInspector(310);}else if(event.key==='End'){event.preventDefault();resizeInspector(maximumInspector);}}}/>}
<div className="inspector-tabs"><button className={tab === 'file' ? 'selected' : ''} onClick={() => setTab('file')}><FileCode2 size={14} />文件</button><button className={tab === 'changes' ? 'selected' : ''} onClick={() => setTab('changes')}><GitBranch size={14} />改动{pending.length > 0 && <b>{pending.length}</b>}</button><button className={tab === 'trace' ? 'selected' : ''} onClick={() => setTab('trace')}><SquareTerminal size={14} />轨迹</button><button className={tab === 'task' ? 'selected' : ''} onClick={() => setTab('task')}><ClipboardCheck size={14} />任务</button><button className={tab === 'index' ? 'selected' : ''} onClick={() => setTab('index')}><Search size={14} />索引</button><button className={tab === 'browse' ? 'selected' : ''} onClick={() => setTab('browse')}><Link2 size={14} />浏览</button><IconButton label={narrow ? '关闭检视区' : wide ? '缩小检视区' : '放大检视区'} onClick={() => setWide(previous => !previous)}>{narrow ? <X size={16} /> : wide ? <Minimize2 size={14} /> : <Maximize2 size={14} />}</IconButton></div>
{tab === 'file' && (fileLoading ? <div className="loading-inspector"><LoaderCircle className="spin" size={24} />正在读取文件</div> : openFile ? <div className="file-inspector"><div className="file-heading"><FileCode2 size={15} /><span title={openFile.path}>{openFile.path}</span><IconButton label="复制文件内容" onClick={() => navigator.clipboard.writeText(openFile.content).then(() => notify('已复制文件内容。')).catch(failure)}><Copy size={14} /></IconButton><IconButton label={editing ? '取消编辑' : '编辑文件'} onClick={() => { setEditing(previous => !previous); setDraft(openFile.content); }}><Pencil size={14} /></IconButton></div><div className="file-details"><span>{lineCount} 行 · {openFile.bytes.toLocaleString()} B{fileLine ? ' · 定位第 ' + fileLine + ' 行' : ''}</span><span className="code-utility">{openFile.sha256.slice(0, 10)}</span></div>{fileNotice && <div className="file-index-notice" role="status">{fileNotice}</div>}{editing ? <><textarea className="code-editor" aria-label="编辑文件内容" spellCheck={false} value={draft} onChange={event => setDraft(event.target.value)} /><div className="editor-actions"><button className="button primary" onClick={saveDraft} disabled={draft === openFile.content || draftSaving}><GitBranch size={14} />保存为提案</button></div></> : <div className="code-view" ref={codeViewRef}>{openFile.content.split('\n').map((line, index) => <div key={index} data-line={index + 1} className={fileLine === index + 1 ? 'code-line-target' : ''}><span>{index + 1}</span><code>{line.replace(/\r$/, '') || ' '}</code></div>)}</div>}</div> : <EmptyInspector kind="file" />)}
{tab === 'file' && (fileLoading ? <div className="loading-inspector"><LoaderCircle className="spin" size={24} />正在读取文件</div> : openFile ? <div className="file-inspector"><div className="file-heading"><FileCode2 size={15} /><span title={openFile.path}>{openFile.path}</span>{/\.html?$/i.test(openFile.path) && <div className="file-mode-switch" role="group" aria-label="文件显示方式"><button type="button" aria-pressed={fileMode === 'preview'} disabled={editing} onClick={() => setFileMode('preview')}>预览</button><button type="button" aria-pressed={fileMode === 'source'} onClick={() => { setFileMode('source'); setEditing(false); }}>源码</button></div>}<IconButton label="复制文件内容" onClick={() => navigator.clipboard.writeText(openFile.content).then(() => notify('已复制文件内容。')).catch(failure)}><Copy size={14} /></IconButton><IconButton label={editing ? '取消编辑' : '编辑文件'} onClick={() => { setFileMode('source'); setEditing(previous => !previous); setDraft(openFile.content); }}><Pencil size={14} /></IconButton></div><div className="file-details"><span>{lineCount} 行 · {openFile.bytes.toLocaleString()} B{fileLine ? ' · 定位第 ' + fileLine + ' 行' : ''}</span><span className="code-utility">{openFile.sha256.slice(0, 10)}</span></div>{fileNotice && <div className="file-index-notice" role="status">{fileNotice}</div>}{editing ? <><textarea className="code-editor" aria-label="编辑文件内容" spellCheck={false} value={draft} onChange={event => setDraft(event.target.value)} /><div className="editor-actions"><button className="button primary" onClick={saveDraft} disabled={draft === openFile.content || draftSaving}><GitBranch size={14} />保存为提案</button></div></> : fileMode === 'preview' && /\.html?$/i.test(openFile.path) ? <HtmlFilePreview key={projectId + ':' + openFile.path} projectId={projectId} path={openFile.path} /> : <div className="code-view" ref={codeViewRef}>{openFile.content.split('\n').map((line, index) => <div key={index} data-line={index + 1} className={fileLine === index + 1 ? 'code-line-target' : ''}><span>{index + 1}</span><code>{line.replace(/\r$/, '') || ' '}</code></div>)}</div>}</div> : <EmptyInspector kind="file" />)}
{tab === 'changes' && (session ? <ChangesInspector session={session} selectedChange={selectedChange} busy={!!changeBusy} isRunning={isRunning} onSelect={setChangeId} onAction={changeAction} onSession={acceptSession} onError={failureFor(session)} onFilesChanged={refreshBatchFiles} /> : <EmptyInspector kind="changes" />)}
{tab === 'trace' && (session?.events.length ? <div className="trace-inspector"><div className="trace-caption"><span>完整执行记录</span><span>{toolEvents.length} 次工具调用</span></div><div className="trace-list">{session.events.map(event => <ToolRow key={event.id} event={event} selected={selectedEvent?.id === event.id} onSelect={() => setEventId(event.id)} />)}</div>{selectedEvent && <div className="event-details"><div className="event-detail-heading"><strong>{selectedEvent.label}</strong><Status value={selectedEvent.phase} /></div>{selectedEvent.input && <><h4>输入</h4><pre>{JSON.stringify(selectedEvent.input, null, 2)}</pre></>}<h4>结果</h4><pre>{selectedEvent.output || (selectedEvent.phase === 'waiting' ? '等待确认后执行。' : '正在等待工具结果。')}</pre>{selectedEvent.durationMs !== undefined && <p className="subtle">耗时 {(selectedEvent.durationMs / 1000).toFixed(2)} 秒,包含确认等待。</p>}</div>}</div> : <EmptyInspector kind="trace" />)}
{tab === 'task' && (session && selectedProject ? <TaskPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} onWorkspaceRefresh={refreshWorkspaceState} onWorkspaceNavigate={navigateWorkspace} onOpenPreview={()=>showInspector('browse')} /> : <EmptyInspector kind="trace" />)}
@@ -616,7 +624,7 @@ export default function App() {
{selectedProject && <CodeIndexPanel key={selectedProject.id} project={selectedProject} active={tab === 'index'} onOpen={(path, line, expectedSha256) => void loadFile(path, { line, expectedSha256 })} />}
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}</span></div>
</aside>
{projectOpen && <Modal title="打开项目" description="选择要在本机读取和开发的项目文件夹。" onClose={() => setProjectOpen(false)}><form onSubmit={event => { event.preventDefault(); openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} onChange={event => setProjectInput(event.target.value)} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label><div className="modal-actions">{desktop && <button type="button" className="button secondary" disabled={pickingProject} onClick={() => void pickDesktopProject()}>选择文件夹</button>}{exampleId && <button type="button" className="button secondary" onClick={() => { chooseProject(exampleId); setProjectOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim()}><FolderOpen size={15} />打开项目</button></div></form></Modal>}
{projectOpen && <Modal title="打开项目" description="选择这台电脑上的项目文件夹,或输入完整路径。" onClose={() => { if (!projectBusy) { setProjectOpen(false); setDirectoryPickerOpen(false); setProjectError(''); } }}><form onSubmit={event => { event.preventDefault(); if (!directoryPickerOpen) void openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} disabled={projectBusy} onChange={event => { setProjectInput(event.target.value); setProjectError(''); }} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label>{projectError && <p className="local-files-error" role="alert">{projectError}</p>}{directoryPickerOpen && <ProjectDirectoryPicker initialPath={projectInput.trim()} onChoose={value => { setProjectInput(value); setProjectError(''); setDirectoryPickerOpen(false); }} onCancel={() => setDirectoryPickerOpen(false)} />}<div className="modal-actions"><button type="button" className="button secondary" disabled={pickingProject || projectBusy} onClick={() => desktop ? void pickDesktopProject() : setDirectoryPickerOpen(value => !value)}><FolderOpen size={15} />选择文件夹</button>{exampleId && <button type="button" className="button secondary" disabled={projectBusy} onClick={() => { chooseProject(exampleId); setProjectOpen(false); setDirectoryPickerOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim() || projectBusy || directoryPickerOpen}>{projectBusy ? <LoaderCircle className="spin" size={15} /> : <FolderOpen size={15} />}{projectBusy ? '正在打开…' : '打开项目'}</button></div></form></Modal>}
{companionOpen && <Modal title="手机连接" description="指定项目和权限,连接到同一个Windows执行宿主。" onClose={() => setCompanionOpen(false)} wide><CompanionPanel projects={projects} selectedProjectId={selectedProject?.id ?? ''} /></Modal>}
{desktopOpen && desktop && <Modal title="桌面与后台任务" description="当前窗口连接同一个本机执行宿主。" onClose={() => setDesktopOpen(false)}><DesktopPanel project={selectedProject} session={session} file={openFile} onProject={acceptDesktopProject} onReview={scope => { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} /></Modal>}
{settingsOpen && <Modal title="模型连接" description="同一套项目工具,可以使用离线演示或你自己的模型服务。" onClose={() => setSettingsOpen(false)}><form onSubmit={event => { event.preventDefault(); saveSettings(); }}><div className="mode-picker"><button type="button" className={settings.mode === 'demo' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'demo' }))}><Play size={18} /><strong>离线演示</strong><span>固定脚本,真实本地工具</span></button><button type="button" className={settings.mode === 'compatible' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'compatible' }))}><Link2 size={18} /><strong>兼容模型服务</strong><span>使用自己的本地或远程模型</span></button></div>
+1 -1
View File
@@ -37,7 +37,7 @@ export function EmbeddedBrowserPanel({project,session,onSession,onError,onReturn
<div className="browser-source"><span>{project.name} · Task {tab.taskId.slice(0,8)}</span><span>{labels[tab.status]??tab.status}</span></div></>}
{failure&&<p role="alert" className="browser-inline-error">{failure}</p>}
{!snapshot?.available&&<p className="browser-inline-note">桌面浏览器未连接。请打开本工作台桌面端;网页端仍可核对已有观察和原动作。</p>}
{tab?.status==='open'&&desktop?.browsingLayout?<div className="native-browser-slot" ref={view}><Globe2 size={28}/><p>所属网页在此区域显示</p></div>:image?<figure className="browser-saved-image"><img src={image} alt="所属标签页原观察截图"/><figcaption>原页面观察 · {observation?new Date(observation.createdAt).toLocaleString('zh-CN'):''}</figcaption></figure>:<div className="browser-empty"><Globe2 size={30}/><h3>在任务旁核对真实页面</h3><p>先启动所属项目预览,或明确授权一个网站。所有页面观察与动作保存在本任务中。</p></div>}
{tab?.status==='open'&&desktop?.browsingLayout?<div className="native-browser-slot" ref={view}><Globe2 size={28}/><p>所属网页在此区域显示</p></div>:image?<figure className="browser-saved-image"><img src={image} alt="所属标签页原观察截图"/><figcaption>原页面观察 · {observation?new Date(observation.createdAt).toLocaleString('zh-CN'):''}</figcaption></figure>:<div className="browser-empty"><Globe2 size={30}/><h3>在任务旁核对真实页面</h3><p>普通 HTML 可从左侧文件列表直接打开预览。需要运行的应用先启动项目预览,网站请从「打开目标」授权。页面观察与动作保存在本任务中。</p></div>}
{imageError&&<p role="alert" className="browser-inline-error">{imageError}</p>}
{tab&&<div className="browser-evidence"><div className="browser-evidence-heading"><strong>页面观察与原动作</strong><button type="button" className="text-button" disabled={!!working||tab.status!=='open'||!snapshot?.available} onClick={()=>perform('browsing/tabs/'+tab.id+'/observe')}><Camera size={14}/>重新观察</button></div>
{observation&&<><p className="browser-evidence-stamp"><ShieldCheck size={13}/>{image?'原截图 SHA-256 已核对':imageError?'原截图核对未通过':'正在核对原截图'} · {new Date(observation.createdAt).toLocaleTimeString('zh-CN')}{!observation.scope.complete?' · 有界采样,未覆盖全部内容':''}</p><code className="browser-sha">{observation.screenshotSha256}</code>
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from 'react';
import { ExternalLink, LoaderCircle, RotateCw } from 'lucide-react';
import { api } from './api';
import { desktop } from './desktop';
import './LocalFiles.css';
type Preview = { id: string; url: string; projectId: string; path: string };
export function HtmlFilePreview({ projectId, path }: { projectId: string; path: string }) {
const [preview, setPreview] = useState<Preview | null>(null), [error, setError] = useState(''), [attempt, setAttempt] = useState(0), [loaded, setLoaded] = useState(false);
useEffect(() => {
let current = true, owned: Preview | null = null;
const close = (value: Preview) => api('/projects/' + projectId + '/file-previews/' + value.id, {}, 'DELETE').catch(() => {});
setPreview(null); setError(''); setLoaded(false);
void api<Preview>('/projects/' + projectId + '/file-previews', { path }).then(value => {
if (current) { owned = value; setPreview(value); } else void close(value);
}).catch(cause => { if (current) setError(cause instanceof Error ? cause.message : '无法打开 HTML 预览。'); });
return () => { current = false; if (owned) void close(owned); };
}, [projectId, path, attempt]);
return <div className="html-file-preview">
<div className="html-preview-toolbar"><span>HTML 文件预览</span><button type="button" className="button secondary" onClick={() => setAttempt(value => value + 1)}><RotateCw size={14} />刷新预览</button>{preview && (desktop?.openFilePreview ? <button type="button" className="button secondary" onClick={() => void desktop!.openFilePreview!({ projectId, url: preview.url }).catch(cause => setError(cause.message))}><ExternalLink size={14} />在浏览器打开</button> : <a className="button secondary" href={preview.url} target="_blank" rel="noopener noreferrer"><ExternalLink size={14} />独立页面</a>)}</div>
{error ? <div className="html-preview-message" role="alert"><p>{error}</p><button className="button secondary" onClick={() => setAttempt(value => value + 1)}>重试预览</button></div> : <>{!loaded && <div className="html-preview-message" role="status"><LoaderCircle size={17} className="spin" />正在打开 HTML 页面…</div>}{preview && <iframe key={preview.id} title={'HTML 预览:' + path} src={preview.url} sandbox="allow-scripts" referrerPolicy="no-referrer" onLoad={() => setLoaded(true)} onError={() => setError('页面加载失败,请刷新预览后重试。')} />}</>}
<p className="html-preview-note">直接读取已保存文件,支持页面脚本与相对资源。需要后端或构建的应用请启动项目预览。</p>
</div>;
}
+1
View File
@@ -0,0 +1 @@
.directory-picker{border:1px solid #d3dfd9;border-radius:8px;background:#fff;margin:14px 0;overflow:hidden}.directory-location{display:flex;align-items:center;gap:6px;padding:10px;border-bottom:1px solid #dfe7e2}.directory-location input{min-width:0;flex:1;border:1px solid #c4d2ca;border-radius:5px;padding:9px;font-size:12px;background:#fff;color:#294a3c}.directory-location .button{padding:0 10px}.directory-bookmarks{display:flex;flex-wrap:wrap;gap:5px;padding:9px 12px;background:#f4f7f5}.directory-bookmarks button{padding:6px 9px;border:1px solid #d4dfd8;border-radius:4px;color:#345b48;font-size:12px;background:#fff}.directory-filter{display:block;width:calc(100% - 24px);margin:10px 12px;padding:9px;border:1px solid #c4d2ca;border-radius:5px;background:#fff;color:#294a3c;font-size:12px}.directory-list{height:235px;overflow:auto;padding:0 8px 8px}.directory-list>button{display:flex;align-items:center;gap:9px;width:100%;padding:10px 8px;text-align:left;border-radius:4px;font-size:13px;color:#2f5140}.directory-list>button:hover,.directory-list>button:focus-visible{background:#e9f0ec}.directory-list>button>span{overflow-wrap:anywhere}.directory-list>p{display:flex;align-items:center;justify-content:center;gap:8px;padding:30px 10px;font-size:12px;color:#526b5d}.directory-selection{border-top:1px solid #dfe7e2;padding:12px;display:grid;gap:12px}.directory-selection>span{font-size:12px;overflow-wrap:anywhere;line-height:1.6}.directory-selection>div{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:8px}.local-files-error{font-size:12px;color:#9a352d;background:#fff2ee;padding:10px 12px;line-height:1.6}.file-mode-switch{display:flex;gap:4px;margin-left:auto}.file-mode-switch button{padding:6px 9px;border-radius:4px;color:#456151;font-size:12px}.file-mode-switch button[aria-pressed=true]{background:#e3ece6;color:#214c37;font-weight:600}.file-mode-switch button:disabled{opacity:.5}.html-file-preview{display:flex;flex:1;min-height:0;flex-direction:column;position:relative;background:#fff}.html-preview-toolbar{display:flex;flex-wrap:wrap;align-items:center;gap:7px;padding:10px;border-bottom:1px solid #dfe7e2;flex-shrink:0}.html-preview-toolbar>span{font-size:11px;color:#536b5c;margin-right:auto}.html-preview-toolbar .button{height:30px;padding:0 9px;font-size:11px;text-decoration:none}.html-file-preview iframe{border:0;width:100%;min-height:200px;flex:1;background:#fff}.html-preview-message{display:flex;align-items:center;justify-content:center;gap:9px;padding:24px;font-size:12px;color:#3e5b4c;line-height:1.7}.html-preview-note{margin:0;padding:9px 12px;font-size:11px;line-height:1.6;color:#536b5c;border-top:1px solid #dfe7e2;background:#f4f7f5;flex-shrink:0}.file-heading:has(.file-mode-switch){flex-wrap:wrap}.file-heading:has(.file-mode-switch)>span{min-width:90px}@media(max-width:620px){.directory-list{height:190px}.directory-picker button,.file-mode-switch button{min-height:40px}.directory-location{padding:7px;gap:3px}.directory-location .button{padding:0 7px}.html-preview-toolbar .button{min-height:38px}.html-preview-toolbar>span{width:100%}}
+30
View File
@@ -0,0 +1,30 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowUp, Folder, LoaderCircle, RotateCw } from 'lucide-react';
import { api } from './api';
import './LocalFiles.css';
type Directory = { name: string; path: string };
type Listing = { current: string; parent: string | null; directories: Directory[]; bookmarks: Directory[]; truncated: boolean };
export function ProjectDirectoryPicker({ initialPath, onChoose, onCancel }: { initialPath: string; onChoose(path: string): void; onCancel(): void }) {
const [listing, setListing] = useState<Listing | null>(null), [busy, setBusy] = useState(true), [error, setError] = useState('');
const [location, setLocation] = useState(initialPath), [filter, setFilter] = useState('');
const request = useRef(0);
async function browse(path: string) {
const sequence = ++request.current; setBusy(true); setError('');
try {
const value = await api<Listing>('/local-directories?path=' + encodeURIComponent(path));
if (sequence === request.current) { setListing(value); setLocation(value.current); setFilter(''); }
} catch (cause) { if (sequence === request.current) setError(cause instanceof Error ? cause.message : '读取文件夹失败。'); }
finally { if (sequence === request.current) setBusy(false); }
}
useEffect(() => { void browse(initialPath); return () => { request.current++; }; }, []);
return <section className="directory-picker" aria-label="本机文件夹选择">
<div className="directory-location"><button type="button" className="icon-button" aria-label="上一级文件夹" disabled={busy || !listing?.parent} onClick={() => void browse(listing!.parent!)}><ArrowUp size={16} /></button><input aria-label="浏览文件夹路径" disabled={busy} value={location} onChange={event => setLocation(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); void browse(location); } }} /><button type="button" className="button secondary" disabled={busy} onClick={() => void browse(location)}>前往</button><button type="button" className="icon-button" aria-label="刷新文件夹" disabled={busy} onClick={() => void browse(listing?.current || location)}><RotateCw size={15} /></button></div>
{listing && <nav className="directory-bookmarks" aria-label="常用位置">{listing.bookmarks.map(item => <button type="button" key={item.path} disabled={busy} onClick={() => void browse(item.path)}>{item.name}</button>)}</nav>}
{error && <p className="local-files-error" role="alert">{error}</p>}
<input className="directory-filter" aria-label="筛选子文件夹" placeholder="筛选当前目录下的文件夹" value={filter} onChange={event => setFilter(event.target.value)} />
<div className="directory-list" aria-busy={busy}>{busy ? <p role="status"><LoaderCircle className="spin" size={16} />正在读取文件夹…</p> : listing?.directories.filter(item => item.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase())).map(item => <button type="button" key={item.path} onClick={() => void browse(item.path)}><Folder size={17} /><span>{item.name}</span></button>)}{!busy && listing && !listing.directories.filter(item => item.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase())).length && <p>{filter ? '没有匹配的子文件夹。' : '此文件夹没有子文件夹,可以直接选择。'}</p>}</div>
{listing?.truncated && <p className="subtle">此处文件较多,已显示部分文件夹;可在上方输入完整路径。</p>}
<div className="directory-selection"><span title={listing?.current}>已定位:{listing?.current || '尚未选择'}</span><div><button type="button" className="button secondary" onClick={onCancel}>取消选择</button><button type="button" className="button primary" disabled={busy || !!error || !listing} onClick={() => onChoose(listing!.current)}>使用此文件夹</button></div></div>
</section>;
}
+1
View File
@@ -12,6 +12,7 @@ type DesktopWorkbench = {
status(): Promise<DesktopHostStatus>;
pickProject(): Promise<Project | null>;
projectFolder(projectId: string): Promise<{ opened: boolean }>;
openFilePreview?(input: { projectId: string; url: string }): Promise<{ opened: boolean }>;
reviewTask(input: DesktopTaskScope): Promise<DesktopTaskScope & { eventSeq: number }>;
revealFile(input: DesktopTaskScope & { path: string; sha256: string }): Promise<{ revealed: boolean }>;
stopHost(): Promise<{ cancelled?: boolean; state?: string; processExited?: boolean }>;
+7
View File
@@ -40,6 +40,13 @@ export class DesktopBridge {
const error = await this.shell.openPath(project.root); if (error) throw desktopError('系统无法打开所属项目目录。');
return { opened: true, projectId: project.id, root: project.root };
}
if (action === 'openFilePreview') {
const access = await this.controller.api('/local-file-preview-access?url=' + encodeURIComponent(value.url));
if (!access.allowed || access.projectId !== value.projectId) throw desktopError('此预览已关闭或不属于当前项目。');
assertDesktopFrame(event, this.getWindow(), this.controller.url);
await this.shell.openExternal(value.url);
return { opened: true };
}
if (action === 'reviewTask') {
const session = await this.task(value); await this.project(value.projectId);
return { projectId: session.projectId, sessionId: session.id, taskId: value.taskId, eventSeq: session.eventSeq };
+89
View File
@@ -0,0 +1,89 @@
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { randomBytes, randomUUID } from 'node:crypto';
import { safePath, readText, excludedFromInventory } from '../../server/files.mjs';
import { verifyWorkspaceProject } from '../workspaces/git-workspaces.mjs';
const types = new Map(Object.entries({ '.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8',
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon',
'.avif': 'image/avif', '.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.otf': 'font/otf', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.mp4': 'video/mp4', '.webm': 'video/webm', '.wasm': 'application/wasm' }));
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
export function localPreviewAddress(value) {
try {
const url = new URL(value);
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && !!url.port && !url.username && !url.password
&& /^\/[a-f0-9]{48}\//.test(url.pathname);
} catch { return false; }
}
export class LocalFilePreviews {
constructor(store, { ttl = 30 * 60 * 1000 } = {}) {
this.store = store; this.ttl = ttl; this.active = new Map(); this.pending = 0; this.disposed = false;
this.sweep = setInterval(() => { for (const entry of this.active.values()) if (Date.now() - entry.lastRead > this.ttl) void this.close(entry.projectId, entry.id); }, Math.min(ttl, 60000));
this.sweep.unref();
}
access(value) {
if (!localPreviewAddress(value)) return { allowed: false };
const url = new URL(value);
const entry = [...this.active.values()].find(item => url.origin === item.origin && url.pathname.startsWith(item.prefix));
return entry ? { allowed: true, projectId: entry.projectId } : { allowed: false };
}
async start(project, relative) {
if (this.disposed) throw fail('文件预览已关闭,请重新打开文件。', 409);
if (this.active.size + this.pending >= 8) throw fail('已打开较多文件预览,请先关闭一个预览再试。', 409);
this.pending++;
try {
await verifyWorkspaceProject(this.store, project);
if (typeof relative !== 'string' || !/\.html?$/i.test(relative)) throw fail('请选择 HTML 文件进行预览。');
if (excludedFromInventory(relative)) throw fail('此目录不用于文件预览。', 403);
readText(project, relative); // Same verified project/file boundary as the source view.
const entry = { id: randomUUID(), projectId: project.id, prefix: '/' + randomBytes(24).toString('hex') + '/', lastRead: Date.now() };
entry.server = http.createServer(async (request, response) => {
response.setHeader('Cache-Control', 'no-store');
response.setHeader('X-Content-Type-Options', 'nosniff');
response.setHeader('Referrer-Policy', 'no-referrer');
response.setHeader('Access-Control-Allow-Origin', 'null'); // Sandboxed module scripts, without credentials.
// Applies to both the embedded frame and a separately opened preview.
response.setHeader('Content-Security-Policy', "sandbox allow-scripts; default-src 'self' data: blob:; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'");
try {
if (request.headers.host !== '127.0.0.1:' + entry.server.address()?.port) throw fail('文件预览仅接受原本机地址。', 421);
if (!['GET', 'HEAD'].includes(request.method)) throw fail('文件预览只支持读取。', 405);
// Parse the raw path before URL normalization so encoded traversal
// cannot silently turn into a different project file.
const raw = request.url.split('?')[0];
if (!raw.startsWith(entry.prefix)) throw fail('预览地址已失效,请重新打开文件预览。', 404);
let resource;
try { resource = decodeURIComponent(raw.slice(entry.prefix.length)); } catch { throw fail('资源路径无效。'); }
if (excludedFromInventory(resource)) throw fail('此资源不在预览范围内。', 403);
const mediaType = types.get(path.extname(resource).toLowerCase());
if (!mediaType) throw fail('此文件类型不用于网页预览。', 403);
await verifyWorkspaceProject(this.store, project);
const file = safePath(project, resource), stat = fs.statSync(file);
if (!stat.isFile() || stat.size > 20 * 1024 * 1024) throw fail('资源不存在或超过 20 MB 预览上限。', 413);
const bytes = fs.readFileSync(file);
entry.lastRead = Date.now();
response.writeHead(200, { 'Content-Type': mediaType, 'Content-Length': bytes.length });
response.end(request.method === 'HEAD' ? undefined : bytes);
} catch (error) { response.writeHead(error.status || 403, { 'Content-Type': 'text/plain; charset=utf-8' }); response.end('无法预览:' + error.message); }
});
entry.server.requestTimeout = 15000;
await new Promise((resolve, reject) => { entry.server.once('error', reject); entry.server.listen(0, '127.0.0.1', resolve); });
if (this.disposed) { entry.server.close(); throw fail('文件预览已关闭。', 409); }
entry.origin = 'http://127.0.0.1:' + entry.server.address().port;
this.active.set(entry.id, entry);
return { id: entry.id, projectId: project.id, path: relative, url: entry.origin + entry.prefix + relative.replaceAll('\\', '/').split('/').map(encodeURIComponent).join('/') };
} finally { this.pending--; }
}
async close(projectId, id) {
const entry = this.active.get(id);
if (!entry) return { closed: true };
if (entry.projectId !== projectId) throw fail('预览不属于当前项目。', 403);
this.active.delete(id);
await new Promise(resolve => { entry.server.close(resolve); entry.server.closeAllConnections(); });
return { closed: true };
}
async stopAll() { this.disposed = true; clearInterval(this.sweep); await Promise.all([...this.active.values()].map(entry => this.close(entry.projectId, entry.id))); }
}
+5 -2
View File
@@ -10,6 +10,7 @@ import { observeWindowsProcess, protectUserDirectory } from '../core/desktop/pro
import { DESKTOP_CHANNELS, desktopOrigin } from '../shared/contracts/desktop-bridge.mjs';
import { desktopLaunchOptions } from '../core/desktop/launch-options.mjs';
import { BrowsingView } from './browsing-view.mjs';
import { localPreviewAddress } from '../core/preview/local-file-preview.mjs';
const options = desktopLaunchOptions(process.argv, { defaultApp: process.defaultApp, mainFile: __filename });
const appRoot = path.resolve(options['--app-root'] || (app.isPackaged ? path.resolve(path.dirname(process.execPath), '..') : path.resolve(__dirname, '..')));
@@ -45,14 +46,16 @@ else {
webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false } });
window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
window.webContents.on('will-navigate', details => { if (!desktopOrigin(details.url, controller.url)) details.preventDefault(); });
window.webContents.on('will-frame-navigate', details => { if (!desktopOrigin(details.url, controller.url)) details.preventDefault(); });
window.webContents.on('will-frame-navigate', details => { if (!desktopOrigin(details.url, controller.url) && !(details.isMainFrame === false && localPreviewAddress(details.url))) details.preventDefault(); });
window.webContents.on('will-attach-webview', event => event.preventDefault());
const session = window.webContents.session;
session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));
session.setPermissionCheckHandler(() => false);
session.webRequest.onBeforeRequest((details, callback) => {
const permitted = desktopOrigin(details.url, controller.url) || details.url.startsWith('data:image/') || details.url.startsWith('blob:' + controller.url + '/');
callback({ cancel: !permitted });
if (permitted) return callback({ cancel: false });
if (!localPreviewAddress(details.url) || details.resourceType === 'mainFrame') return callback({ cancel: true });
void controller.api('/local-file-preview-access?url=' + encodeURIComponent(details.url)).then(access => callback({ cancel: !access.allowed })).catch(() => callback({ cancel: true }));
});
bridge = new DesktopBridge(controller, { dialog, shell, getWindow: () => window, onStopped: () => setTimeout(() => app.quit(), 150) });
for (const [action, channel] of Object.entries(DESKTOP_CHANNELS)) ipcMain.handle(channel, (event, input) => bridge.execute(event, action, input));
+1
View File
@@ -4,6 +4,7 @@ contextBridge.exposeInMainWorld('desktopWorkbench', Object.freeze({
status: () => ipcRenderer.invoke('awb:desktop-status'),
pickProject: () => ipcRenderer.invoke('awb:desktop-pick-project'),
projectFolder: projectId => ipcRenderer.invoke('awb:desktop-project-folder', { projectId }),
openFilePreview: input => ipcRenderer.invoke('awb:desktop-file-preview', input),
reviewTask: input => ipcRenderer.invoke('awb:desktop-review-task', input),
revealFile: input => ipcRenderer.invoke('awb:desktop-reveal-file', input),
stopHost: () => ipcRenderer.invoke('awb:desktop-stop-host'),
+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(); }
}
+2 -2
View File
@@ -1,5 +1,5 @@
export const DESKTOP_CHANNELS = Object.freeze({ status: 'awb:desktop-status', pickProject: 'awb:desktop-pick-project',
revealFile: 'awb:desktop-reveal-file', projectFolder: 'awb:desktop-project-folder', reviewTask: 'awb:desktop-review-task', stopHost: 'awb:desktop-stop-host' });
revealFile: 'awb:desktop-reveal-file', openFilePreview: 'awb:desktop-file-preview', projectFolder: 'awb:desktop-project-folder', reviewTask: 'awb:desktop-review-task', stopHost: 'awb:desktop-stop-host' });
export const desktopError = message => Object.assign(new Error(message), { code: 'DESKTOP_SCOPE_REJECTED', status: 403 });
export function desktopOrigin(value, origin) {
try { const url = new URL(value); return url.origin === origin && url.protocol === 'http:' && !url.username && !url.password; } catch { return false; }
@@ -10,7 +10,7 @@ export function assertDesktopFrame(event, window, origin) {
}
export function desktopInput(action, input) {
const fields = { status: [], pickProject: [], stopHost: [], projectFolder: ['projectId'], reviewTask: ['projectId', 'sessionId', 'taskId'],
revealFile: ['projectId', 'sessionId', 'taskId', 'path', 'sha256'] }[action];
openFilePreview: ['projectId', 'url'], revealFile: ['projectId', 'sessionId', 'taskId', 'path', 'sha256'] }[action];
if (!fields) throw desktopError('本机操作不存在。');
const value = input ?? {};
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !fields.includes(key))) throw desktopError('本机操作字段无效。');