Skip to content

Commit a28bceb

Browse files
fengzhi09claude
andauthored
fix(webui): exec stream events + P17 svg escape + PB-1 session context actions + PB-8 services window + M4-3a deleteSession facade (#159)
* docs(webui): the engine layer has six files, not five (webui-parity 107) ARCHITECTURE.md:492 counted five files under server/engine/ while the directory has shipped six since #143. The missing one is providers/local-runtime-v2.capabilities.js, the declaration-only module whose sole import is ../capabilities.js — the split that keeps the v2 host's ~4.7 s TypeScript dependency tree off the boot path. The local-runtime-v2.js row credited itself with the declaration it only re-exports, so that credit moves to the file that actually defines it. The zh-CN mirror takes the same edit in the same commit (equal weight); check-docs-alignment.mjs resolves the new bare-path citation against the merged tree. * test(webui): M2 capability-declaration snapshot vs the real host (engine-abstraction M2) Baseline: feat/engine-capabilities (M1, PR #143), NOT main — the server/lib/engine -> server/engine path fix has not landed yet. - test/lib/engine/capability-snapshot.test.js boots ONE real catalogue host on an isolated tmp data dir (MINIMAX_DATA_DIR + every MCODE_WEBUI_* path pinned before the provider import) and audits every full/partial key of both providers against the reflected surfaces: full requires every tracked method (REQUIRED_METHODS, derived from the live prototype chains — 91 adapter / 94 CliService methods — not copied from the design matrix); partial requires the present half to exist, method-named missing items to be genuinely absent (under-declaration goes red), and kebab-case sub-capability names to have no covering method; none is not method-checked. - Mutation tests pin the checker itself: flipped level / deleted method / grown sub-capability each go red (also verified by hand: three file mutations red at exit 1, restored byte-identical). - Registry-driven static guard: every registered provider declares exactly ENGINE_CAPABILITY_KEYS — typo keys cannot pass silently, and M4 providers are swept without editing the test. - Docs: ARCHITECTURE.md/.zh-CN.md M2 section, webui.md/.zh-CN.md migration-state entry; tmp prefix registered in the leak gate. * test(webui): point the capability snapshot at the engine layer's real path The M1 path move took server/lib/engine to server/engine. This file was written against the old one and rebase carried the code forward without carrying the import, so the suite failed on MODULE_NOT_FOUND and said nothing about the capabilities it was meant to check. * fix(webui): stop the shell from carrying one session's state into another Three leaks, all from state that lived outside the component that should have owned it. page.tsx read localStorage during render, so the pre-rendered HTML and the first client frame could not agree — a skeleton screen was hiding it, which is exactly the kind of cover that disappears the moment someone edits the shell. The first frame now uses defaults and one mount effect restores; the three write-back mirrors are gated so a default never overwrites a stored value. Scroll position is read by the same sessionKey effect Chat already had, which reads the same key. The draft store was a module-level bucket, so a draft, a failure banner and a model chip all followed you across sessions — type into one conversation, switch, and your words are in the other. The store is keyed by session now. Isolation is not discarding: switching back finds the draft still there. Clearing was the alternative and it destroys an unread banner every time you return to a conversation. #126 left the accepted-but-unconfirmed banner without anything to consume it when a turn ended. unconfirmedPatchOnTurnEnd clears it on the falling edge of running, and only there — the three-value decision about when to show it is untouched. * refactor(webui): the plugins and turn-diff routes take the host from the engine facade Migration step M3, batch B0 (engine-abstraction). 13 endpoints across routes/plugins.js and routes/turn-diff.js reached the catalogue host by importing lib/acp-client.js#getCatalogueHost directly. They now call getEngineCatalogueHost() from the facade. - engine/host.js: the lazy bridge. Its only import is a dynamic `await import("../lib/acp-client.js")` inside the function body, so engine/index.js gains a function and not a module load. That boundary is the whole point: app.js reaches engine/index.js through routes/engine-capabilities.js, and a static import of acp-client there would put the ACP client tree on every server start — the regression M1 paid for once (209ms -> 2700ms; facade load 4685ms -> 5ms once declaration and construction were split). The value is forwarded verbatim, `null` included, so "host did not boot" stays RUNTIME_UNAVAILABLE and never a second host. - engine/index.js re-exports the getter; the two routes import it from there and no longer name acp-client.js. - No endpoint behaviour changes: same wire shapes, statuses, codes, same `deps.getCliService` / `deps.getDiffApplication` seams, same one process-wide host. Measured on the module graph: routes/plugins.js drops from 13 product files + @mavis/shared to 8 files and zero bare packages; engine/index.js's whole closure is 6 files and 0 bare specifiers. Server start and the facade's own load are unchanged (facade ~1.2ms -> ~3ms, i.e. one more 45-line zero-import file; boot stays in the same 200-300ms band) because lib/state-bus.js already pulls acp-client into app.js's boot graph — closing that edge belongs to the catalogue read/write batches (M3-B1+), not here. Tests: test/lib/engine/host-facade.test.js pins the contract against the real module graph rather than against source text — a resolve hook (module.registerHooks) in a fresh process reports, per parent, which specifiers each entry resolved. It asserts neither route has a direct edge to acp-client/runtime-host/acp.mjs, that loading engine/index.js pulls no host module and no @mavis/* or @minimax/* package, that engine/host.js is in that closure, and the source-shape tripwires (dynamic import only, facade re-export). Mutation-checked: making the facade import statically turns 4 tests red, making plugins.js import directly turns 4 more red. The existing plugins/turn-diff suites pass unchanged under both transports (158 tests x acp and x runtime). Docs: ARCHITECTURE.md + .zh-CN.md — the engine/ file table gains engine/host.js on top of the six files #143 + the doc batch settled, the "one host" rule now names the facade, and the boot-path discipline is stated where the file list lives. docs/webui.md + .zh-CN.md are untouched: no user-visible change. Source inventory regenerated for the two new files (rebase conflict in it was resolved by taking the upstream copy and regenerating, never by hand). * test(webui): make the run-mirror, first-turn-guard and mavis-usage suites immune to the gate's isolation env The webui gate runs with MCODE_WEBUI_DATA_DIR, MCODE_WEBUI_SETTINGS_PATH and MINIMAX_DATA_DIR exported at a scratch directory. Two suites read paths those exports take away from them: - config.js#resolveDataDir reads MINIMAX_DATA_DIR ?? MAVIS_DATA_DIR, so the gate's MINIMAX_DATA_DIR outranked mavis-usage.check.mjs's own MAVIS_DATA_DIR fixture and every DB-backed case resolved null against a scratch dir that holds no runtime-state.sqlite. The suite now exports the name that wins. - config.js resolves SESSIONS_DB as MCODE_WEBUI_SESSIONS_DB || join(WEBUI_DATA_DIR, "sessions.json"). A caller that exports MCODE_WEBUI_SESSIONS_DB redirects the store, while the suite's beforeEach still cleared join(DATA_DIR, "sessions.json") — so each run read the previous run's records and the mid-run switch resolved an id whose workspace belonged to a since-removed tmp dir. Both chat-route suites now pin MCODE_WEBUI_SESSIONS_DB to the same path their cleanup clears. Test-only: no server/ code, no helper under test/helpers/_setup.js, and no assertion weakened or skipped. Verified with the three variables set, with MCODE_WEBUI_SESSIONS_DB additionally set, and bare. * refactor(webui): the plugins and turn-diff routes take the host from the engine facade Migration step M3, batch B0 (engine-abstraction). 13 endpoints across routes/plugins.js and routes/turn-diff.js reached the catalogue host by importing lib/acp-client.js#getCatalogueHost directly. They now call getEngineCatalogueHost() from the facade. - engine/host.js: the lazy bridge. Its only import is a dynamic `await import("../lib/acp-client.js")` inside the function body, so engine/index.js gains a function and not a module load. That boundary is the whole point: app.js reaches engine/index.js through routes/engine-capabilities.js, and a static import of acp-client there would put the ACP client tree on every server start — the regression M1 paid for once (209ms -> 2700ms; facade load 4685ms -> 5ms once declaration and construction were split). The value is forwarded verbatim, `null` included, so "host did not boot" stays RUNTIME_UNAVAILABLE and never a second host. - engine/index.js re-exports the getter; the two routes import it from there and no longer name acp-client.js. - No endpoint behaviour changes: same wire shapes, statuses, codes, same `deps.getCliService` / `deps.getDiffApplication` seams, same one process-wide host. Measured on the module graph: routes/plugins.js drops from 13 product files + @mavis/shared to 8 files and zero bare packages; engine/index.js's whole closure is 6 files and 0 bare specifiers. Server start and the facade's own load are unchanged (facade ~1.2ms -> ~3ms, i.e. one more 45-line zero-import file; boot stays in the same 200-300ms band) because lib/state-bus.js already pulls acp-client into app.js's boot graph — closing that edge belongs to the catalogue read/write batches (M3-B1+), not here. Tests: test/lib/engine/host-facade.test.js pins the contract against the real module graph rather than against source text — a resolve hook (module.registerHooks) in a fresh process reports, per parent, which specifiers each entry resolved. It asserts neither route has a direct edge to acp-client/runtime-host/acp.mjs, that loading engine/index.js pulls no host module and no @mavis/* or @minimax/* package, that engine/host.js is in that closure, and the source-shape tripwires (dynamic import only, facade re-export). Mutation-checked: making the facade import statically turns 4 tests red, making plugins.js import directly turns 4 more red. The existing plugins/turn-diff suites pass unchanged under both transports (158 tests x acp and x runtime). Docs: ARCHITECTURE.md + .zh-CN.md — the engine/ file table gains engine/host.js on top of the six files #143 + the doc batch settled, the "one host" rule now names the facade, and the boot-path discipline is stated where the file list lives. docs/webui.md + .zh-CN.md are untouched: no user-visible change. Source inventory regenerated for the two new files (rebase conflict in it was resolved by taking the upstream copy and regenerating, never by hand). * test(webui): make the run-mirror, first-turn-guard and mavis-usage suites immune to the gate's isolation env The webui gate runs with MCODE_WEBUI_DATA_DIR, MCODE_WEBUI_SETTINGS_PATH and MINIMAX_DATA_DIR exported at a scratch directory. Two suites read paths those exports take away from them: - config.js#resolveDataDir reads MINIMAX_DATA_DIR ?? MAVIS_DATA_DIR, so the gate's MINIMAX_DATA_DIR outranked mavis-usage.check.mjs's own MAVIS_DATA_DIR fixture and every DB-backed case resolved null against a scratch dir that holds no runtime-state.sqlite. The suite now exports the name that wins. - config.js resolves SESSIONS_DB as MCODE_WEBUI_SESSIONS_DB || join(WEBUI_DATA_DIR, "sessions.json"). A caller that exports MCODE_WEBUI_SESSIONS_DB redirects the store, while the suite's beforeEach still cleared join(DATA_DIR, "sessions.json") — so each run read the previous run's records and the mid-run switch resolved an id whose workspace belonged to a since-removed tmp dir. Both chat-route suites now pin MCODE_WEBUI_SESSIONS_DB to the same path their cleanup clears. Test-only: no server/ code, no helper under test/helpers/_setup.js, and no assertion weakened or skipped. Verified with the three variables set, with MCODE_WEBUI_SESSIONS_DB additionally set, and bare. * feat(webui): the five read endpoints ask the engine facade, not the transport (M3-B1) The directory-read family — #9 acp-sessions, #10 acp-session-title, #72 protocol/list-sessions, #74 state, #75 health — reached the engine through whatever MCODE_WEBUI_TRANSPORT happened to be, so "does the engine support this" had no answer anywhere except the absence of a crash. server/engine/ session-reads.js gives it one: each endpoint declares the capability and the provider method it needs, the facade checks the registered provider's declaration first, and a provider that does not offer the read answers 501 through invokeHandler instead of an empty list. Nothing on the wire moves. The facade forwards to the same acp-client exports the routes already called, so the 30s cache, the cwd normalisation, the 30s-stale sidebar push semantics and the catalogue-sessions projection are the same code; handleHealth becomes async because the version now resolves through the facade, which is why app-hono's legacy-parity helper learned to await it. /api/state's snapshot field list is untouched — snapshotViewFields and mcodeSessionsSnapshotFields are the first-frame render contract and this batch adds and removes nothing. Each read also reports where its bytes came from — catalogue, acp, or acp-fallback when the runtime transport asked for a host that never booted. That is metadata, not wire, and it is the difference between a sidebar that degraded and one that pretends. Two things this batch found rather than assumed: the catalogue host exposes no version accessor, so /api/health keeps answering from the ACP initialize mirror and says so rather than inventing a method; and protocol.js#72's old test drove a mock key nothing read, so "the cwd filter works" had never actually been proven. * feat(webui): the session-tree and export endpoints ask the engine facade (M3-B2) Routes #8 GET /api/session-tree and #11 GET /api/sessions/:id/export through the engine facade instead of the transport, keeping every response shape, status code and reason string unchanged. The two families are separate files because their gate policies are opposite. The tree is entirely engine data, so a provider that cannot list sessions genuinely has no tree: assertSessionTreeCapability throws and invokeHandler answers 501. Export's primary source is sessions.json and the engine only contributes a best-effort transcript enrichment the endpoint has always promised never to block on, so checkSessionExportCapability reports and never throws — gating it hard would delete working functionality in response to a declaration about a capability the endpoint does not depend on. The tree route re-throws the capability error, matched with the class's own instanceof helper rather than a `.name` compare: `name` is a writable instance property, so a stray `err.name = "…"` would silently turn that 501 back into the 200 soft-fail the gate exists to prevent. A test pins both halves — the real class propagates, an impostor carrying the right `.name` does not. Verified by exporting the real tree (303 rows, 32 projects, 299 nodes) before and after and diffing every node's id/title/parent/depth: 3289 field comparisons, zero differences. A synthetic fixture covers what the live data does not contain (orphans, cycles, four-level nesting, exotic titles): 165 comparisons, zero differences. Two pre-existing shapes are pinned because a "cleanup" would silently break them — child nodes carry no `children` key (all 66 of them), and the response has no parent_session_id key at all. * feat(webui): the usage endpoints ask the engine facade, and the derived figures get one home (M3-B3) * fix(webui): rebase M3-B3 onto M3-B2, register B2's two tmp prefixes, and record the whole-namespace mock trap * feat(webui): the account, model and capability reads ask the engine facade (M3-B4) #20 /api/account, #57 /api/models and #73 /api/protocol/capabilities now reach the engine through three new engine/ modules instead of naming lib/mcode-rpc.js, lib/models.js, lib/providers-config.js, lib/engine-catalogue.js and lib/acp-client.js themselves. Three modules because the three gate policies are all different: the account read gates HARD on authCredentials.getAccountStatus (the same provider method B3's #15/#16 read, so a provider that drops it takes both down together), the model catalogue gates SOFT (its primary sources are files webui owns, so a hard gate would delete a working picker), and #73 declares nothing at all because it IS the declaration endpoint. The model projection moved whole — three sources, the per-provider dedupe, both builtin-tree annotations and the three derived figures are now named pure functions pinned on their inputs, and #57 is verified by a full snapshot whose oracle was captured from the pre-refactor implementation. Its read stays synchronous so handleGetModels keeps its contract, which is also why engine/model-reads.js is not re-exported from engine/index.js: its four sources reach @mavis/shared and js-yaml, and the boot-path guard is right to refuse that under the shared facade. #73 is the one response body in the migration that changes: it gains an `engine` key carrying the engine-capabilities view, with `providerFor` saying whether the declaration came from the active transport's provider or from the default one standing in. Every pre-existing key keeps its name, position and value, and the ACP wire table is not replaced by the 14 matrix keys. * feat(webui): #73 swaps the ACP wire table for the 14-key engine-capabilities view (user-approved contract change) `GET /api/protocol/capabilities` used to answer from two hand-maintained places: `MCODE_ACP_CAPABILITIES`, a flat `{method: boolean}` table of the ACP JSON-RPC surface, and the `initialize` agentInfo mirror. The engine's DECLARED capability surface already existed — the 14-key per-provider object that `GET /api/engine-capabilities` serves — so webui was carrying two parallel answers to "what can this engine do", able to disagree, with no test able to notice. This makes `capabilities` the declared object and drops the wire table from the endpoint. This is a reviewed, user-authorised endpoint contract change, not a refactor side effect, and it is stated as such in the module header, in `docs/API.md` and in both ARCHITECTURE twins. The twelve old accessors are asserted GONE, so a consumer reading `capabilities.set_mode` gets undefined and fails loudly rather than receiving a truthy object field. No runtime consumer exists: nothing in `webapp/` reads this endpoint, and `engine/capability-reads.js` no longer imports `lib/mcode-rpc.js` at all (pinned by a static tripwire, because an unused import is behaviourally inert and no behavioural test could see it). The `engine` key the previous commit added is REMOVED rather than kept: with `capabilities` already the declaration, an `engine` block would carry the same 14 keys a second time in one response. What survives from that shape is the provenance — `capabilitiesProvider` / `capabilitiesProviderFor`, the honest bit that says whether the declaration came from the active transport's provider or from the default one standing in — plus `capabilitiesUnavailable` for the derived degradation roll-up. A test counts the declaration's occurrences in the serialised body and requires exactly one, so a second carrier is a red bar. `MCODE_ACP_CAPABILITIES` is kept and stays pinned by `test/lib/mcode-rpc.check.mjs`: it is still a true statement about the ENGINE's ACP surface and `docs/CAPABILITIES.md` cites it as one. It has no webui consumer left, recorded as debt in the module header rather than deleted as a side effect. `docs/webui.md` and `docs/webui.zh-CN.md` gain a diff here for the first time in this migration: they carried the old response shape in their endpoint tables, and an authorised contract change has to be documented where the contract is written. * fix(webui): stop two B4 comments describing behaviour the code no longer has Found by the dual-axis code review (Standards + Spec) before B4 merges. No logic changes; both were documentation lying about the code next to it. `engine/index.js` still described #73 as an additive change — "the response body gains a key (`engine`, the engine-capabilities view) … additive rather than a replacement". The second B4 commit made it a REPLACEMENT and deleted the `engine` key, so the facade's own export table was the one place still telling a reader the opposite of what the endpoint does. It now states the replacement, why the `engine` key was removed rather than kept, and what survived from it (the provenance keys and the derived roll-up). `docs/ARCHITECTURE.md` and its zh-CN twin called `engine/account-reads.js`'s read **synchronous**. It is `async` — `readEngineAccount` awaits a `Promise.all` of dynamic imports — and the boot-path note the row pointed at describes model-reads, not this module. The same two documents already listed account-reads correctly under the `await import()` rule a few paragraphs down, so the file contradicted itself in two languages at once. Both rows now say asynchronous and point at the ordinary rule. Also drops a dead `assertEngineCapability` import from `engine/model-reads.js`: the soft gate inspects the declaration inline, so the throwing helper was never called and its presence read as if the soft path could still throw. Replaced by a comment saying why it is absent, so the next reader does not "fix" it back in. And the one comment with Chinese embedded mid-sentence (仓库 review 要求注释用英文) is now English; the header parentheticals naming each family (账户读 / 模型目录读 / 能力声明读) stay, as do the quoted product strings — `本地用户` is the real zh-CN value of `userMenu.localUser` and `shell.tsx` cites it the same way. * feat(webui): move the session write family behind the engine facade M3 batch B5: #7 DELETE /api/sessions/:id, #4 POST /api/sessions/rename and #6 POST /api/sessions/cleanup-orphans stop driving the store, the caches and the engine's own local_runtime_* tables from the route. They ask engine/session-writes.js instead, so the load -> resolve -> authorize -> intent-audit -> mutate ordering — and the resurrection guard inside it — becomes named, testable code rather than a two-line helper a route could call out of order. #7 and #6 gate HARD on sessionCrud.deleteSession, because the rows they destroy are the engine's own; #4 declares no capability at all, because a rename writes webui's own store and touches no engine surface. The policy is decided by who owns the rows the write destroys, which is a different question from the read families' and does not have the same answer twice in a row here. The facade exposes a plan/commit pair rather than one deleteSession(), so the write-ahead audit still lands between "know what the user asked to delete" and "delete it". Response bodies are built in the facade once, which is what lets the #6 and #7 dryRun shapes be pinned byte-for-byte by unit tests. No status code, response body or error code changes. The 32-table delete SQL stays in lib/mcode-session-delete.js and is reached by dynamic import; acp-client.js and four test files bind to that specifier, so collecting it is a later batch's job. Recorded as KNOWN DEBT, along with rename writing a webui-side label only, and delete not detecting an in-flight session. * fix(webui): drop whitespace text nodes in markdown tables and dedupe thinking label * fix(webui): sweep the non-flipping inverted text token off primary surfaces The authorize-button fix (08599472) surfaced five more primary surfaces pairing text-text_default_inverted_static with bg_interaction_primary_default; dark mode inverts that background to pure white while the token stays near-white, so the label composites to white-on-white. Swap all of them to text-text_label_primary_default and add a source-scan guardrail that keeps the pairing out of primary surfaces while pinning the sanctioned status-badge exception (toolbar). * feat(webui): move session switch behind the engine facade M3-B6: #3 POST /api/sessions/switch now asks the engine facade instead of reaching into lib/acp-client.js, lib/transcript.js, lib/mavis-usage.js, lib/models.js and lib/config.js from the route. The new engine/session-switch.js owns the four load-bearing facts the ~290-line handler had accumulated: the mvs-sid-first resolution order (single base-session identity), the backfill decision and its read, the workspace containment gate (which runs before any cs mutation, so a refused switch leaves the client untouched), and the response body. The gate is SOFT — it reports and never throws — because the switch's primary data is webui's own record and both engine touches have a defined degradation. Gating hard would remove a working endpoint over a title and a transcript, and would do it on the default acp transport first. The route keeps what is its own: the "id required" 400, the status mapping, the fail-closed audit and the SSE push — the audit has to land after the switch has already mutated cs, and the push must not fire when it fails. Behaviour is unchanged and pinned: the four red lines (transcript backfill, cumulative detection, workspace containment, single base session identity) each get named tests with their negative half, and the success body's key ORDER is compared as a string. Six mutations of the facade were run to prove the tests are load-bearing. KNOWN DEBT 1 in the new module records what this batch did NOT retire: the 3-candidate transcript probe. The default acp transport has no engine surface to replace it with, getMessages paginates where the probe caps lines, their orderings differ, and export's enrichment is still byte-pinned to the same candidates. What IS retired is the coupling — the route no longer names lib/transcript.js, and the probe list is an implementation detail behind one seam. * chore: allowlist the leak-tripwire fixture in model-reads tests gitleaks' generic-api-key rule flags the deliberate sk-secret-should- never-leak fixture that model-reads.test.js uses as a leak-prevention tripwire (asserting the facade never serializes provider keys). The value is fake and the assertion exists to catch real leaks; allowlist the exact pairing instead of weakening the fixture. * test(webui): pin session-writes cleanup-orphans test to isolated paths * chore: ignore gitleaks fingerprints of deliberate test fixtures The full-history scan flags two synthetic-credential fixtures: the model-reads leak tripwire (fake provider keys asserting the facade never serializes them) and the fs-credential-guard canaries (fake id_rsa/pem bodies asserting the 403 guard). Pin their fingerprints in .gitleaksignore; the .gitleaks.toml path allowlist for the same files stays as a coarse first line. * chore: make the gitleaks fixture allowlists path-only The match-targeted entry missed the byok fixture key (the generic rule's match string differs from the tripwire value the entry was written for). Scope both entries to the two fixture files themselves — every finding in them is synthetic by construction — and keep .gitleaksignore as the precise fingerprint layer. * feat(webui): move interrupt and load endpoints behind the engine facade * fix(webui): take the plan's 5s abort force-kill bound by product call The batch plan transcribed the abort bound as 5s; the migrated file ran 2000ms. The product call (2026-10-03) takes the plan's value: the longer grace gives a stubborn child more time to finalize at the cost of 'already stopped' staying a lie for three extra seconds. The pinning test moves with it and KNOWN DEBT 1 records the resolution. * docs(webui): add session-switch, interrupt and session-load to the architecture map * docs(webui): add the missing zh-CN section for the B5 write family * fix(webui): make webui-only session delete return promptly instead of hanging * fix(webui): retire lossy streaming mirrors when the engine transcript arrives * feat(webui): add the streaming-send capability gate and pure stream bridge M3-B8a (1 of 2) splits M3-B8 at the boundary the plan drew but the original batch crossed. This commit ships the PURE layer of the #12 send family: the streamingSend capability declaration, the HARD gate that enforces it, and the eight derivations that turn the runtime's stream vocabulary into webui's chat-line vocabulary. NO USER-VISIBLE CHANGE. The gate and the derivations are in place and tested, but nothing calls them: POST /api/send is not wired to a runtime branch yet and behaves exactly as it did at 32277c3a on every transport. Both the acp and the runtime failure sets are the pre-existing baseline core. M3-B8b adds the runner and the route branch and lights the transport up. The family gates HARD, the first M3 family to do so, because #12's response is {ok:true} written BEFORE the engine is called: a provider with no send surface could only be answered with an ack for a turn that never runs, and there is no truthful degradation to fall back to. The gate is deliberately unreachable today (v2 declares streamingSend: full; acp has no registered provider until M4), and the suite pins both halves of that so making it reachable is a deliberate edit. * feat(webui): run send on the runtime transport behind the engine facade M3-B8b (2 of 2) lights up POST /api/send on the runtime transport. It adds the half B8a deliberately left out: the runner, the route branch, and the data plane that opens a turn's event stream. The acp path is unchanged. runMcodeAcp and streamAcpPrompt were not edited, and the route's post-run tail — the finalize drain, promoteDraftToMcodeSid, persistCurrentChat, pushStateFor — is untouched, because the runtime runner resolves to the same result shape and writes through the same run-chat buffer. That is what makes run-mirror, the drain and the single-identity promotion structural rather than re-implemented: they cannot differ between transports. MCODE_USE_ACP=0 still outranks the new branch, as lib/config.js documents — the escape hatch exists for the moment a transport misbehaves, so an operator must not have to unset a second variable first. The three route-level test files that install a fake ACP transport now pin MCODE_WEBUI_TRANSPORT=acp at module scope. Before B8b the send endpoint had no sibling to follow, so no test had to declare which transport it was written against; that declaration is what stops an acp-path contract from silently becoming a runtime-path one. Recorded in engine/streaming-send.js: /api/stop cannot stop a runtime turn and says so; attachments reach the runtime without a mime type; the context limit is not bridged from the stream; a first runtime turn does not receive the user's model pick; transport selection is still an env read rather than a registry lookup. * feat(webui): answer set-mode and set-config-option with structured 501 when the capability is absent * docs(webui): add the streaming-send architecture section, bilingual * docs(webui): add the streaming-send architecture section, bilingual * fix(local-runtime): make an abandoned migration lease recoverable at startup The V2 agent cutover takes a dataDir lease before `mcode acp` can serve a prompt, and the lease is a bare directory: mkdir acquires, rmdir releases, a live holder heartbeats the directory mtime every `stale / 2`. A process killed between the two leaves the directory behind, and an abandoned lease is then indistinguishable from a held one except by that mtime. The window was 30 minutes while the retry budget was 120 attempts at this backoff shape — about 55 seconds. A waiter could not outlast the window, so every engine launch during it spent the whole budget and then died with `agent_name_conflict_migration_failed:lock`. One killed process therefore made `mcode acp` unstartable for half an hour, and each blocked launch produced no answer, no engine process and no session — the reported send regression. The stale window drops to 2 minutes. That does not weaken the safety property: proper-lockfile derives the heartbeat from the stale window, so "two missed heartbeats before the lease is called abandoned" is unchanged, and the migration re-inspects under the lease, so the worst a wrongly-considered stale lease costs is one extra inspection rather than a double rewrite. The retry budget rises to ~195s so a waiter survives one expiry and acquires instead of dying at the moment the lease becomes reapable. Verified against the live data directory: an orphaned lease took the engine from 55450ms/exit=1 to 2030ms/exit=0, and an isolated webui instance returned a real model reply with zero `acp exited` events. * feat(webui): move model and permission writes behind the engine facade * Reset dev-lhl to the full local integration line (B9+B10+docs+P13+P14+B8a/B8b) after push-order rollback * fix(webui): surface truncated acp stderr in failure alerts * feat(webui): move the provider family behind the engine facade with storage migration * fix(webui): acknowledge in-flight messages explicitly instead of echoing into a void * fix(webui): normalise the expected side of the provider cwd path assertion The macOS verify red was a TEST defect, not a product one. The product never resolved a provider path beyond what its resolver returned: `sources.cwd` is `join(process.cwd(), "models.json")`, and `process.cwd()` is `getcwd(2)`, which returns a fully-resolved path on every POSIX platform. The assertion built its expectation from the literal string the test had chdir'd into, so the two agreed only when the temp path had no symlink component — true on Linux CI, false on macOS, where `/var` is a symlink to `private/var`. Normalising the EXPECTED side is the fix, and the behaviour is now pinned rather than assumed: - the assertion states the contract (`process.cwd()` + the file name) instead of re-deriving it; - a named regression test drives a real symlinked cwd and asserts webui applies no second resolution of its own; - the same symlink machinery is applied to the WRITE path, where the question is a security one: the store is 0600 via tmp+rename and carries every plaintext apiKey, so a write that resolved its path differently from the read would put the keys in a file the catalogue never reads; - a source tripwire fails if a `realpath` (or equivalent) is ever added to the provider path resolution, so the symptom is not "fixed" in product code next time. Both the symlink behaviour and the tripwire were verified to bite: a `realpathSync` injected into `loadProvidersConfig` turns the symlink test, the sources test and the tripwire red. The whole B11 suite was re-run with TMPDIR pointed at a symlinked directory, which reproduces the macOS `/var` condition on Linux: 149 tests pass. The pre-fix assertion fails under exactly that condition and the post-fix one passes. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(webui): bridge thinkingEffort as the third config id and gate the model and permission writes * feat(webui): register the acp transport as the first engine capability provider * fix(webui): keep over-tall code blocks inside their scroll container * feat(webui): replace the flat provider form with the desktop-style dialog * docs(webui): document the provider dialog interaction, bilingual * feat(webui): route session deletion through the engine deleteSession facade * feat(webui): open the host services window for capability exposure batches * feat(webui): register the exec transport in the engine capability registry * fix(webui): escape raw svg tags in markdown output instead of mounting them * fix(webui): consume the real stream-json events on the exec transport * feat(webui): unlock the session context menu actions backed by the engine * test(webui): register the PB-1 real-host tmp prefix * chore(release-tools): register the mcode-exec-stream- tmp prefix --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent de094d8 commit a28bceb

31 files changed

Lines changed: 4718 additions & 160 deletions

‎docs/webui.md‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ The fourth registered provider is the **`exec` transport** (M4-2) — the one-sh
243243
| sessionCrud | partial — missing `createSession`, `listSessions`, `getSession`, `updateSession`, `renameSession`, `archiveSession`, `deleteSession`, `forkSession`, `getSessionForkOptions`, `loadSession`, `activateSession`. Only `--session` / `--continue` exist, and they re-enter a session rather than choose one |
244244
| streamingSend | full (`--input -` plus the `stream-json` event stream) |
245245
| interrupt | none — interface-absent: nothing to call. The SIGINT/SIGTERM/SIGHUP in `packages/tui/src/cli/run-exec-command.ts` are signals webui sends to the child **it** spawned, i.e. webui's own kill cascade, not a capability the transport offers |
246-
| toolSkillInvocation | partial — missing `listSkills`, `listRuntimeSkills`, `listPendingPermissions`, `replyPermission`, `setMode`. The transport PRODUCES `tool_call` items and webui does not read them; and `--permission` is fixed at spawn time (the CLI says `ask` requires TUI/ACP), so there is no permission request/reply pair |
246+
| toolSkillInvocation | partial — missing `listSkills`, `listRuntimeSkills`, `listPendingPermissions`, `replyPermission`, `setMode`. The transport PRODUCES `tool_call` items and webui consumes but does not render them; and `--permission` is fixed at spawn time (the CLI says `ask` requires TUI/ACP), so there is no permission request/reply pair |
247247
| turnDiff | none — interface-absent, **servedBy `local-runtime-v2`** |
248248
| turnRewindRedo | none — interface-absent (`mcode exec review` reviews local git changes and carries no turn coordinate, so it is not a rewind surface) |
249249
| plugins | none — interface-absent, **servedBy `local-runtime-v2`** |
@@ -257,7 +257,20 @@ The fourth registered provider is the **`exec` transport** (M4-2) — the one-sh
257257

258258
Three cells are **weaker** than acp, and for structural reasons rather than unfinished engine work: `interrupt` (acp has a cancel notification, exec has nothing to declare one on), `subagents` (acp can parse sub-agent activity off its stream, exec's event union has no such kind) and `authCredentials` (acp has two RPC methods, exec has no channel). The reverse exception is the same two keys for the same reason, which is a finding rather than a copy: `/api/turn-diff*` and `/api/plugins*` project the in-process v2 host and gate on **no transport**, so every transport inherits it.
259259

260-
**A known mismatch this audit surfaced, recorded rather than hidden.** The three event names `collectExecResult` branches on — `delta`, `message`, `exec.result` — are the *supervisor's internal* stream-event names. `--output-format stream-json` writes only what `ExecEventProjector` produces (`packages/tui/src/headless/output.ts` refuses the format with no projector, and `packages/tui/src/headless/runner.ts` always supplies one), so the wire carries the ten `ExecEvent` types and the two name families do not intersect. That is a real gap in the exec data plane. M4-2 does not fix it — the batch registers a declaration and changes no routing — but it is pinned in `EXEC_INTERFACE.consumedEvents` and asserted by a test that fails if the intersection ever becomes non-empty in either direction.
260+
**The mismatch this audit surfaced, and what it cost.** The three event names `collectExecResult` branched on — `delta`, `message`, `exec.result` — are the *supervisor's internal* stream-event names. `--output-format stream-json` writes only what `ExecEventProjector` produces (`packages/tui/src/headless/output.ts` refuses the format with no projector, `packages/tui/src/headless/runner.ts` always supplies one, and the encoder's `result()` leg goes through `projector.complete()` rather than writing the `ExecResult` itself), so the wire carries the ten `ExecEvent` types and the two name families did not intersect.
261+
262+
That was not a missing feature but a **dead data plane**, and it is worth spelling out what a user saw on `MCODE_USE_ACP=0` — and on every non-`Full access` permission mode, which silently re-routes to exec: reasoning and answer text streamed in and never landed, the turn ended with no answer line at all, the context counters never moved, and the follow-up turn started a brand-new engine session because the session id was never read back. D1 rewrote the consumer against the wire:
263+
264+
| Wire event | Consumed as |
265+
| --- | --- |
266+
| `sessionId` on every line | the engine session this run entered, written back to `cs.mcodeSessionId` so the next turn continues it |
267+
| `item.started` / `item.updated` | `item.contentDelta` appended to the answer / reasoning accumulator and streamed as a `●` / `▲` line |
268+
| `item.completed` | `item.content`, adopted only for an item that never streamed a delta |
269+
| `turn.completed` | per-turn `usage` and `durationMs` |
270+
| `turn.failed` | `status` and `error` |
271+
| `exec.completed` | the terminal `ExecResult`, and the call to `finalize()` |
272+
273+
`EXEC_INTERFACE.consumedEvents` now names exactly those six, `EXEC_INTERFACE.baseOnlyEvents` names the four that carry nothing beyond `ExecEventBase`, and a test asserts the two partition the union, that the parser's `switch` arms are the same set, and that every consumed name is one the wire can emit. A `tool_call` item is consumed but not rendered — it carries a `toolCall` payload rather than text — which is why `toolSkillInvocation` stays `partial`.
261274

262275
**`servedBy` is the plan's one reverse exception, and it is load-bearing.** `turnDiff` and `plugins` are honestly `none` on the protocol, and the three `/api/turn-diff` and ten `/api/plugins` endpoints still work on the default acp transport, because they project the in-process local-runtime-v2 host through `getEngineCatalogueHost()` and are gated on no provider declaration. Reading the level alone would eventually 501 two working features the moment a frontend consulted the transport's provider instead of the default one. `summarizeCapabilityHosting(capabilities)` and `resolveCapabilityHostProvider(providerId, key)` expose the routing fact; the hosted keys deliberately stay in `summarizeUnavailableCapabilities`, because the provider really has none and that `{none, partial}` shape is already on the wire. The `exec` provider carries the same two fields for the same structural reason, which is what makes `servedBy` a per-key declaration field rather than an acp special case.
263276

@@ -1648,6 +1661,27 @@ implementation accident:
16481661
The `mermaid` dependency (11.12.1, MIT) is recorded in
16491662
`release/dependency-licenses.json`.
16501663

1664+
### Raw HTML in Markdown is text, never markup (P17)
1665+
1666+
HTML written into a Markdown source — an assistant message, an activity
1667+
group, a `.md` file preview — is **shown as the source text**. It is never
1668+
parsed into DOM elements. That is the whole contract; the rest is how it is
1669+
kept, and how you would notice a regression.
1670+
1671+
| Aspect | Contract | Backed by |
1672+
| --- | --- | --- |
1673+
| Author HTML | Inline and block HTML are escaped, so a pasted `<svg><path …/></svg>`, a `<div onclick=…>`, or a `<script>` block appears verbatim as text. The prose around it is unaffected — one snippet does not blank the message | `webapp/lib/markdown.ts` (the `renderer.html` override) |
1674+
| Why the parser and not the sanitiser | `marked` has no "no raw HTML" option: without the override the snippet reached the tag allowlist, which admits `svg`/`path` for KaTeX geometry, and `components/markdown-html.tsx` then called `createElement("path")` — an unknown host element, and one `The tag <path> is unrecognized in this browser` console error per occurrence (nine in a single UAT round; `doc/uat/2026-10-03-16-master-sub-agent-comm-redline1.md`, anomaly #2) | `webapp/lib/markdown.ts`, `components/markdown-html.tsx` (`htmlToReact`) |
1675+
| Generated HTML is exempt | Markup this app *generates* never passes through that override: KaTeX arrives from the `webuiMath` inline extension and every fenced language from `registerLanguageRenderer`, both of which return their HTML directly. Formula geometry — real `<svg>`/`<path>` — therefore still renders | `webapp/lib/math-renderer.ts`, `webapp/lib/markdown.ts` (`safeLanguageRenderer`) |
1676+
| Line structure | A block snippet keeps its original line breaks; escaping never collapses a multi-line paste onto one line | `webapp/lib/markdown.ts`, `webapp/test/markdown-raw-html.test.ts` |
1677+
| How to tell it works | The regression suite asserts the React tree, not just the string: no `svg`/`g`/`path` element is ever created for author HTML, and a formula still creates `svg` + `path`. A change that lets a tag through turns the suite red, and so does one that over-tightens and kills formula geometry | `webapp/test/markdown-raw-html.test.ts` |
1678+
1679+
Rejected alternatives: **rendering model-authored SVG** (an XSS surface — an
1680+
`<svg>` can carry `<foreignObject>`, animation and event handlers, and the
1681+
product intent is a transcript, not a renderer); **adding DOMPurify** (a
1682+
multi-megabyte dependency to defend markup the app never needs, when the
1683+
parser can refuse it outright).
1684+
16511685
### Code block wrapping and scrollbars (ticket 52)
16521686

16531687
Every markdown codeblock — chat messages, activity groups and markdown

‎docs/webui.zh-CN.md‎

Lines changed: 60 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ host 对象(子进程没有对象可反射),而是线路表 `MCODE_ACP_CAP
255255
| sessionCrud | partial——缺 `createSession`、`listSessions`、`getSession`、`updateSession`、`renameSession`、`archiveSession`、`deleteSession`、`forkSession`、`getSessionForkOptions`、`loadSession`、`activateSession`。只有 `--session` / `--continue`,而它们是「重新进入」一个会话而非「挑选」一个 |
256256
| streamingSend | full(`--input -` 加上 `stream-json` 事件流) |
257257
| interrupt | none——接口无:没有可调的东西。`packages/tui/src/cli/run-exec-command.ts` 里的 SIGINT/SIGTERM/SIGHUP 是 webui 发给**自己 spawn 的**子进程的信号,即 webui 自己的 kill 级联,不是传输提供的能力 |
258-
| toolSkillInvocation | partial——缺 `listSkills`、`listRuntimeSkills`、`listPendingPermissions`、`replyPermission`、`setMode`。传输**产出** `tool_call` 项而 webui 不读它们;且 `--permission` 在 spawn 时就定死(CLI 明说 `ask` 需要 TUI/ACP),所以没有权限请求/应答对 |
258+
| toolSkillInvocation | partial——缺 `listSkills`、`listRuntimeSkills`、`listPendingPermissions`、`replyPermission`、`setMode`。传输**产出** `tool_call` 项而 webui 消费了它们却不渲染;且 `--permission` 在 spawn 时就定死(CLI 明说 `ask` 需要 TUI/ACP),所以没有权限请求/应答对 |
259259
| turnDiff | none——接口无,**servedBy `local-runtime-v2`** |
260260
| turnRewindRedo | none——接口无(`mcode exec review` 审阅本地 git 变更、不带回合坐标,所以不是 rewind 面) |
261261
| plugins | none——接口无,**servedBy `local-runtime-v2`** |
@@ -274,14 +274,34 @@ RPC 方法,exec 没有通道)。反向例外是同样两个键、同样一
274274
复制:`/api/turn-diff*` 与 `/api/plugins*` 投影的是进程内 v2 host,且**完全不按
275275
传输门控**,所以每条传输都继承它。
276276

277-
**这条审计查出的一处错配,选择记录而非隐藏。** `collectExecResult` 匹配的三个
277+
**这条审计查出的一处错配,以及它的代价。** `collectExecResult` 匹配的三个
278278
事件名——`delta`、`message`、`exec.result`——是 **supervisor 内部**的流事件名。
279279
而 `--output-format stream-json` 只写 `ExecEventProjector` 的产出(`packages/tui/src/headless/output.ts`
280-
在没有 projector 时直接拒绝该格式,`packages/tui/src/headless/runner.ts` 总会提供一个),所以线路上跑的是
281-
那十个 `ExecEvent` 类型,两个名字族并不相交。这是 exec 数据面上的真实缺口。
282-
M4-2 不修它——本批只注册声明、不改路由——但它被钉在
283-
`EXEC_INTERFACE.consumedEvents`,并由一条「相交集一旦在任一方向变为非空就转红」
284-
的测试守住。
280+
在没有 projector 时直接拒绝该格式,`packages/tui/src/headless/runner.ts` 总会提供一个,
281+
且编码器的 `result()` 那条腿走 `projector.complete()` 而非直接写出 `ExecResult` 本身),
282+
所以线路上跑的是
283+
那十个 `ExecEvent` 类型,两个名字族并不相交。
284+
285+
这不只是「少一个功能」,而是**一整条死掉的数据面**。值得把用户在
286+
`MCODE_USE_ACP=0` 下会看到什么写清楚——以及在每一种非 `Full access` 的权限模式下,
287+
因为那会静默改道到 exec:思考与回答的文本流进来却从不落地,回合结束时连一行回答
288+
都没有,上下文计数从不走动,而下一轮会另起一个全新的引擎会话,因为会话 id 从未被读回。
289+
D1 把消费面改回线路本身:
290+
291+
| 线路事件 | 消费为 |
292+
| --- | --- |
293+
| 每一行都带的 `sessionId` | 本次运行进入的引擎会话,写回 `cs.mcodeSessionId`,使下一轮能续接 |
294+
| `item.started` / `item.updated` | `item.contentDelta` 追加进回答/思考累加器,并以 `●` / `▲` 行流式呈现 |
295+
| `item.completed` | `item.content`,仅对从未流出增量的 item 采纳 |
296+
| `turn.completed` | 每轮 `usage` 与 `durationMs` |
297+
| `turn.failed` | `status` 与 `error` |
298+
| `exec.completed` | 终态 `ExecResult`,以及 `finalize()` 的调用 |
299+
300+
`EXEC_INTERFACE.consumedEvents` 现在正好点名这六个,`EXEC_INTERFACE.baseOnlyEvents`
301+
点名除 `ExecEventBase` 外无内容的另外四个,并由一条测试断言二者恰好划分整个联合、
302+
解析器的 `switch` 分支与之是同一集合、且每个被消费的名字都是线路真能发出的名字。
303+
`tool_call` item 会被消费但不会被渲染——它携带的是 `toolCall` 负载而非文本——
304+
这正是 `toolSkillInvocation` 停在 `partial` 的原因。
285305

286306
**`servedBy` 是计划里唯一的反向例外,且有承重意义。** `turnDiff` 与 `plugins`
287307
在协议上如实 `none`,而那三个 `/api/turn-diff` 与十个 `/api/plugins` 端点在缺省
@@ -1220,6 +1240,39 @@ flowchart LR
12201240

12211241
依赖:`mermaid` 11.12.1(MIT),已登记于 `release/dependency-licenses.json`。
12221242

1243+
### Markdown 里的裸 HTML:按代码文本显示(P17)
1244+
1245+
Markdown 源里写的 HTML——助手回复、活动组、`.md` 文件预览——一律**当作
1246+
源码文本显示**,绝不会被解析成页面元素。这就是全部契约;下面是它靠什么
1247+
维持、以及怎么发现它坏了。
1248+
1249+
**你会看到什么**
1250+
1251+
- 模型在推理或正文里贴 `<svg><path …/></svg>`,屏幕上是这段源码本身,
1252+
不是一张图,浏览器控制台也不会因为 `<path>` 报警。
1253+
- `<div onclick=…>`、`<script>` 之类的片段同理:原样显示成文字。周围的
1254+
正文不受影响,一段 HTML 不会让整条消息消失。
1255+
1256+
**为什么不是"把 SVG 画出来"**
1257+
1258+
`<svg>` 能携带 `<foreignObject>`、动画与事件属性,渲染模型输出的 SVG
1259+
等于开一个 XSS 面;而这个产品的定位是会话记录,不是渲染器。所以选择
1260+
"安全显示为文本",也没有为此引入 DOMPurify 这类重型依赖——问题出在解析
1261+
层允许裸 HTML 透传,在解析层拒绝即可(`webapp/lib/markdown.ts`)。
1262+
1263+
**为什么不影响公式**
1264+
1265+
本应用**自己生成**的 HTML 不走这条规则:KaTeX 由行内扩展产出、各代码围栏
1266+
由语言渲染器注册表产出,两者都直接返回自己的 HTML。因此公式的几何图形
1267+
(真正的 `<svg>`/`<path>`)照常渲染(`webapp/lib/math-renderer.ts`)。
1268+
1269+
**怎么发现它坏了**
1270+
1271+
回归用例断言的是 React 树而不只是字符串:作者写的 HTML 永远不会生成
1272+
`svg`/`g`/`path` 元素,公式仍然生成 `svg` + `path`。往松了改(放行标签)
1273+
或往紧了改(连公式几何一起转义)都会让用例变红
1274+
(`webapp/test/markdown-raw-html.test.ts`)。
1275+
12231276
### 代码块的换行与滚动条(工单 52)
12241277

12251278
所有 markdown 代码块——聊天消息、活动组、markdown 文件预览——都经同一

0 commit comments

Comments
 (0)