feat(ui): show actual model route and inspect live stream evidence

This commit is contained in:
Agent Workbench Dev
2026-10-31 22:42:47 +08:00
parent eeb11d6a76
commit 31ed219477
22 changed files with 276 additions and 38 deletions
+8
View File
@@ -15,3 +15,11 @@ Responses的typed Items、原call_id配对、原用量与同线路reasoning续
相关恢复检查42/42通过;新增边界29/29、流式/手机投影/上下文38/38通过(这些范围有重叠,不相加)。原日志见[恢复专项](model-protocols-current-specialists.txt)、[边界专项](model-protocols-boundary-specialists.txt)、[投影与上下文](model-protocols-projection-specialists.txt)。新增验证包括原停用对象导致probe引用失效的修复、检测所属attempt精确绑定、原始畸形UTF8捕获、CR事件终结、超时关闭HTTP、自有CCSwitch SQLite/TOML Responses导入,全部使用自有loopback数据。原失败夹具与首次UI定位失败保留;后者为select隐式名称包含option文字,已增加明确aria-label,重新实际验收中。
E界面已构建,正在操作验收;F独立发行与正式部署未执行。协议实现不能代表视觉/音频已接入或真实模型自主工程能力已经通过。具体协议和来源见[协议边界](MODEL-PROTOCOLS.md)。
## E:真实界面与回看修复
模型中心新增协议/能力/范围、实际线路与拒绝原因、完整/未完整流字节与原SHA下载;桌面与伴随端显示同一原Run的有界片段。实际Edge桌面1440px、窄屏390px以及真实TLS网关配对的手机视口5组流程通过,页面错误和失败请求均0,响应下载与工件SHA一致。实际iPhone本轮未联调,不能把窄屏或TLS中继称作实机。入口见[本轮界面结果](model-protocols-e-ui-validation.json)。
目视截图发现并修复:片段同批到达后上游停顿,节流需要定时补发最新状态;选池后主窗口可能仍显示离线演示,旧提交校验还错误要求未选中的原连接模型名。现在用公开选路身份同步主窗口,刷新仍保留实际池名,原连接配置不被改写;新UI流程明确等待选路并刷新后发送。下载直接读取工件字节,畸形UTF8也不再被文本解码改写。37项流式/请求计划/升级、20项旧模型中心/API兼容和26项原字节/连接专项通过(重叠范围不累计)。
原UI定位失败、外部API增加连接后未刷新界面的夹具失败、真实节流缺陷、错误mobile选择器和原首次完整UI运行都保留。首次历史UI全量运行的Purge来源传成打包目录,修正为原source/upstream;原日志与阶段结果单独保存,重跑使用新顶层日志。完整回归早于最后修复启动,属于开发中诊断;最终结论以冻结后的独立源码整轮为准。
+6
View File
@@ -9,3 +9,9 @@
统一消息不能取代真正发送的请求。Responses和流式池各封存实际变体,并另记当前物理请求的SHA/字节;保留原工具call_id、reasoning与原用量。流式进展不进入工具执行,直到原终结与参数通过核对;断流/超时保留unknown不自动重放。原始Buffer捕获保持畸形字节,发生已知凭据脱敏时单列工件SHA。
回顾发现probe引用原可变连接时,toggle会同时更新比较两端,导致旧检测结论被错误接纳;改为连接快照并验证修订。原attempt通过progress身份绑定,避免并发任务改变账本末项。29项新增边界及38项关联投影/上下文检查通过。预算仍按所有成员容量保守取最小值,可能降低混合池可用容量;没有损失请求/审批边界,后续可按真实任务需求优化。E实际验收和F独立发行仍按计划执行。
## E:观察后再判定可用
单看控件存在会遗漏主任务问题。截图中主窗口还显示离线演示,导致发现选池/关闭窗口时的外部状态同步与旧legacy模型校验缺陷;现在选择和刷新都保留实际池名,再由同一后端选路执行。流式首批事件合并时曾只显示0字符,增加定时补发最终片段,停止时清除计时器,专门检查上游不再发送任何事件的情形。
桌面/390px和真实TLS配对观察窗口5组完整流程通过并目视回看。手机原生Safari、信任/PWA已有1.16实机记录;1.17新增流式尚无新实机结论。工程回归继续使用固定原测试和真实Node/React/Python执行,增加同一原工程算法通过Responses SSE与受控Harness的独立门槛,不能拿文本fixture结束当工程完成。
+35
View File
@@ -0,0 +1,35 @@
✔ model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart (2370.3633ms)
✔ config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts (2117.705ms)
✔ real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity (6897.5971ms)
✔ pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests (9250.5979ms)
✔ 401 blocks the credential revision; updating the key restores availability without leaking error echoes (3217.6818ms)
✔ queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request (2598.7156ms)
✔ compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model (4360.1888ms)
✔ model registry disk failures restore routing, pool profiles and credential references without partial updates (1893.4263ms)
✔ model selection and saved configuration commit together and failures preserve the original mode and endpoint (2166.135ms)
✔ configuration imports roll back the entire batch and retain one usable preview after validation or commit failure (1609.896ms)
✔ HTTP download preserves original malformed SSE bytes and artifact SHA instead of decoding invalid UTF8 (3952.9458ms)
✔ real Chat SSE carries UTF8 and split tool JSON; Runtime executes only after DONE, stores partial progress and original usage (7105.3473ms)
✔ Responses typed SSE validates original item identity, terminal data, raw usage and tool result pair (6291.606ms)
✔ incomplete network stream retains unknown attempt and never automatically switches pool or dispatches fragment tools (4041.245ms)
✔ stopping an active HTTP stream closes only original request and keeps partial text without executing tools (4006.955ms)
✔ explicit streaming probe uses actual SSE despite unknown declaration and binds its own original attempt (2517.4313ms)
✔ coalesced initial SSE events publish the latest partial state even when the upstream stays idle (4539.5055ms)
✔ stream timeout closes the original HTTP response, preserves redacted capture and never retries (2557.65ms)
✔ SSE accepts CR-only final event boundaries and retains exact invalid UTF8 bytes without dispatch (0.9326ms)
▶ stream parser rejects truncation, finish length, malformed JSON, duplicate sequence, changed final item and oversized data
✔ reject 0 (0.1952ms)
✔ reject 1 (0.234ms)
✔ reject 2 (0.2449ms)
✔ reject 3 (5.2352ms)
✔ reject 4 (0.1967ms)
✔ reject 5 (0.1693ms)
✔ stream parser rejects truncation, finish length, malformed JSON, duplicate sequence, changed final item and oversized data (6.8177ms)
ℹ tests 26
ℹ suites 0
ℹ pass 26
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 36601.3161
+41
View File
@@ -0,0 +1,41 @@
{
"success": true,
"version": "1.17.0",
"appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench",
"nodePath": "D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe",
"containedRuntime": false,
"nodeSha256": "d702daa815eabbff763c7d3808e235cf031cf2ca70211b56847bc72f51e240e5",
"passed": [
"actual form saves Responses and declared stream, refresh preserves both and narrow editor remains operable",
"separate text, nonce tool and actual SSE probes bind only their requested capability and own attempts",
"actual pooled task excludes text-only before dispatch, executes original tool once and downloads SHA-matched original SSE",
"desktop and actual paired gateway show same bounded stream; mobile stops original HTTP with zero fragment tool dispatch or replay",
"truncated output keeps explicit unknown ledger, partial evidence and no automatic failover or incomplete tool execution"
],
"screenshots": [
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\desktop-editor.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\narrow-editor.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\desktop-capabilities.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\narrow-capabilities.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\desktop-ledger.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\desktop-streaming.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\narrow-streaming.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\mobile-streaming.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\mobile-stopped.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\narrow-stopped.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\desktop-incomplete.png",
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4\\narrow-incomplete.png"
],
"pageErrors": [],
"requestFailures": [],
"fixtureModelRequests": 7,
"realModelRequests": 0,
"osTrustChanged": false,
"nativeIPhone": "not exercised; paired Edge viewport uses CA-verifying owned relay",
"taskId": "238c7b5e-3a50-41bb-a88b-83612d53de00",
"runIds": [
"d9ba991e-8cad-4ee5-bdf1-622f9d71347b",
"67e4674f-57eb-4d97-bd70-2c4ef62eb2ae",
"888065cf-7745-4295-9ae0-cd743c89d682"
]
}
@@ -0,0 +1,46 @@
✔ real Chat SSE carries UTF8 and split tool JSON; Runtime executes only after DONE, stores partial progress and original usage (5983.0173ms)
✔ Responses typed SSE validates original item identity, terminal data, raw usage and tool result pair (6258.0056ms)
✔ incomplete network stream retains unknown attempt and never automatically switches pool or dispatches fragment tools (4047.5165ms)
✔ stopping an active HTTP stream closes only original request and keeps partial text without executing tools (4001.9193ms)
✔ explicit streaming probe uses actual SSE despite unknown declaration and binds its own original attempt (1869.4361ms)
✔ coalesced initial SSE events publish the latest partial state even when the upstream stays idle (4337.4586ms)
✔ stream timeout closes the original HTTP response, preserves redacted capture and never retries (2078.133ms)
✔ SSE accepts CR-only final event boundaries and retains exact invalid UTF8 bytes without dispatch (1.0764ms)
▶ stream parser rejects truncation, finish length, malformed JSON, duplicate sequence, changed final item and oversized data
✔ reject 0 (0.204ms)
✔ reject 1 (0.137ms)
✔ reject 2 (0.192ms)
✔ reject 3 (5.0447ms)
✔ reject 4 (0.7307ms)
✔ reject 5 (0.202ms)
✔ stream parser rejects truncation, finish length, malformed JSON, duplicate sequence, changed final item and oversized data (7.0625ms)
✔ context APIs retain exact request identity, paginate archived groups and reject foreign sessions/runs (6192.0329ms)
✔ delivery reports verify request body, sealed plan and original archived bytes, and show corruption as needing verification (5243.1234ms)
✔ direct code evidence remains selected while recent historical-index browsing is archived within the complete request budget (4520.4396ms)
✔ one long user turn becomes bounded complete groups with exact UTF-8 history and recent JSON arguments (10567.6007ms)
✔ tool definitions, exact system bytes, output reserve and remaining Run/Task budget are accounted before requests (2088.1285ms)
✔ oversized required user instructions pause intact and can be explicitly resumed after increasing the window (4121.4042ms)
✔ all task instructions, constraints and acceptance remain in the runtime system instead of an eight-item or byte prefix (3632.5053ms)
✔ a newest manageable multi-tool group stays exact even beyond the working target; oversized earlier groups are archived (2187.4153ms)
✔ invalid orphan result is rejected before archive or network preparation (1310.8086ms)
✔ invalid missing result is rejected before archive or network preparation (1405.7107ms)
✔ invalid wrong result is rejected before archive or network preparation (1532.416ms)
✔ invalid duplicate call is rejected before archive or network preparation (2103.016ms)
✔ a group larger than the artifact limit uses verified Unicode-safe chunks without replacing tool JSON (4459.0071ms)
✔ changed or missing archived evidence stops reuse and is never silently recreated (2227.314ms)
✔ transaction failure prevents publishing a plan and any corresponding model request (2090.0617ms)
✔ the Provider rejects body mutation after a sealed plan before calling HTTP (1741.8434ms)
✔ HTTP failure and explicit same-Task resume reuse exact completed results and request hashes without repeating a command (13863.0813ms)
✔ a real process exit after plan persistence marks interruption and never issues an automatic model request (2513.3048ms)
✔ hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing (2472.0281ms)
✔ failed adoption restores the original virtual data-root name and original open database (1811.855ms)
✔ hot upgrade refreshes retained model and importer methods while preserving credential and routing objects (2029.5545ms)
✔ hot upgrade refuses active probes and restores retained model methods if installation fails (1963.2231ms)
ℹ tests 37
ℹ suites 0
ℹ pass 37
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 72015.918
@@ -0,0 +1,28 @@
✔ the bundled local service enforces host, origin, token and JSON object contracts (2974.454ms)
✔ an in-flight connection probe prevents configuration changes and another probe until its actual result returns (4037.4954ms)
✔ API review applies verified content, detects conflicts, exports sessions and keeps keys in memory (7025.1254ms)
✔ a real bundle restart preserves proposals, interrupts old approvals and requests fresh consent on resume (20310.8193ms)
✔ runtime diagnostics and model-response validation use actual records and preserve the saved connection (3695.7218ms)
✔ persistent event replay is read-only and keeps run/artifact identity across reconnects (13297.8198ms)
✔ model registry keeps original credentials/endpoint intact, rejects stale edits, and forgets only volatile keys on restart (1701.7823ms)
✔ config import previews exact revisions, keeps secrets volatile, syncs only when enabled and preserves manual edits on conflicts (1223.0659ms)
✔ real HTTP pool fails over 429 to another model and never repeats completed tools; attempts seal actual request bytes and Run identity (6081.7127ms)
✔ pool rotation and weights select members on new Runs; disabled and missing credentials are excluded without requests (8632.154ms)
✔ 401 blocks the credential revision; updating the key restores availability without leaking error echoes (4455.0191ms)
✔ queued request cancellation and in-flight disable release only owned leases and do not dispatch another HTTP request (1923.0023ms)
✔ compiled model-center HTTP API persists public profiles, blocks forged origins, and local operations never invoke a model (4051.2999ms)
✔ model registry disk failures restore routing, pool profiles and credential references without partial updates (1738.0266ms)
✔ model selection and saved configuration commit together and failures preserve the original mode and endpoint (1983.278ms)
✔ configuration imports roll back the entire batch and retain one usable preview after validation or commit failure (2341.2948ms)
✔ hot upgrade adopts a retained virtual data root without reopening SQLite or changing rows, Provider or routing (2644.1625ms)
✔ failed adoption restores the original virtual data-root name and original open database (1229.9266ms)
✔ hot upgrade refreshes retained model and importer methods while preserving credential and routing objects (1692.9317ms)
✔ hot upgrade refuses active probes and restores retained model methods if installation fails (1448.422ms)
ℹ tests 20
ℹ suites 0
ℹ pass 20
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 51433.0448
+3
View File
@@ -823,3 +823,6 @@ formal-stage已成功,12:28:12Z→12:38:20Z约10分9秒;真实产品setup/
## 1.17 B–E恢复与边界复核
A已提交578cf88。B/C/D新增协议、请求变体、SSE及能力选路,恢复后42/42相关检查和当前TypeScript/Vite/手机壳/服务构建通过,原日志protocol-current-specialists.tap与protocol-e-current-build.log保留。实际审查发现:probe持有可变连接引用,toggle会令旧修订比较失效;改为快照。检测原账本由progress.modelAttemptId绑定,避免并发任务改变最后一条请求。SSE末尾CR在EOF处补齐边界;原捕获改为Buffer,畸形UTF8也保留原字节,只有发生凭据脱敏才改变工件字节。补原停止/断开工件SHA、实际流式probe、禁用期间检测作废、超时不重发及自有CCSwitch SQLite/TOML协议导入回归。补查尚待本轮专项结果,不预判通过。
只读误猜SessionView/verify-desktop-projects等已通过rg定位,实际桌面工程入口controlled-projects --desktop。一次在Windows使用glob路径产生rg路径错误,未写入;改用实际src/core/storage/artifact-store.mjs及目录检索。递归.qa检索误带旧node_modules导致无用超长输出,后续只读顶层自有执行器。正式PID/Provider未动,真实模型请求0。
1.17 E真实操作5组通过,原result与13张截图保持在.qa/model-protocols-ui-5c599342-cbbd-4019-8865-ee1d7b4570e4;主窗口池名、手机接收/停止、390px未知账本已目视核对。补修select明确可访问名称、完成外部API新增后刷新UI夹具、mobile-stream实际选择器、上游停顿的延迟进展、主窗口legacy误判/快速关闭同步、原工件下载字节;37/37、20/20及26/26相关专项分别通过。一次精确替换误命中凭据callback,立即rg核对定位并修正,未执行或部署该中间版本。
第一次历史全量UI运行误将Purge打包目录当源码目录,原结果/日志逐字节复制到protocol-first-ui-environment-failure后,以source/upstream重新整轮,session82022;早于最终修复启动的full-tests session80218仅作开发中诊断。响应协议真实工程新门槛使用同一受控Node/React/Python算法、原测试、审批与Git,但走实际Responses SSE+ModelHub。当前session64602执行,结果尚未判定。只读路径version/gateway误猜后已用rg定位diagnostics.mjs与server/companion-gateway.mjs,无数据写入。
+10 -9
View File
@@ -1,8 +1,8 @@
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, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types';
import type { Bootstrap, Change, Config, ModelSelection, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types';
import { api, downloadBlob, exportSession, setToken } from './api';
import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, ToolRow, FailureCard } from './components';
import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, ToolRow, FailureCard, ModelStreamPreview } from './components';
import { DiagnosticsPanel } from './DiagnosticsPanel';
import { TaskPanel } from './TaskPanel';
import { CodeIndexPanel } from './CodeIndexPanel';
@@ -36,6 +36,7 @@ export default function App() {
const [sessionId, setSessionId] = useState('');
const [session, setSession] = useState<Session | null>(null);
const [config, setConfig] = useState<Config>(defaultConfig);
const [modelSelection, setModelSelection] = useState<ModelSelection>({ type: "legacy", id: "legacy-default", name: "原模型连接" });
const [exampleId, setExampleId] = useState<string | null>(null);
const [files, setFiles] = useState<FileEntry[]>([]);
const [filter, setFilter] = useState('');
@@ -242,7 +243,7 @@ export default function App() {
async function submit() {
if (!composer.trim() || sending || isRunning || (sessionId && !session)) return;
if (restrictedWorker || session?.execution?.collaborations?.some(value => !['completed', 'discarded', 'resolved_external'].includes(value.status))) { setWorkersOpen(true); return; }
if (config.mode === 'compatible' && !config.model) { openSettings(); notify('请先填写模型名称。'); return; }
if (config.mode === 'compatible' && modelSelection.type === 'legacy' && !config.model) { openSettings(); notify('请先填写模型名称。'); return; }
setSending(true);
const content = composer.trim();
try {
@@ -336,7 +337,7 @@ export default function App() {
setSettingsBusy(true);
try {
const payload = { ...settings, ...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) };
const saved = await api<Config>('/config', payload); setConfig(saved); setSettingsOpen(false);
const saved = await api<Config>('/config', payload); setConfig(saved); setModelSelection({ type: "legacy", id: "legacy-default", name: "原模型连接" }); setSettingsOpen(false);
notify(saved.mode === 'demo' ? '已切换到离线演示。' : '模型连接已保存。API Key 仅在本次服务内存中使用。');
} catch (error) { failure(error); } finally { setSettingsBusy(false); }
}
@@ -408,7 +409,7 @@ export default function App() {
let alive = true;
api<Bootstrap>('/bootstrap').then(result => {
if (!alive) return;
setToken(result.token); setAccess(result.token); setVersion(result.version); setProjects(result.projects); setBriefs(result.sessions); setConfig(result.config); setSettings(result.config); setExampleId(result.exampleProjectId);
setToken(result.token); setAccess(result.token); setVersion(result.version); setProjects(result.projects); setBriefs(result.sessions); setConfig(result.config); if (result.modelSelection) setModelSelection(result.modelSelection); setSettings(result.config); setExampleId(result.exampleProjectId);
const savedCursor = Number(sessionStorage.getItem('awb-event-cursor:' + location.origin));
eventCursor.current = Number.isSafeInteger(savedCursor) && savedCursor >= 0 && savedCursor <= (result.eventCursor ?? 0) ? savedCursor : result.eventCursor ?? 0;
for (const brief of result.sessions) revisions.current.set(brief.id, brief.revision);
@@ -536,7 +537,7 @@ export default function App() {
</aside>
<main className="task-pane">
<header className="work-header"><div className="work-title">{(!sidebarOpen || mobile) && <IconButton label="展开项目栏" onClick={() => setSidebarOpen(true)}><PanelLeftOpen size={18} /></IconButton>}<span className="header-symbol"><Code2 size={17} /></span><div><span className="header-breadcrumb">{selectedProject?.name || '工作空间'} <ChevronRight size={12} /> 任务</span><h1>{session?.title || '让任务走到完成'}</h1></div></div>
<div className="model-launch"><button className="button secondary" onClick={() => setCompanionOpen(true)} aria-label="手机连接"><Link2 size={16} /><span>手机连接</span></button>{desktop && <button className="button secondary desktop-launch" onClick={() => setDesktopOpen(true)} aria-label="桌面宿主"><SquareTerminal size={16} /><span>桌面宿主</span></button>}<button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={openSettings}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : config.model || '选择模型'}<ChevronDown size={13} /></button></div>
<div className="model-launch"><button className="button secondary" onClick={() => setCompanionOpen(true)} aria-label="手机连接"><Link2 size={16} /><span>手机连接</span></button>{desktop && <button className="button secondary desktop-launch" onClick={() => setDesktopOpen(true)} aria-label="桌面宿主"><SquareTerminal size={16} /><span>桌面宿主</span></button>}<button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={() => modelSelection.type !== 'legacy' && config.mode !== 'demo' ? setModelCenterOpen(true) : openSettings()}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : modelSelection.type !== 'legacy' ? modelSelection.name : config.model || '选择模型'}<ChevronDown size={13} /></button></div>
</header>
<div className="task-toolbar"><span className="task-local"><GitBranch size={13} />本地项目</span>{session ? <Status value={session.status} /> : <span className="subtle">等待新任务</span>}<div className="toolbar-actions">
<IconButton label="运行诊断" onClick={() => openDiagnostics()}><Activity size={15} /></IconButton>
@@ -556,7 +557,7 @@ export default function App() {
{session?.recoveryNotice && <div className="recovery-note"><ShieldCheck size={16} /><div><strong>已恢复会话记录</strong><p>{session.recoveryNotice}</p></div></div>}
{entries.map(entry => 'message' in entry && entry.message ? <div key={entry.id} className={'message message-' + entry.message.role}><span className="message-avatar">{entry.message.role === 'user' ? '你' : entry.message.role === 'assistant' ? 'AW' : '·'}</span><div className="message-body"><div className="message-label">{entry.message.role === 'user' ? '你的任务' : entry.message.role === 'assistant' ? session?.executionMode === 'demo' ? '演示执行器' : '编程助手' : '工作台'}<time>{new Date(entry.date).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}</time></div><div className="message-text">{entry.message.role === 'system' && failureForMessage(entry.message)
? <FailureCard failure={failureForMessage(entry.message)!} onDiagnose={() => openDiagnostics()} onRetry={session?.status === 'failed' && session?.failure?.messageId === entry.message.id ? () => resumeSession() : undefined} busy={resuming || isRunning} />
: entry.message.role === 'assistant' ? <ResearchContent content={entry.message.content} /> : entry.message.content}</div></div></div> : 'event' in entry && entry.event ? <div key={entry.id} className="inline-event">{['tool', 'model'].includes(entry.event.kind) ? <ToolRow event={entry.event} onSelect={() => { setEventId(entry.event!.id); showInspector('trace'); }} /> : <div className={'system-event event-' + entry.event.phase}><span />{entry.event.label}{entry.event.output && <p>{entry.event.output}</p>}</div>}</div> : null)}
: entry.message.role === 'assistant' ? <ResearchContent content={entry.message.content} /> : entry.message.content}</div></div></div> : 'event' in entry && entry.event ? <div key={entry.id} className="inline-event">{['tool', 'model'].includes(entry.event.kind) ? <><ToolRow event={entry.event} onSelect={() => { setEventId(entry.event!.id); showInspector('trace'); }} /><ModelStreamPreview event={entry.event} /></> : <div className={'system-event event-' + entry.event.phase}><span />{entry.event.label}{entry.event.output && <p>{entry.event.output}</p>}</div>}</div> : null)}
{isRunning && !approval && <div className="working-note"><LoaderCircle size={14} className="spin" /><span>{session?.executionMode === 'demo' ? '正在执行演示流程' : '正在处理任务'}</span></div>}
</div>}
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>{approval.browserPlanId ? '确认实际页面检查' : approval.checkPlanId ? '确认工程检查' : '确认这次终端执行'}</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre>
@@ -566,7 +567,7 @@ export default function App() {
{canContinueReview && <button type="button" aria-label="继续检查与交付" className="review-callout" disabled={resuming} onClick={continueReviewed}><ClipboardCheck size={17} /><span><strong>继续检查与交付</strong><small>改动已应用,沿用原任务继续实际测试和修复。</small></span><ArrowRight size={17} /></button>}
<div ref={chatEnd} />
</section>
<footer className="composer-wrap"><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><textarea ref={composerRef} aria-label="任务内容" placeholder={config.mode === 'demo' ? '先体验完整流程,或连接自己的模型开始开发…' : '描述项目任务,或询问工作台的执行状态与报错…'} value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '固定演示脚本' : '兼容模型服务'}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
<footer className="composer-wrap"><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><textarea ref={composerRef} aria-label="任务内容" placeholder={config.mode === 'demo' ? '先体验完整流程,或连接自己的模型开始开发…' : '描述项目任务,或询问工作台的执行状态与报错…'} value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '固定演示脚本' : modelSelection.type !== 'legacy' ? modelSelection.name : '兼容模型服务'}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
</main>
{((mobile && sidebarOpen) || (narrow && wide)) && <button type="button" className="panel-scrim" aria-label="关闭侧边面板" onClick={() => { setSidebarOpen(false); setWide(false); }} />}
<aside className="inspector">
@@ -588,7 +589,7 @@ export default function App() {
{reaOpen && session && selectedProject && <Modal title="REA 工件研究" description="原分析与同一项目、任务和运行绑定。" wide onClose={() => setReaOpen(false)}><ResearchPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} /></Modal>}
{engineOpen && session && selectedProject && <Modal title="本地代理引擎" description="本地安装、受控工程运行与原记录。" wide onClose={() => setEngineOpen(false)}><EnginePanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failureFor(session)} busy={isRunning} onNavigate={async (projectId, sessionId) => { setEngineOpen(false); await navigateWorkspace(projectId, sessionId); }} /></Modal>}
{researchOpen && <Modal title="机制研究与独立设计" description="从分发客户端的静态证据提炼产品机制。运行时与远端服务的未知部分在报告中说明。" wide onClose={() => setResearchOpen(false)}><div className="research-layout"><nav>{researchDocs.map(document => <button className={report?.title === document.title ? 'selected' : ''} key={document.id} onClick={() => loadReport(document.id)}><BookOpenText size={15} /><span><strong>{document.title}</strong><small>{document.description}</small></span></button>)}</nav><article className="research-document">{report && <ResearchContent content={report.content} />}</article></div></Modal>}
{modelCenterOpen && <Modal title="模型中心" description="连接、模型池与执行健康统一管理。" wide onClose={() => setModelCenterOpen(false)}><ModelCenter busy={anyRunning} onConfig={setConfig} onLegacy={() => { setModelCenterOpen(false); openSettings(); }} /></Modal>}
{modelCenterOpen && <Modal title="模型中心" description="连接、模型池与执行健康统一管理。" wide onClose={() => setModelCenterOpen(false)}><ModelCenter busy={anyRunning} onConfig={(value, selection) => { setConfig(value); if (selection) setModelSelection(selection); }} onLegacy={() => { setModelCenterOpen(false); openSettings(); }} /></Modal>}
{memoryOpen && selectedProject && <Modal title="项目记忆" description="项目事实与决策绑定源码指纹,变化后自动要求重新核对。" wide onClose={() => setMemoryOpen(false)}><ProjectMemoryPanel key={selectedProject.id + ':' + (session?.id ?? '')} project={selectedProject} session={session?.projectId === selectedProject.id ? session : null} /></Modal>}
{skillsOpen && selectedProject && <Modal title="项目技能" description="管理当前项目的技能来源、版本与启用状态。" wide onClose={() => setSkillsOpen(false)}><SkillCenter key={selectedProject.id} projectId={selectedProject.id} busy={isRunning} /></Modal>}
{mcpOpen && selectedProject && <Modal title="项目 MCP 工具" description="实际探测本地 stdio 服务,选择可以请求的工具,并核对每次运行原记录。" wide onClose={() => setMcpOpen(false)}><McpPanel key={selectedProject.id + ':' + (session?.id ?? '')} projectId={selectedProject.id} session={session?.projectId === selectedProject.id ? session : null} busy={isRunning} onSession={acceptSession} onError={session ? failureFor(session) : failure} /></Modal>}
+8
View File
@@ -10,3 +10,11 @@
@media(max-width:620px){.modal:has(.model-center)>.modal-heading>.icon-button{min-width:44px;min-height:44px}}
.mc-checks article>div{min-width:0;flex:1}.mc-checks p,.mc-operations-pages p{overflow-wrap:anywhere}.mc-operations-pages .mc-row-actions{display:flex;gap:8px;flex-wrap:wrap;margin:12px 0}.mc-operations-pages{border-top:1px solid #cbd6e2;margin-top:18px;padding-top:12px}.mc-operations-pages .error{color:#a23731}
.mc-probe-scope { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--text-muted, #53616b); }
.mc-probe-scope select { min-height: 36px; max-width: 136px; padding: 4px 8px; color: inherit; border: 1px solid #c7d2d9; border-radius: 6px; background: white; }
.mc-capabilities [data-capability="unsupported"] { color: #903c35; background: #fbefed; }
.mc-capabilities [data-capability="verified"] { color: #285c47; background: #eaf5ed; }
.mc-route-rejections { margin: 8px 0 0; color: #7c4c22; font-size: 12px; overflow-wrap: anywhere; }
.mc-stream-receipt { border-top: 1px solid var(--border); margin-top: 10px; padding-top: 8px; }
.mc-stream-receipt code { display: block; overflow-wrap: anywhere; font-size: 11px; line-height: 1.7; }
.mc-stream-receipt .button { margin-top: 8px; }
+23 -15
View File
@@ -1,13 +1,13 @@
import { useEffect, useRef, useState } from 'react';
import { Activity, Check, CircleHelp, KeyRound, Layers3, Plus, Power, RefreshCw, Route, Server, Settings2 } from 'lucide-react';
import { api } from './api';
import type { Config } from './types';
import { api, downloadArtifact } from './api';
import type { Config, ModelSelection } from './types';
import './ModelCenter.css';
type Connection = { id: string; name: string; brand: string; protocol: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean;
requiresKey: boolean; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
requiresKey: boolean; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
type Attempt = { id: string; connectionId: string; poolId: string | null; model: string; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; runId: string; requestArtifactId?: string; usage?: { prompt_tokens?: number; completion_tokens?: number } };
type Attempt = { id: string; connectionId: string; poolId: string | null; model: string; protocol?: string; streaming?: boolean; rejections?: { connectionName: string; capability: string; reason: string }[]; status: string; startedAt: string; ordinal: number; usageStatus: string; reason?: string; taskId?: string; sessionId?: string; runId: string; requestArtifactId?: string; responseArtifactId?: string; responseSha256?: string; responseRedacted?: boolean; stream?: { bytes: number; capturedBytes?: number; frames: number; sha256: string; terminal: boolean }; usage?: { prompt_tokens?: number; completion_tokens?: number } };
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
type Center = { revision: number; selected: { type: string; id: string }; connections: Connection[]; pools: Pool[]; imports: ImportRecord[]; attempts: Attempt[]; waiting: number };
type Operations = { checkedAt: string; version: string; scope: string; activeTasks: number; queue: number; checks: { id: string; title: string; status: string; detail: string }[];
@@ -15,10 +15,12 @@ type Operations = { checkedAt: string; version: string; scope: string; activeTas
type SavedCredential = { id: string; name: string; revision: number; status: string; enabled?: boolean; savedAt?: string; message: string };
type CredentialView = { supported: boolean; unavailable: boolean; connections: SavedCredential[]; scope: string };
const savedStates: Record<string, string> = { not_saved: '仅本次内存', saved: '本机加密保存', disabled: '关闭自动加载', source_changed: '配置已变化', decrypt_failed: '无法解密', user_mismatch: '用户不匹配', directory_mismatch: '目录不匹配', unavailable: '保存登记不可用' };
const states: Record<string, string> = { configured: '已配置', needs_key: '待填凭据', disabled: '已停用', needs_attention: '需要处理', cooling: '冷却中', completed: '收到响应', failed: '失败', running: '请求中', unknown: '结果待核对', interrupted: '已中断', passed: '通过', attention: '待配置' };
const initial = { name: '', brand: '自定义', model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, contextLimit: 16000, maxOutputTokens: 2048, concurrency: 1 };
const states: Record<string, string> = { configured: '已配置', needs_key: '待填凭据', disabled: '已停用', needs_attention: '需要处理', cooling: '冷却中', completed: '收到响应', failed: '失败', running: '请求中', unknown: '结果待核对', interrupted: '已中断', rejected: '能力不匹配', passed: '通过', attention: '待配置' };
const initial = { name: '', brand: '自定义', protocol: 'chat-completions', streaming: false, capabilityDeclarations: { text: 'supported', tools: 'supported', streaming: 'unknown', vision: 'unknown', audio: 'unknown' } as Record<string, string>, model: '', baseUrl: 'https://api.openai.com/v1', requiresKey: true, enabled: true, contextLimit: 16000, maxOutputTokens: 2048, concurrency: 1 };
const capabilityLabels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音' };
const capabilityStates: Record<string, string> = { protocol_declared: '声明支持', verified: '已验证', unknown: '待验证', unsupported: '不支持' };
const emptyPool: Pool = { name: '', members: [], strategy: 'round-robin', sticky: true, maxAttempts: 3, queueTimeoutMs: 15000 };
export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Config) => void; onLegacy: () => void; busy: boolean }) {
export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Config, selection?: ModelSelection) => void; onLegacy: () => void; busy: boolean }) {
const [view, setView] = useState<Center | null>(null);
const [tab, setTab] = useState('connections');
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number }>(initial);
@@ -27,6 +29,7 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
const [credentialView, setCredentialView] = useState<CredentialView | null>(null), [credentialKey, setCredentialKey] = useState(''), [credentialTarget, setCredentialTarget] = useState('');
const [pool, setPool] = useState<Pool>(emptyPool), [poolEditing, setPoolEditing] = useState(false);
const [working, setWorking] = useState(false), [notice, setNotice] = useState('');
const [probeScopes, setProbeScopes] = useState<Record<string, string>>({});
const [operations, setOperations] = useState<Operations | null>(null), [autoInspect, setAutoInspect] = useState(false);
const [importPath, setImportPath] = useState(''), [importSource, setImportSource] = useState('ccswitch');
const [preview, setPreview] = useState<{ id: string; entries: { id: string; name: string; model: string; baseUrl: string; hasKey: boolean }[]; notices: string[] } | null>(null);
@@ -67,19 +70,24 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
{tab === 'connections' && <>
<div className="mc-section-title"><div><h3>模型连接</h3><p>默认仅在本次宿主内存中使用;可在凭据保存中选择本机加密。已配置与调用通过分别显示。</p></div><button className="button primary" disabled={locked} onClick={() => { setDraft(initial); setKey(''); setPersistKey(false); setEditing(true); }}><Plus size={16} />添加连接</button></div>
<div className="mc-connections">{view.connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · Chat Completions</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {value.protocol === 'responses' ? 'Responses' : 'Chat Completions'}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>接口</dt><dd>{value.baseUrl}</dd><dt>凭据</dt><dd>{value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>请求 / 容量</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency} · 上下文 {value.contextLimit.toLocaleString()}</dd></dl>
<div className="mc-capabilities"><span>工具:协议声明</span><span>视觉 / 语音:待验证</span></div>
<div className="mc-capabilities">{Object.entries(capabilityLabels).map(([key, title]) => <span key={key} data-capability={value.capabilities?.[key] ?? 'unknown'}>{title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']}</span>)}</div>
{value.health.reason && <p className="mc-card-warning">{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}</p>}
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); if (alive.current) onConfig(result.config); })}>{selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { if (value.id === 'legacy-default') { onLegacy(); return; } setDraft(value); setKey(''); setPersistKey(false); setEditing(true); }}>编辑</button>
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
<button className="button secondary" disabled={locked} onClick={() => { if (value.id === 'legacy-default') { onLegacy(); return; } setDraft({ ...initial, ...value, streaming: value.streaming === true, capabilityDeclarations: { ...initial.capabilityDeclarations, ...value.capabilityDeclarations } }); setKey(''); setPersistKey(false); setEditing(true); }}>编辑</button>
{value.id !== 'legacy-default' && <button className="mc-icon-action" aria-label={(value.enabled ? '停用' : '启用') + value.name} disabled={working} onClick={() => void act(async () => { await api('/model-center/toggle', { id: value.id, enabled: !value.enabled }); })}><Power size={15} />{value.enabled ? '停用' : '启用'}</button>}
<button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { await api('/model-center/probe', { id: value.id }); if (alive.current) setNotice('该连接已收到实际响应;请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
<label className="mc-probe-scope">检测范围<select aria-label={value.name + '检测范围'} value={probeScopes[value.id] ?? 'text'} disabled={locked} onChange={event => setProbeScopes({ ...probeScopes, [value.id]: event.target.value })}><option value="text">文本响应</option><option value="tools">工具调用</option><option value="streaming">流式文本</option></select></label>
<button className="mc-probe" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ scope: string }>('/model-center/probe', { id: value.id, scope: probeScopes[value.id] ?? 'text' }); if (alive.current) setNotice(capabilityLabels[result.scope] + '检测通过;只验证所选能力,原请求与用量已记入账本。'); })}>验证响应(调用模型)</button></footer>
</article>)}</div>
{editing && <form className="mc-editor" aria-label="编辑模型连接" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/connections', { ...draft, ...(key ? { apiKey: key } : {}), ...(persistKey ? { persistKey: true } : {}) }); if (alive.current) { setKey(''); setEditing(false); setNotice(persistKey ? '连接与本机加密凭据已一起保存。' : '连接已保存。'); } }); }}>
<h3>{draft.id ? '编辑模型连接' : '添加模型连接'}</h3><div className="mc-form-grid">
<label>连接名称<input required value={draft.name} onChange={event => setDraft({ ...draft, name: event.target.value })} /></label>
<label>服务品牌<select value={draft.brand} onChange={event => setDraft({ ...draft, brand: event.target.value })}>{['自定义', 'OpenAI', 'Claude 兼容代理', 'DeepSeek', 'Ollama', 'vLLM', '兼容服务'].map(brand => <option key={brand}>{brand}</option>)}</select></label>
<label>接口协议<select aria-label="接口协议" value={draft.protocol} onChange={event => setDraft({ ...draft, protocol: event.target.value })}><option value="chat-completions">Chat Completions</option><option value="responses">OpenAI Responses</option></select></label>
<label>工具调用能力<select aria-label="工具调用能力" value={draft.capabilityDeclarations.tools} onChange={event => setDraft({ ...draft, capabilityDeclarations: { ...draft.capabilityDeclarations, tools: event.target.value } })}><option value="supported">服务声明支持</option><option value="unknown">尚未确定</option><option value="unsupported">明确不支持</option></select></label>
<label>流式能力<select aria-label="流式能力" value={draft.capabilityDeclarations.streaming} onChange={event => setDraft({ ...draft, streaming: event.target.value === 'supported' && draft.streaming, capabilityDeclarations: { ...draft.capabilityDeclarations, streaming: event.target.value } })}><option value="unknown">尚未确定</option><option value="supported">服务声明支持</option><option value="unsupported">明确不支持</option></select></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.streaming} disabled={draft.capabilityDeclarations.streaming !== 'supported'} onChange={event => setDraft({ ...draft, streaming: event.target.checked })} />使用流式输出</label>
<label className="mc-full">接口根地址<input type="url" required value={draft.baseUrl} onChange={event => setDraft({ ...draft, baseUrl: event.target.value })} /></label>
<label>实际模型名称<input required value={draft.model} onChange={event => setDraft({ ...draft, model: event.target.value })} /></label>
<label>临时 API Key<input type="password" autoComplete="off" value={key} placeholder={draft.id ? '留空保留本次凭据' : '按服务要求填写'} onChange={event => setKey(event.target.value)} /></label>
@@ -88,7 +96,7 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
<label>并发请求上限<input type="number" min="1" max="8" value={draft.concurrency} onChange={event => setDraft({ ...draft, concurrency: Number(event.target.value) })} /></label>
<label className="mc-checkbox"><input type="checkbox" checked={draft.requiresKey} onChange={event => setDraft({ ...draft, requiresKey: event.target.checked })} />服务需要 API Key</label></div>
<label className="mc-checkbox"><input type="checkbox" checked={persistKey} onChange={event => setPersistKey(event.target.checked)} />本机加密保存本次填写的 API Key</label>
<p className="mc-help"><CircleHelp size={14} />加密保存需要新填凭据;配置变化后需重新保存。选择品牌仅用于分类,接口需提供 Chat Completions 协议。</p>
<p className="mc-help"><CircleHelp size={14} />品牌仅用于分类,请选择服务实际提供的协议。能力检测会发起一次模型请求,可能产生费用;使用合成输入,不发送项目文件。文本检测不能证明工具或视觉能力。配置变化后需重新检测并核对凭据保存状态。</p>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => { setEditing(false); setKey(''); }}>取消</button><button className="button primary" disabled={locked || persistKey && !key.trim()} type="submit">保存模型连接</button></div>
</form>}
</>}
@@ -122,12 +130,12 @@ export function ModelCenter({ onConfig, onLegacy, busy }: { onConfig: (value: Co
</section>}
{tab === 'pools' && <><div className="mc-section-title"><div><h3>模型池</h3><p>按能力、凭据、健康和并发选择成员,切换保留已完成操作。</p></div><button className="button primary" disabled={locked} onClick={() => { setPool(emptyPool); setPoolEditing(true); }}><Plus size={16} />新建模型池</button></div>
{!view.pools.length && <p className="mc-empty">添加多个连接后建立模型池,设置轮询与故障切换规则。</p>}
{view.pools.map(value => <article className="mc-pool" key={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {value.sticky ? '运行内保持连接' : '每次请求重新选择'}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{view.connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); if (alive.current) onConfig(result.config); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
{view.pools.map(value => <article className="mc-pool" key={value.id}><Layers3 size={23} /><div><h4>{value.name}</h4><p>{value.strategy === 'weighted' ? '权重轮询' : '顺序轮询'} · {value.members.length} 个成员 · {value.maxAttempts} 次尝试上限 · {value.sticky ? '运行内保持连接' : '每次请求重新选择'}</p><div className="mc-members">{value.members.map(member => <span key={member.connectionId}>{view.connections.find(connection => connection.id === member.connectionId)?.name} ×{member.weight}</span>)}</div></div><div className="mc-actions"><button className="button secondary" disabled={locked} onClick={() => { setPool(value); setPoolEditing(true); }}>编辑</button><button className="button primary" disabled={locked} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: 'pool', id: value.id }); onConfig(result.config, { type: 'pool', id: value.id!, name: value.name }); })}>{selected?.id === value.id ? '当前模型池' : '使用此模型池'}</button></div></article>)}
{poolEditing && <form className="mc-editor" aria-label="编辑模型池" onSubmit={event => { event.preventDefault(); void act(async () => { await api('/model-center/pools', pool); if (alive.current) setPoolEditing(false); }); }}><h3>模型池规则</h3><div className="mc-form-grid"><label>模型池名称<input required value={pool.name} onChange={event => setPool({ ...pool, name: event.target.value })} /></label><label>调度策略<select value={pool.strategy} onChange={event => setPool({ ...pool, strategy: event.target.value })}><option value="round-robin">顺序轮询</option><option value="weighted">权重轮询</option></select></label><label>单请求尝试上限<input type="number" min="1" max="8" value={pool.maxAttempts} onChange={event => setPool({ ...pool, maxAttempts: Number(event.target.value) })} /></label><label>排队上限(秒)<input type="number" min="1" max="60" value={pool.queueTimeoutMs / 1000} onChange={event => setPool({ ...pool, queueTimeoutMs: Number(event.target.value) * 1000 })} /></label></div><label className="mc-checkbox"><input type="checkbox" checked={pool.sticky} onChange={event => setPool({ ...pool, sticky: event.target.checked })} />同一运行优先保持连接;明确失败后才切换</label>
<fieldset><legend>模型池成员与权重</legend>{view.connections.map(connection => { const member = pool.members.find(value => value.connectionId === connection.id); return <label key={connection.id} className="mc-member-choice"><input type="checkbox" checked={!!member} onChange={event => setPool({ ...pool, members: event.target.checked ? [...pool.members, { connectionId: connection.id, weight: 1 }] : pool.members.filter(value => value.connectionId !== connection.id) })} /><span>{connection.name}<small>{connection.model || '尚未选择模型'} · {states[connection.status]}</small></span><input type="number" aria-label={connection.name + '权重'} disabled={!member} min="1" max="10" value={member?.weight ?? 1} onChange={event => setPool({ ...pool, members: pool.members.map(value => value.connectionId === connection.id ? { ...value, weight: Number(event.target.value) } : value) })} /></label>; })}</fieldset>
<div className="mc-actions"><button className="button secondary" type="button" onClick={() => setPoolEditing(false)}>取消</button><button className="button primary" disabled={locked || !pool.members.length}>保存模型池</button></div></form>}
</>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{view.connections.find(connection => connection.id === value.connectionId)?.name} · 尝试 {value.ordinal} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : '用量未知'}</p><code>Run {value.runId}</code>{value.reason && <p className="mc-card-warning">{value.reason}</p>}</article>)}</div></>}
{tab === 'attempts' && <><div className="mc-section-title"><div><h3>请求账本</h3><p>最近100次物理请求;最多保存1000次。未知用量保持未知。</p></div><span>{view.attempts.length} 条记录</span></div>{!view.attempts.length && <p className="mc-empty">当前没有模型中心请求。选择连接或模型池执行任务后,实际尝试会保存在这里。</p>}<div className="mc-attempts">{view.attempts.map(value => <article key={value.id}><div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span><strong>{value.model}</strong><time>{new Date(value.startedAt).toLocaleString()}</time></div><p>{view.connections.find(connection => connection.id === value.connectionId)?.name || '未派发'} · {value.protocol === 'responses' ? 'Responses' : value.protocol ? 'Chat Completions' : '能力筛选'}{value.streaming ? ' · 流式' : ''} · {value.ordinal ? '尝试 ' + value.ordinal : '未发送'} · {value.usageStatus === 'reported' ? `${value.usage?.prompt_tokens ?? '?'} 输入 / ${value.usage?.completion_tokens ?? '?'} 输出 tokens` : value.usageStatus === 'not_dispatched' ? '未产生请求用量' : '用量未知'}</p><code>Run {value.runId}</code>{value.stream && <div className="mc-stream-receipt"><p>{value.stream.terminal ? "响应完整终结" : "响应未完整,片段保留待核对"} · 已接收 {value.stream.bytes.toLocaleString()} bytes · {value.stream.frames} 个事件{value.stream.capturedBytes !== undefined && value.stream.capturedBytes < value.stream.bytes ? " · 仅保存上限内片段" : ""}</p><code>原流 SHA256 {value.stream.sha256}</code>{value.responseSha256 && <code>工件 SHA256 {value.responseSha256}{value.responseRedacted ? "(已脱敏)" : ""}</code>}{value.sessionId && value.responseArtifactId && <button className="button secondary" disabled={working} onClick={() => void act(async () => { await downloadArtifact(value.sessionId!, value.responseArtifactId!, "model-stream-" + value.id + ".sse"); })}>下载已保存的响应</button>}</div>}{value.reason && <p className="mc-card-warning">{value.reason}</p>}{!!value.rejections?.length && <p className="mc-route-rejections">{value.rejections.map(item => item.connectionName + ':' + (capabilityLabels[item.capability] ?? item.capability) + ' · ' + item.reason).join(';')}</p>}</article>)}</div></>}
{tab === 'imports' && <><div className="mc-section-title"><div><h3>已有配置导入</h3><p>先预览来源和模型,再导入。原客户端配置保持原样。</p></div><button className="button secondary" disabled={working} onClick={() => void act(async () => { const value = await api<{ sources: typeof discovery }>('/model-center/imports'); if (alive.current) setDiscovery(value.sources); })}>识别本机来源</button></div>
{view.imports.length > 0 && <><h4>已登记来源</h4>{view.imports.map(value => <article className="mc-import-source" key={value.id}><strong>{value.source}</strong><code>{value.path}</code><span>{value.enabled ? '每分钟检查' : '自动同步已关闭'}</span>{value.lastCheckedAt && <p>最近检查 {new Date(value.lastCheckedAt).toLocaleString()}</p>}{value.lastError && <p className="mc-card-warning">{value.lastError}</p>}{!!value.lastResult?.conflicts?.length && <p className="mc-card-warning">有 {value.lastResult.conflicts.length} 项与手动修改冲突,已保留工作台中的修改。</p>}<button className="button secondary" disabled={locked} onClick={() => void act(async () => { await api('/model-center/import-toggle', { id: value.id, enabled: !value.enabled }); })}>{value.enabled ? '关闭自动同步' : '启用自动同步'}</button></article>)}<button className="button secondary" disabled={locked || !view.imports.some(value => value.enabled)} onClick={() => void act(async () => { const result = await api<{ results: { imported?: string[]; conflicts?: string[]; error?: string }[] }>('/model-center/import-sync', {}); const imported = result.results.reduce((sum, value) => sum + (value.imported?.length ?? 0), 0); const conflicts = result.results.reduce((sum, value) => sum + (value.conflicts?.length ?? 0), 0); if (alive.current) setNotice(`已检查启用来源:更新 ${imported} 项,冲突 ${conflicts} 项。`); })}>立即同步已启用来源</button></>}
{discovery.map(value => <article className="mc-import-source" key={value.source}><strong>{value.source}</strong><code>{value.path || '当前版本尚无可发现的配置路径'}</code><span>{value.available ? value.supported ? '可预览' : '当前不支持' : '未发现'}</span>{value.detail && <p>{value.detail}</p>}<button className="button secondary" disabled={!value.available || !value.supported || locked} onClick={() => { setImportSource(value.source); setImportPath(value.path); }}>选择来源</button></article>)}
+2 -1
View File
@@ -12,7 +12,8 @@ export interface MobileTask extends MobileBrief {
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string } } | null;
run: { id: string; status: string; steps: number; toolCalls: number; stopReason: string | null; usage: MobileUsage } | null;
progress: { total: number; completed: number; unknown: { id: string; tool: string; state: string; runId: string }[] };
events: { id: string; label: string; phase: string; output: string; taskId?: string; runId?: string; createdAt: string; exitCode?: number }[];
events: { id: string; label: string; phase: string; output: string; taskId?: string; runId?: string; createdAt: string; exitCode?: number;
stream?: { status: string; protocol?: string; textCharacters?: number; textPreview?: string; toolFragments?: number } }[];
messages: { id: string; role: string; content: string; createdAt: string }[];
approvals: { id: string; taskId: string; runId: string; projectId: string; command: string; reason: string; shell: string; fingerprint: string; actionable: boolean }[];
changes: { id: string; path: string; reason: string; status: string; sha256: string; baseSha256: string; additions: number; deletions: number }[];
+7
View File
@@ -96,6 +96,13 @@ export function ToolRow({ event, selected = false, onSelect }: { event: ToolEven
</button>;
}
export function ModelStreamPreview({ event }: { event: ToolEvent }) {
const stream = event.stream;
if (!stream || stream.status === 'completed') return null;
return <div className="model-stream-preview" aria-label="模型输出片段"><div><strong>{stream.status === 'receiving' ? '正在接收' : '输出未完成'}</strong><span>{stream.protocol === 'responses' ? 'Responses' : 'Chat Completions'} · {stream.textCharacters ?? 0} 字符{stream.toolFragments ? ' · ' + stream.toolFragments + ' 个工具参数片段' : ''}</span></div>
{stream.textPreview && <pre>{stream.textPreview}</pre>}<p>片段仅供查看。完整响应核对前不执行工具;中断后保留原记录。</p></div>;
}
export function FailureCard({ failure, onDiagnose, onRetry, busy = false }: { failure: RuntimeFailure; onDiagnose: () => void; onRetry?: () => void; busy?: boolean }) {
return <div className="failure-card" role="alert">
<div className="failure-heading"><AlertTriangle size={17} /><span>{failure.source === 'model_connection' ? '模型连接' : '工作台运行'}</span><strong>{failure.title}</strong></div>
+1 -1
View File
@@ -119,7 +119,7 @@ export function MobileApp({ initialToken }: { initialToken: string }) {
{!!selectedTask.progress.unknown.length && <div className="mobile-unknown"><strong>{selectedTask.progress.unknown.length} 项工具结果需要核对</strong><p>请在电脑核对原输入和实际结果。刷新、重连和手机审批均不会自动重新执行。</p>{selectedTask.progress.unknown.map(item => <code key={item.id}>{item.tool} · {stateLabel(item.state)}</code>)}</div>}
{!!selectedTask.approvals.length && <section className="mobile-approvals"><h2><ShieldCheck size={18} />等待你的确认</h2>{selectedTask.approvals.map(approval => <article key={approval.id}><span>{approval.shell}</span><pre>{approval.command}</pre><p>{approval.reason}</p>{!me.device.permissions.approve ? <p className="mobile-muted">此设备仅可观察,请在电脑审批。</p> : !approval.actionable ? <p className="mobile-muted">原审批已失效,请在电脑核对。</p> : <div className="mobile-action-pair"><button disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: false })}>拒绝</button><button className="mobile-primary" disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: true })}>核对并批准</button></div>}</article>)}</section>}
<nav className="mobile-tabs" aria-label="任务内容">{[['progress', '执行进展'], ['changes', '文件差异'], ['checks', '检查与报告']].map(([key, label]) => <button key={key} aria-current={tab === key ? 'page' : undefined} onClick={() => { setTab(key); setDocument(null); }}>{label}{key === 'changes' && !!selectedTask.changes.length && <span>{selectedTask.changes.length}</span>}</button>)}</nav>
{tab === 'progress' && <section className="mobile-progress"><div className="mobile-section-heading"><h2>原执行记录</h2><span>{selectedTask.progress.completed} / {selectedTask.progress.total} 工具完成</span></div><ol>{selectedTask.events.map(item => <li key={item.id}><div><strong>{item.label || '执行事件'}</strong><span className={'mobile-state state-' + item.phase}>{stateLabel(item.phase)}</span></div>{item.output && <details><summary>查看原输出片段{item.exitCode !== undefined ? ' · 退出码 ' + item.exitCode : ''}</summary><pre>{item.output}</pre></details>}</li>)}</ol>{!selectedTask.events.length && <p className="mobile-muted">尚无工具执行记录。</p>}{selectedTask.messages.map(message => <article className="mobile-message" key={message.id}><span>{message.role === 'assistant' ? '代理回复' : '系统记录'} · {time(message.createdAt)}</span><p>{message.content}</p></article>)}<p className="mobile-muted">手机显示最近60条执行记录和8条回复;完整记录保留在电脑原会话。</p></section>}
{tab === 'progress' && <section className="mobile-progress"><div className="mobile-section-heading"><h2>原执行记录</h2><span>{selectedTask.progress.completed} / {selectedTask.progress.total} 工具完成</span></div><ol>{selectedTask.events.map(item => <li key={item.id}><div><strong>{item.label || '执行事件'}</strong><span className={'mobile-state state-' + item.phase}>{stateLabel(item.phase)}</span></div>{item.stream && item.stream.status !== "completed" && <div className="mobile-stream"><strong>{item.stream.status === "receiving" ? "正在接收模型输出" : "模型输出未完成"}</strong><span>{item.stream.textCharacters ?? 0} 字符 · 片段不执行工具</span>{item.stream.textPreview && <pre>{item.stream.textPreview}</pre>}</div>}{item.output && <details><summary>查看原输出片段{item.exitCode !== undefined ? ' · 退出码 ' + item.exitCode : ''}</summary><pre>{item.output}</pre></details>}</li>)}</ol>{!selectedTask.events.length && <p className="mobile-muted">尚无工具执行记录。</p>}{selectedTask.messages.map(message => <article className="mobile-message" key={message.id}><span>{message.role === 'assistant' ? '代理回复' : '系统记录'} · {time(message.createdAt)}</span><p>{message.content}</p></article>)}<p className="mobile-muted">手机显示最近60条执行记录和8条回复;完整记录保留在电脑原会话。</p></section>}
{tab === 'changes' && <section className="mobile-changes"><div className="mobile-section-heading"><h2>当前任务的改动</h2><span>{selectedTask.changes.length} 个文件</span></div>{!selectedTask.changes.length && <p className="mobile-muted">尚未提出文件改动。</p>}{selectedTask.changes.map(change => <button key={change.id} className="mobile-file-row" disabled={!!busy || !fresh} onClick={() => void openDiff(change)}><FileDiff size={19} /><div><strong>{change.path}</strong><span>{stateLabel(change.status)} · <b>+{change.additions}</b> / −{change.deletions}</span></div><ChevronRight size={17} /></button>)}<p className="mobile-muted">手机可查看原差异;应用、恢复和 Git 提交在电脑审查。</p></section>}
{tab === 'checks' && <section className="mobile-checks"><h2>工程检查</h2>{!selectedTask.checks.length && <p className="mobile-muted">尚无工程检查结果。</p>}{selectedTask.checks.map(check => <article key={check.id}><div className="mobile-section-heading"><strong>检查 {check.id.slice(0, 8)}</strong><span className={'mobile-state state-' + check.status}>{stateLabel(check.status)}</span></div><p>{check.summary}</p>{check.results.map((result, index) => <p className="mobile-check-result" key={index}><span>{result.name}</span><span>{stateLabel(result.status)}{result.exitCode !== undefined ? ' · ' + result.exitCode : ''}{result.tests ? ' · ' + result.tests.passed + '/' + result.tests.total + ' 项测试' : ''}</span></p>)}</article>)}<h2>原交付报告</h2>{!selectedTask.reports.length && <p className="mobile-muted">尚未生成交付报告。</p>}{selectedTask.reports.map(report => <button className="mobile-file-row" key={report.id} disabled={!!busy || !fresh} onClick={() => void act('document', async () => { const value = await verifiedText('/sessions/' + selectedTask.id + '/reports/' + report.id); if (chosen.current === selectedTask.id) setDocument({ title: report.kind === 'delivery-report-markdown' ? '交付报告' : '交付报告 JSON', ...value }); })}><ClipboardCheck size={18} /><div><strong>{report.kind === 'delivery-report-markdown' ? '交付报告' : '交付报告 JSON'}</strong><span>{report.bytes.toLocaleString()} bytes · 校验后显示</span></div><ChevronRight size={17} /></button>)}</section>}
{selectedTask.task && <div className="mobile-budget"><span>任务累计用量</span><strong>{selectedTask.task.usage.totalTokens.toLocaleString()} tokens / {selectedTask.task.budget.maxTokens.toLocaleString()}</strong>{!!selectedTask.task.usage.unknownRequests && <p>{selectedTask.task.usage.unknownRequests} 次用量未知,另按 {selectedTask.task.usage.estimatedUnknownTokens.toLocaleString()} tokens 估算;不计为已确认用量。</p>}</div>}
+4
View File
@@ -2,3 +2,7 @@
:root .mobile-document{width:100%;height:100dvh;max-height:100dvh;border:0;color:var(--ink)}
.mobile-task-title .mobile-goal p{font-size:14px;color:var(--ink);white-space:pre-wrap;margin-top:0}.mobile-task-title h1{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
.mobile-progress li > .mobile-stream { display: block; padding: 12px; margin-top: 10px; background: #f0f6f3; border-left: 2px solid #608271; }
.mobile-stream strong, .mobile-stream span { display: block; }
.mobile-stream span { color: #526658; font-size: 11px; margin-top: 6px; }
.mobile-stream pre { max-height: 240px; overflow-y: auto; margin-bottom: 0; }
+5
View File
@@ -27,3 +27,8 @@ html,body,#root{width:100%;height:100%;overflow:hidden}.workbench{grid-template-
.desktop-project-actions{display:flex;gap:10px;flex-wrap:wrap}.desktop-scope-note{margin:14px 0;color:var(--muted)}
.desktop-stop-row{display:flex;gap:18px;align-items:center;margin-top:26px;padding-top:20px;border-top:1px solid var(--line)}.desktop-stop-row>div{flex:1;min-width:0}.desktop-stop-row strong{color:var(--ink)}.desktop-stop-row p{margin:4px 0 0}.desktop-stop-row>.button{color:#a14236;border-color:#d5b1ab;flex-shrink:0}.desktop-error{color:#a14236;padding:12px;background:#fff6f2;overflow-wrap:anywhere}
@media(max-width:620px){.desktop-launch span{display:none}.desktop-host-facts{grid-template-columns:72px minmax(0,1fr);padding:13px;font-size:11px}.desktop-stop-row{align-items:flex-start;flex-direction:column}.desktop-project-actions>.button{flex-grow:1}.desktop-host-heading .button{min-height:34px;padding:5px 9px}}
.model-stream-preview { margin: 8px 0 16px; padding: 12px 16px; border-left: 3px solid #607f71; background: #f3f7f5; color: #284338; border-radius: 0 6px 6px 0; }
.model-stream-preview > div { display: flex; align-items: baseline; flex-wrap: wrap; gap: 10px; font-size: 12px; }
.model-stream-preview span, .model-stream-preview p { color: #52665b; font-size: 12px; }
.model-stream-preview pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 260px; overflow-y: auto; font: inherit; line-height: 1.7; margin: 10px 0; }
.model-stream-preview p { margin: 8px 0 0; }
+3 -1
View File
@@ -3,6 +3,7 @@ export interface Config {
contextLimit: number; maxSteps: number; maxOutputTokens: number; hasKey: boolean;
maxRunDurationMs: number; maxRunTokens: number; maxTaskTokens: number;
}
export interface ModelSelection { type: 'legacy' | 'connection' | 'pool'; id: string; name: string }
export interface WorkspaceOrigin { id: string; sourceProjectId: string; sourceSessionId: string; sourceRoot: string; sourceWorkspaceId: string | null; baseCommit: string; branch: string; commonGitDir: string; gitDir: string; fingerprint: string }
export interface WorkspaceIdentity { kind: 'local-project' | 'managed-worktree'; projectId: string; root: string; workspaceId?: string; sourceProjectId?: string; sourceSessionId?: string; sourceRoot?: string; sourceWorkspaceId?: string | null; baseCommit?: string; branch?: string; commonGitDir?: string; gitDir?: string; fingerprint?: string }
export interface Project { id: string; root: string; name: string; addedAt: string; workspace?: WorkspaceOrigin }
@@ -21,6 +22,7 @@ export interface ToolEvent {
input?: Record<string, unknown>; output?: string; durationMs?: number; startedAt?: string; finishedAt?: string;
source?: string; attempts?: number; diagnostic?: RuntimeFailure; exitCode?: number;
taskId?: string; runId?: string; invocationId?: string; artifactId?: string;
stream?: { status: string; protocol?: string; sequence?: number; bytes?: number; textCharacters?: number; textPreview?: string; toolFragments?: number };
}
export interface DiffPart { value: string; count: number; added?: boolean; removed?: boolean }
export interface Change {
@@ -59,7 +61,7 @@ export interface RuntimeDiagnostics {
}
export interface FileEntry { path: string; name: string; kind: string; bytes: number }
export interface OpenFile { path: string; content: string; sha256: string; bytes: number; bom?: boolean }
export interface Bootstrap { token: string; version: string; config: Config; projects: Project[]; sessions: SessionBrief[]; exampleProjectId: string | null; environment?: ExecutionEnvironment; eventCursor?: number; storage?: { engine: string; schemaVersion: number }; runtimeRoot?: string }
export interface Bootstrap { token: string; version: string; config: Config; modelSelection?: ModelSelection; projects: Project[]; sessions: SessionBrief[]; exampleProjectId: string | null; environment?: ExecutionEnvironment; eventCursor?: number; storage?: { engine: string; schemaVersion: number }; runtimeRoot?: string }
export interface ResearchDoc { id: string; title: string; description: string }
export type CodeQueryKind = 'all' | 'symbols' | 'imports' | 'files';
+2 -1
View File
@@ -14,7 +14,8 @@ export function mobileSession(store, runtime, session, redact = String) {
progress: { total: tools.length, completed: tools.filter(value => value.state === 'completed').length,
unknown: tools.filter(value => value.requiresVerification).map(value => pick(value, ['id', 'tool', 'state', 'runId'])) },
events: session.events.slice(-60).map(value => ({ ...pick(value, ['id', 'kind', 'phase', 'taskId', 'runId', 'createdAt', 'exitCode', 'durationMs']),
label: String(value.label ?? value.tool ?? '').slice(0, 240), output: String(value.output ?? '').slice(-4000) })),
label: String(value.label ?? value.tool ?? '').slice(0, 240), output: String(value.output ?? '').slice(-4000),
...(value.stream ? { stream: { ...pick(value.stream, ['status', 'protocol', 'sequence', 'bytes', 'textCharacters', 'toolFragments']), textPreview: String(value.stream.textPreview ?? '').slice(0, 4000) } } : {}) })),
messages: session.messages.filter(value => ['assistant', 'system'].includes(value.role)).slice(-8).map(value => ({ ...pick(value, ['id', 'role', 'createdAt']), content: String(value.content).slice(0, 12000) })),
approvals: session.approvals.filter(value => value.status === 'pending' && value.taskId === session.taskId && value.runId === session.runId).map(value => ({
...pick(value, ['id', 'taskId', 'runId', 'projectId', 'command', 'reason', 'shell', 'createdAt']),
+11 -2
View File
@@ -8,10 +8,17 @@ export async function readModelStream(response, config, signal, onProgress) {
const reader = response.body.getReader(), decoder = new TextDecoder('utf-8', { fatal: true }), hash = createHash('sha256');
const chunks = [];
let buffer = '', data = [], bytes = 0, frames = 0, sequence = -1, text = '', done = false, terminal = null, usage = null, finish = null;
let lastProgress = 0, responseId = null, validated = false;
let lastProgress = 0, responseId = null, validated = false, progressTimer = null, progressFailure = null;
const calls = new Map(), responseCalls = new Map();
const progress = force => {
if (!force && Date.now() - lastProgress < 100) return;
if (!force && Date.now() - lastProgress < 100) {
progressTimer ??= setTimeout(() => {
progressTimer = null;
try { progress(true); } catch (cause) { progressFailure = cause; void reader.cancel().catch(() => {}); }
}, 100 - (Date.now() - lastProgress));
return;
}
if (progressTimer) { clearTimeout(progressTimer); progressTimer = null; }
lastProgress = Date.now();
onProgress?.({ phase: 'running', streaming: true, protocol: config.protocol ?? 'chat-completions', streamSequence: frames,
streamBytes: bytes, textPreview: text.slice(0, 8000), textCharacters: text.length, toolFragments: Math.max(calls.size, responseCalls.size) });
@@ -85,6 +92,7 @@ export async function readModelStream(response, config, signal, onProgress) {
while (true) {
signal?.throwIfAborted();
const chunk = await reader.read();
if (progressFailure) throw progressFailure;
signal?.throwIfAborted();
if (chunk.done) break;
bytes += chunk.value.length; hash.update(chunk.value);
@@ -121,6 +129,7 @@ export async function readModelStream(response, config, signal, onProgress) {
validated = true; progress(true);
return { value, evidence: { bytes, frames, sha256: hash.copy().digest('hex'), terminal: true, protocol: config.protocol ?? 'chat-completions' } };
} finally {
if (progressTimer) clearTimeout(progressTimer);
try { await reader.cancel(); } catch {} reader.releaseLock();
onProgress?.({ streamCapture: Buffer.concat(chunks), stream: { bytes, capturedBytes: chunks.reduce((sum, item) => sum + item.length, 0), frames,
sha256: hash.digest('hex'), terminal: validated, terminalSeen: !!terminal || done, protocol: config.protocol ?? 'chat-completions' } });
+10 -4
View File
@@ -183,13 +183,19 @@ return async (request, response) => {
if (method === 'GET' && route === '/api/operations') {
return json(response, inspectOperations({ store, provider, runtime, server, appDirectory, version: APP_VERSION, parameters: url.searchParams }));
}
if (method === 'GET' && route === '/api/bootstrap') return json(response, {
if (method === 'GET' && route === '/api/bootstrap') {
const hub = provider.modelHub(store), selected = hub.state.selected;
const name = selected.type === 'pool' ? hub.state.pools.find(value => value.id === selected.id)?.name
: hub.connections().find(value => value.id === selected.id)?.name;
return json(response, {
token, version: APP_VERSION, config: { ...store.config, hasKey: provider.hasKey() },
modelSelection: { ...selected, name: name ?? '原模型连接' },
eventCursor: store.eventCursor, storage: store.storageInfo(), runtimeRoot: appDirectory,
environment: executionEnvironment(),
projects: store.projects, sessions: store.listSessions(), exampleProjectId: exampleProject?.id ?? null,
capabilities: { workspaces: 'owned-git-worktree-and-explicit-recovery', gitReview: 'durable-confirmation-boundary', requestContext: 'bounded-whole-request-and-history-artifacts', latestToolFeedback: 'sealed-original-result-fields', changeSets: 'reviewed-recoverable-batches', fileChanges: 'review', exactPatches: 'sha256-unique-anchors', codeIndex: 'bounded-ast-and-candidates', commands: 'per-call-approval', recovery: 'durable-tool-results', model: 'chat-completions-compatible', execution: 'task-run-step', events: 'persistent-cursor', artifacts: 'sha256-verified', checks: 'npm-and-python-counted-jobs', pythonChecks: 'bound-interpreter-and-structured-results', browserChecks: 'sealed-static-build-and-real-edge-assertions', projectInspection: 'bounded-source-and-git', projectMemory: 'project-scoped-source-fingerprint-and-expiry', gitDelivery: 'reviewed-local-snapshot', deliveryReports: 'evidence-json-markdown' },
});
});
}
if (method === 'GET' && route === '/api/diagnostics') {
const selected = url.searchParams.get('session');
const session = selected ? store.session(selected) : null;
@@ -223,13 +229,13 @@ return async (request, response) => {
const artifactMatch = route.match(/^\/api\/artifacts\/([a-f0-9-]+)$/);
if (method === 'GET' && artifactMatch) {
const artifact = store.owned('artifact', artifactMatch[1], url.searchParams.get('session'));
const text = store.artifactStore.read(artifact), offset = cursorNumber(url.searchParams.get('offset'));
if (url.searchParams.get('download') === '1') {
const extension = artifact.mediaType === 'application/json' ? '.json' : artifact.mediaType === 'text/markdown' ? '.md' : '.txt';
response.writeHead(200, { 'Content-Type': artifact.mediaType + '; charset=utf-8', 'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'attachment; filename="agent-workbench-' + artifact.kind + '-' + artifact.id + extension + '"' });
response.end(text); return;
response.end(store.artifactStore.readBytes(artifact)); return;
}
const text = store.artifactStore.read(artifact), offset = cursorNumber(url.searchParams.get('offset'));
const limit = Math.min(64000, url.searchParams.has('limit') ? cursorNumber(url.searchParams.get('limit')) : 16000);
return json(response, { ...artifact, content: text.slice(offset, offset + limit), offset, totalCharacters: text.length, truncated: offset + limit < text.length });
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { randomUUID, createHash } from 'node:crypto';
export const APP_VERSION = '1.16.0';
export const APP_VERSION = '1.17.0';
export function executionEnvironment() {
const windows = process.platform === 'win32';
+2 -2
View File
@@ -8,8 +8,8 @@
2. [complete] B:Responses实际Items/工具call_id/原用量和私有reasoning续接已实现,混合池按实际线路封存请求;专项与原连接兼容42项通过,旧证据不改。
3. [complete] C:Chat/Responses有界SSE、原工具参数/终结核对、断流不重发、停止原HTTP、片段与原响应工件已通过专项;新增字节/超时边界复核中。
4. [complete] D:租约前按能力排除,原Run账本保留拒绝;文本/工具/流式各自检测及修订失效已实现。补查原对象toggle别名导致检测失效遗漏,已修复并加入回归。
5. [in_progress] E:模型中心协议/能力/范围、请求账本与桌面/手机流状态已实现并构建通过;正在实际操作桌面/390px/手机页面,不将窄屏夹具当实机。
6. [pending] F:三工程/故障验证、完整历史回归、独立源码/便携/安装、保留状态部署、证据/文档封存及本地Git;逐切片回顾。
5. [complete] E:模型中心协议/能力/范围、请求账本与桌面/手机流状态已实现并构建通过;5组真实桌面/390px/手机页面流程通过并目视回看,选择/刷新/执行/停止/断流/下载已核对;窄屏夹具不当实机。
6. [in_progress] F:三工程/故障验证、完整历史回归、独立源码/便携/安装、保留状态部署、证据/文档封存及本地Git;逐切片回顾。
## 2026-10-31 已交付:1.16 手机伴随端
+20 -1
View File
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import http from 'node:http';
import { createHash } from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { fixture, until, assertToolPairs } from './helpers.mjs';
import { fixture, until, assertToolPairs, launchWorkbench } from './helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { readModelStream } from '../src/core/models/model-stream.mjs';
@@ -12,6 +12,16 @@ const sse = event => 'data: ' + (typeof event === 'string' ? event : JSON.string
const chat = (delta, finish_reason = null) => sse({ choices: [{ index: 0, delta, finish_reason }] });
const chatEnd = (reason = 'stop') => chat({}, reason) + sse({ choices: [], usage: { prompt_tokens: 20, completion_tokens: 10 } }) + sse('[DONE]');
const native = (type, value, sequence_number) => sse({ type, sequence_number, ...value });
test('HTTP download preserves original malformed SSE bytes and artifact SHA instead of decoding invalid UTF8', async t => {
const f = fixture(t), bytes = Buffer.from([100, 97, 116, 97, 58, 32, 0xff, 10, 10]);
const artifact = f.store.artifactStore.write(f.session, null, bytes, { kind: 'model-stream-response', mediaType: 'text/event-stream' });
f.store.core.artifact.set(artifact.id, artifact); f.store.save(f.session); f.store.close();
const host = await launchWorkbench(t, f.data);
const response = await fetch(host.url + '/api/artifacts/' + artifact.id + '?session=' + f.session.id + '&download=1', { headers: { 'X-Workbench-Token': host.bootstrap.token } });
assert.equal(response.status, 200); const downloaded = Buffer.from(await response.arrayBuffer());
assert.deepEqual(downloaded, bytes); assert.equal(createHash('sha256').update(downloaded).digest('hex'), artifact.sha256);
});
async function streamingServer(t, handler) {
const requests = [], sockets = new Set();
const server = http.createServer(async (request, response) => {
@@ -113,6 +123,15 @@ test('explicit streaming probe uses actual SSE despite unknown declaration and b
assert.equal(view.capabilityEvidence.attemptId, hub.view().attempts[0].id); assert.equal(f.session.events.length, 0);
});
test('coalesced initial SSE events publish the latest partial state even when the upstream stays idle', async t => {
const f = fixture(t), server = await streamingServer(t, async res => {
res.write(native('response.created', { response: { id: 'resp_idle' } }, 0) + native('response.output_text.delta', { delta: '等待中的实际片段' }, 1));
});
const { provider } = configure(f, server, 'responses'), runtime = new Runtime(f.store, provider); t.after(() => runtime.stopAll());
runtime.start(f.session.id, 'Inspect'); await until(() => f.session.events.some(item => item.stream?.textPreview === '等待中的实际片段'));
assert.equal(runtime.isActive(f.session.id), true); runtime.stop(f.session.id); await until(() => !runtime.isActive(f.session.id));
});
test('stream timeout closes the original HTTP response, preserves redacted capture and never retries', async t => {
const f = fixture(t); let closed = false;
const server = await streamingServer(t, async res => { res.on('close', () => { closed = true; }); res.write(chat({ content: 'owned-secret partial' })); });