12 KiB
DSH Diagnostic Workspace Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [x]) syntax for tracking.
Goal: 在现有工作台提供尽可能复用 DSH 的三栏运行诊断体验、真实阶段推送与受控诊断命令。
Architecture: 官方 DSH 0.2.1-rc.2 headless 继续负责模型运行,应用适配原生阶段事件。会话状态和加密事件同库事务提交,SSE 与轮询读取同一递增序列;原生布局/命令纯逻辑优先提取复用,工作台负责身份、权限、业务证据和确认执行。
Tech Stack: Node.js >=22.13、CommonJS、SQLite/AES-GCM、原生浏览器 JS、Tabler、Playwright、官方固定 DSH。
Spec: approved design,用户于 2026-10-27 批准执行并强调尽可能复用 DSH/做适配。
Global Constraints
- 原地使用用户明确创建的
dsh分支;不切换主分支,不提交原有三个未跟踪业务文档。 - 继续使用官方 DSH 0.2.1-rc.2 最小 profile;不为模仿原生界面挂载文件/Shell/MCP/插件/自主任务工具。
- 保留个人会话归属、角色、操作审计、100 轮限制、每日额度、全局最多 2 个模型调用。
- 首版“流式”指真实阶段/受控操作进展推送;不包含逐 token 回答。
thinking、原始 stderr、运行环境、密钥、原始 cwd 不进入 UI 事件;回答与卡片只在完整校验后发布。- 不改变业务发送资格、归档前置关系、收件人、业务规则或 SMTP unknown 的人工核验边界。
- 不启用真实模型、不调用真实恢复操作、不重启/部署正在运行的服务。
- 无新增前端构建链;上游源码提取须固定版本、文件和 MIT 许可。
Task 1: Durable events and official headless adaptation
Files: create src/modules/assistant/conversation-events.cjs, src/modules/assistant/dsh-events.cjs, tests/assistant/workspace-events.test.cjs; modify assistant store.cjs, service.cjs, conversation-history.cjs, dsh-runtime.cjs.
Interfaces:
-
store.events(id, owner, {after=0,limit=100}) -> {events,nextCursor,hasMore}; events{schemaVersion:1,conversationId,seq,turnId,actionId?,kind,at,data}. -
store.eventCursor(id,owner) -> number;store.stage(turnId,kind,data={}); conversation includeseventCursor. -
service.send(id,principal,text,{diagnostic,requestId,repair}={})remains synchronous; stores request identity before a model task is launched. Same request and payload reuses turn, conflict rejects 409. -
runtime.chat({...existing,onEvent})sends sanitized native lifecycle callbacks synchronously; only statuses exposed, full reply returned as before. -
Persist
turn.diagnosticSnapshotwith already sanitized context actually used; stored encrypted.cancelRequestedis transient until exit confirmation; unknown stop/result remains needs_review. -
Write behavior tests before implementation: create store, begin/update turn, verify ordered events and encrypted disk, reject other owner and ahead/negative cursors; restart produces interruption events; request dedup uses one model call and conflicts on changed payload.
const c=store.create('alice');
const t=store.beginTurn(c.id,'alice','diagnose');
const before=store.eventCursor(c.id,'alice');
store.updateTurn(t.id,'success',{reply:'checked'});
assert.ok(store.events(c.id,'alice',{after:before}).events.length>0);
assert.throws(()=>store.events(c.id,'bob',{}),e=>e.status===404);
- Run
node --test tests/assistant/workspace-events.test.cjsand capture expected missing event interface failure. - Add transactional encrypted event table; reuse existing store transactions (nested writes run within existing transaction), bounded 128 events per turn with reserved terminal slots; stage only safe schema fields. Use persisted states as authority, not event text.
// All state changes and UI events share the assistant database transaction.
store.transaction(()=>{ /* update existing turn and append validated event */ });
// Native NDJSON status arrives before process completion.
onEvent?.({kind:'model',data:{phase:'step_start'}});
- Add incremental UTF-8 NDJSON decoder and native event validation, retaining existing final parsing/timeout/tree cleanup; reject tools/errors/unknown events, immediately discard thinking and never publish text JSON fragments.
- Integrate stage, dedup, stored evidence, cancellation, action progress/terminal and recover events without changing authorization, final parsing or action execution semantics.
- Run new tests and
node --test --test-concurrency=1 tests/assistant/assistant.test.cjs tests/assistant/dsh-runtime.test.cjs tests/assistant/controlled-operations.test.cjs tests/assistant/conversation-lifecycle.test.cjsand commit only owned files.
Task 2: Authenticated diagnostics and resilient event transport
Files: create assistant diagnostic-context.cjs, event-stream.cjs, tests/assistant/workspace-http.test.cjs; modify policy.cjs, api.cjs, conversation-history.cjs, src/app/dashboard.cjs, src/app/application.cjs.
Interfaces: consumes Task 1 events/store methods; produces /assistant/context, /conversations/:id/events?after=N, /stream?after=N; assistantStreams.close() drains streams. Add query search and {diagnostic,requestId} request validation.
- Write HTTP tests for owner-only event replay, heartbeat, Last-Event-ID, future/invalid cursor rejection, cookie invalidation and clean close. Context tests prove reads have no external side effects and diagnostic IDs are reauthorized server-side.
assert.equal((await call('/api/assistant/conversations/'+id+'/events?after=-1',undefined,cookie)).status,400);
assert.equal((await call('/api/assistant/context',undefined,cookie)).status,200);
assert.equal(modelCalls,0);
- Run
node --test tests/assistant/workspace-http.test.cjs, observe expected route failures. - Project context from existing snapshot + source authorization; only present identifiers already readable on business pages. Validate exact
/help /status /bpm /storage /archivecommand catalog, string targets and unknown fields; prohibit automatic command-to-write dispatch. - Add safe cursor parsing; SSE reads durable log in ascending batches so replay/live transition cannot miss events. Keep last cursor only after frame write, bound buffer 256KiB, each user max2/global30 streams, 15s heartbeat+reauth. End streams before
server.closeand databases. No timer or listener leaks on disconnect.
response.write('id: '+event.seq+'\nevent: assistant_event\ndata: '+JSON.stringify(event)+'\n\n');
// Poll and SSE use exactly store.events and never call service.send/executeAction.
- Extend title search: active limit50, archived recent2000, chunk100 with event-loop yields, encrypted titles only and explicit search range/truncation.
- Run HTTP tests, assistant legacy HTTP tests and shutdown tests; commit only task files.
Task 3: DSH native three-column workspace and commands
Files: create web/modules/assistant/{dsh-native,layout,conversation,commands,context-panel,events-client}.js, workspace.css, license/source notice and UI behavior tests; modify assistant view.js, operations.js, web/index.html, src/app/assets.cjs, web/app.js as needed for disposal.
Interfaces: browser globals AssistantNative, AssistantLayout, AssistantConversation, AssistantCommands, AssistantContextPanel, AssistantEvents; modules consume configured {api,esc,formatDate,user} and return explicit cleanup functions. Keep window.AssistantViews.configure/render/settings.
- Add UI tests that fail current page: at1366×768 input visible;
/helpand/statuscause zero model calls; unknown commands stay in draft; narrow panes mutually exclusive; phase updates retain reply DOM/selection; cleanup closes SSE on navigation; repair result blocked/needs_review uses actual label. - Run
node --test tests/assistant/diagnostic-workspace-ui.test.cjs, record missing layout/command failures. - Extract pure native
clampWidth/computeColumnsand command resolution/search functions from installed fixed DSH bundle; adapt only dependency/exports wrappers. Retain license and exact source mapping. Use these helpers in actual layout and menu; no unused vendor assets.
const columns=AssistantNative.computeColumns(width,sidebarOpen?264:0,rightOpen?320:0,width<880?0:56);
// Native command resolution targets only the project's fixed catalog.
- Replace stacked cards with compact header/left catalog/middle transcript+composer/right tabs; move audit/admin advanced form into right side. Keep old action IDs and API permissions. Render authoritative action result distinctions and target/impact before confirm.
- Update keyed transcript nodes instead of replacing messages.innerHTML; safe Markdown headings/lists/tables/code and links with escaped raw HTML/no remote images. Preserve per-conversation in-memory draft/scroll/folds; text copied via explicit button.
- Add typed target selections, exact commands, keyboard/IME, whitespace/length validation; one requestId per send attempt until server outcome resolved. Retrying diagnosis creates new round, never executes actions.
- Add authenticated fetch SSE client with1/2/4/8/15s backoff, fallback after3 stream failures to3s event polling, SSE probe every60s, abort on leave/logout, no automatic message POST retry. Handle new data without stealing reading scroll.
- Run new and legacy UI tests; four viewport screenshots inspected; commit owned files.
Task 4: Integration review and validation
Files: docs/user-guide.md, design status, plan checkboxes, docs/dsh-workspace-verification-2026-10-27.md; fixes scoped to findings.
- Independently review state transitions, authorization, external side effects, schema compatibility, NDJSON limits, SSE replay/close and native source usage. Fix important issues with covering tests.
- Execute
npm ci, assistant suite, freshnpm test, thennpm run test:fullbecause shutdown paths change. Save isolated receipts under ignored output and distinguish failures reproducible at baseline from regressions; do not present a filtered run as full pass. - Inspect screenshots at1600×900,1366×768,1024×768,390×844; validate real fixed official DSH using local fake Messages provider only; no real model enabled or service restart.
- Update guide and verification with exact commands/counts, source reuse evidence and limitations. Mark tasks according to evidence, commit scoped tracked files, leave user untracked documents intact.
Execution rulings
- User already authorized implementation; execute inline with specialist implementation/review, without new preference/approval prompts.
- Existing
dshbranch is the user-selected workspace; no additional worktree is required for this in-place task. Tests use temporary state directories, not running business state. - Backend Task1 and root's frontend/transport work own separate files until integration; only one implementation subagent is active at a time. Code reviews are read-only.
- Fresh baseline receipts are kept separately; only test failures with evidence of preexistence may be labeled pre-existing.
Execution outcome
2026-10-27 已实施。最终隔离业务回归334/334通过,独立审查无未解决P1/P2;全量按181+33个文件分段覆盖,旧流程/环境失败如实保留。详细结果见验证记录。本轮未部署运行服务。