diff --git a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.i18n.yaml new file mode 100644 index 0000000000..44869d6f05 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md +2026-07-28-tool-call-file-open-in-os.md: a2c9b52507d32c2d851f811f0ecdd878a60b1e1c +2026-07-28-tool-call-file-open-in-os.zh.md: efb4c39503d9de71a9d773bdae7fac4fb2b08ee3 diff --git a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md new file mode 100644 index 0000000000..a2c9b52507 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.md @@ -0,0 +1,30 @@ +# Agent Note: Tool-call file open in OS + +Status: implemented + +English | [中文](2026-07-28-tool-call-file-open-in-os.zh.md) + +## Problem + +Chat tool rows treated the whole summary line as a click target that opened the right-hand details panel, with a hover background on the row. For filesystem tools the useful action is opening the mentioned file in the operating system's default application, not inspecting the raw tool payload in a sidebar. + +## Decision + +File-tool path summaries (`read` / `write` / `edit` args carrying `path` or `file_path`) render as hover-underline links with a pointer cursor. Clicking the path calls `host.openPath` through `WorkspacesService.openPath`, resolving relative paths against the session cwd. File-link rows disable args expand (leading icon is inert); whole-row click, row hover fill, and the click-to-open-details gesture are removed from tool rows (including bash and todo registrations). The details panel and its inject surface remain for programmatic selection; rows no longer drive them. + +`host.openPath` is a privileged unary RPC accepted only from loopback, same-origin browser requests (same carrier guard as `host.pickDirectory`). Platform adapters open without a shell: `open` on macOS, PowerShell `Invoke-Item` on Windows, `xdg-open` on Linux. The opener is injectable for tests. URL-only read args (`web_fetch`) are not file links. + +## Alternatives considered + +- Keep row-click details and add a separate file affordance — rejected; the product ask replaces the row gesture with the file link. +- Open files inside an in-app preview — rejected; the ask is the OS default application. +- Reuse `host.pickDirectory`'s timeout exemption — unnecessary; path open hand-off completes quickly under the normal unary deadline. + +## Consequences + +Clicking a file path in a tool row opens that path on the host. Non-file tool rows are inert summaries (expand toggles remain where the row already supported them). Remote or non-loopback clients cannot invoke `host.openPath`. + +## Risks + +- Linux hosts without `xdg-open` fail the RPC; the chat row stays silent while the host returns an internal error. +- Relative paths without a session cwd are forwarded verbatim and may fail on the host. diff --git a/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.zh.md b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.zh.md new file mode 100644 index 0000000000..efb4c39503 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-28-tool-call-file-open-in-os.zh.md @@ -0,0 +1,30 @@ +# Agent Note: 在工具调用中用系统应用打开文件 + +Status: implemented + +[English](2026-07-28-tool-call-file-open-in-os.md) | 中文 + +## Problem + +聊天工具行把整行摘要当作点击目标,点击后打开右侧 details 面板,并带有整行悬停背景。对文件系统工具而言,有用的动作是用操作系统默认应用打开所涉文件,而不是在侧栏里查看原始工具载荷。 + +## Decision + +文件工具的路径摘要(`read`/`write`/`edit` 参数中的 `path` 或 `file_path`)渲染为悬停下划线链接并使用 pointer 光标。点击路径会经 `WorkspacesService.openPath` 调用 `host.openPath`,相对路径相对会话 cwd 解析。带文件链接的行关闭参数展开(左侧图标不可点);工具行(含 bash 与 todo 注册)去掉整行点击、整行悬停底色,以及点击打开 details 的手势。details 面板及其 inject 面仍保留供程序化选择;工具行不再驱动它们。 + +`host.openPath` 是特权一元 RPC,仅接受来自回环、同源浏览器请求(与 `host.pickDirectory` 相同的载体守卫)。平台适配器不经 shell 打开:macOS 为 `open`,Windows 为 PowerShell `Invoke-Item`,Linux 为 `xdg-open`。打开器可在测试中注入。仅含 URL 的 read 参数(`web_fetch`)不是文件链接。 + +## Alternatives considered + +- 保留整行点击打开 details,另加文件入口 — 否决;产品要求用文件链接替换整行手势。 +- 在应用内预览文件 — 否决;要求是操作系统默认应用。 +- 复用 `host.pickDirectory` 的超时豁免 — 不必要;打开路径的交接在常规一元截止时间内即可完成。 + +## Consequences + +点击工具行中的文件路径会在宿主上打开该路径。非文件工具行是惰性摘要(行内已有的展开开关仍保留)。远程或非回环客户端无法调用 `host.openPath`。 + +## Risks + +- 没有 `xdg-open` 的 Linux 宿主会使 RPC 失败;聊天行保持静默,宿主返回 internal 错误。 +- 没有会话 cwd 时相对路径会原样转发,可能在宿主侧失败。 diff --git a/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.i18n.yaml b/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.i18n.yaml new file mode 100644 index 0000000000..2476db5785 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md +2026-07-27-session-projection-and-command-log.md: 51cc60208ecafd55738c12f1887056c7b0427117 +2026-07-27-session-projection-and-command-log.zh.md: 71f6f6ea944c7c1bdd7e560ec8f0dc2528522fc1 diff --git a/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md b/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md new file mode 100644 index 0000000000..51cc60208e --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.md @@ -0,0 +1,183 @@ +# Agent Note: Session projections and command lifecycle logging + +Status: proposed + +English | [中文](2026-07-27-session-projection-and-command-log.zh.md) + +## Problem + +Three in-flight web features — todo (#497), goal (#527), and plan mode (#587) — each derive per-session state from the session log and surface it in the browser client, and each invented its own copy of the same machinery: + +- **The client core class absorbs every domain.** All three add private fields, fetch choreography, and event switches to the client runtime's `Session` class and project their values through `ConversationSnapshot`. Plan alone adds seven private fields and a three-layer fence (request version, event version, latest-live cache); goal adds a write-revision fence plus a coalesced refetch loop; todo adds a projection field and an event case. A fourth domain means editing the core class a fourth time. +- **Three baseline channels.** Todo rides a `todos` field on the history tail page — computed by `backscanTodos` **inside api-proxy**, business folding living in the carrier; plan adds a dedicated `session.planMode` unary; goal adds `goals.get`. Same problem, three wire shapes. +- **Command results are unrecoverable.** `/goal`, `/plan`, and every other slash command return their outcome only in the `command.execute` RPC response, surfaced as a transient composer notice on the issuing tab. Nothing reaches the session log: a refresh, another tab, resume, or fork loses the record that the command ever ran. The domain *state* changes are durable (goal commits `goal/change` metadata, plan commits `plan/mode`), but the command invocation and its verdict are not. + +The underlying gap is architectural: the client has no seam for a plugin to observe session events in a session's scope and keep its own derived state, and the host has no uniform way to hand a client the current value of log-derived state whose history may have been paged out of the client's window. + +## Proposal + +Four infrastructure pieces, then the domains become pure contributors. + +### Whole-value event rule + +A state-carrying log event MUST carry the complete post-change state, never a bare delta. All three domains already comply: `todo/write` is a whole-list snapshot, `plan/mode` a whole boolean, `goal/change` metadata a full `GoalSnapshot` (or a whole-value clear tombstone). The rule keeps every domain's transition trivially cheap (the framework drives it per event), keeps values self-describing on the wire, and lets any consumer treat the latest pushed value as final — out-of-order immunity by seq comparison, self-healing because a missed update is corrected by the next one. + +### Host projection registry (`dsh-session-projection`, new package) + +A light interface package: the merge-extensible type map, the registry service, zod at the boundary. Capability-seam three-way split: domain host plugins contribute, carriers consume, neither knows the other. + +What a domain registers is a **state-driven computation unit** — three pure functions plus declarations — never an opaque getter. The framework owns driving it (subscription, watermark, caching, and later checkpointing); the domain owns only the mathematics. Projections serve every business domain (session title, plan, goal, permission, todos); commands are merely one trigger path and hold no special position in this contract. + +```ts ignore-check +export interface SessionProjectionMap {} // the single type table for the whole chain + +export interface ProjectionDefinition { + key: K + schema: ZodType // validates the payload before it leaves the host + /** State for the empty log. */ + init(): S + /** Pure transition: previous state + one event → next state. The framework drives it; domains hold no subscriptions. */ + apply(state: S, event: SessionEvent): S + /** State → wire payload (the read-side projection). */ + view(state: S): SessionProjectionMap[K] + /** State must be plain JSON (persisted-cache precondition); bump to invalidate persisted rows. */ + stateVersion: number +} + +declare module 'cordis' { + interface Context { sessionProjections: SessionProjectionRegistry } +} +``` + +- Values are wire JSON payloads; the same map typed end to end (host unit, wire block, React hook) via `import type` — no second DTO table, no separate client-side "views" map. How a value is *rendered* is the slot system's business, never the projection layer's. +- **The host is the only place a projection is computed.** The framework drives every registered unit forward eagerly: each committed session event passes through `apply`; a unit uninterested in an event returns the same state reference, and an unchanged reference (`Object.is`) produces no downstream work. Clients never fold domain events — they receive finished values (baseline block + push frame below). This removes the double-implementation trap (plan's two-event fold written once, on the host) and any client-side domain code. +- **State is always computed, never logged.** The log holds events only; the unit's state lives in the framework's per-session watermark cache (`{state, observedSeq}` per unit) and, in a later phase, in a **persisted projection cache** on the domain-KV storage seam: rows of `(sessionId, key, stateVersion, observedSeq, stateJson)`. A row is never wrong, only possibly stale — `observedSeq` says exactly how stale. The one read recipe, cold and live alike: take the cached state (or `init()`), forward-apply only the events past its watermark, `view` the result. Cold listings (every session's title across all workspaces) become an index read plus, at worst, a short tail replay; the session-persistence seam grows a read-from-seq primitive for that tail in the same later phase. Write policy: throttled (count/interval, configurable) plus two mandatory points — `turn/end` and detach (the live-to-cold moment). A crash between writes costs a longer tail replay, never a wrong value. +- A domain's input event set is its own choice: todos folds `todo/write` alone; plan folds `plan/mode` plus its own `/plan` `command/run` records (see the plan section); goal folds `goal/change` metadata; session title folds its title events (retiring the bespoke `session/title` frame and the client's title-snapshot map — the fourth hand-rolled projection this seam absorbs). +- Registration is an effect (disposer with the fiber): an unloaded plugin's key disappears from subsequent responses and the client reads it as capability absence — HMR semantics for free. Duplicate keys throw. Domain plugins register under `ctx.inject(['sessionProjections'], …)` so headless assemblies without the registry stay unaffected. +- The package owns `./invariant` (every served key has a live registration). + +### Wire: projections block on the history tail page + +```ts ignore-check +// session.history response, tail page only (beforeSeq absent): +{ events, hasMore, + projections?: { asOfSeq: number, values: Partial } } +``` + +The api-proxy history handler, after slicing the tail page, synchronously walks the registry — no `await` anywhere, so every key's value and `asOfSeq` form one consistent cut. `asOfSeq` is the **last event's seq** (`session.seq - 1`; `-1` for an empty log, the same vocabulary as `session/subscribed.lastSeq`), so a push frame carrying the first post-baseline change always compares strictly greater. Api-proxy holds zero domain knowledge (the same carrier/contributor relationship as `viewFor` against `ctx.tools`). + +No new RPC method. The timing coincidence is exact: every moment the client needs a fresh baseline (open, reconnect resync, gap repair) already pulls the tail page, and the only path that never needs one (loadOlder) is the only path that passes `beforeSeq`. The client therefore has **no** independent "refetch the baseline" decision at all. Window content is never a signal: "no domain event in the window" is unanswerable there by construction, and only the baseline answers it. + +Retired by this block: `session.planMode` and `setPlanMode` (both sides — plan selection goes through the standard command channel, see the plan section), `goals.get` (read side; the six mutation RPCs stay, their responses no longer feed state — the mux event arrives anyway), the `todos` rider field, and `backscanTodos` in api-proxy (moves into the todo domain's unit, in `tool-todo`). + +### Push frame and the client value store (domains write zero client code) + +Because the host is the only computation site, finished values reach clients over one new mux frame: + +```ts ignore-check +// MuxFrame union + schema branch: +{ type: 'session/projection', sessionId, key: string, value: unknown, seq: number } +``` + +The framework emits it whenever a unit's state reference changes (`Object.is` gate above); `seq` is the unit's watermark at emission. This is live push state, never logged — the same posture as the tool-view `view` slot: replay recomputes on the host. + +The client object layer keeps one **generic value store** per session: `key → { value, seq }`, seeded by the tail page's projections block and updated by the frame, under the single rule **higher seq wins**. Replayed baselines cannot roll a newer frame back; a lost frame costs staleness until the next frame or baseline, never wrongness. No `fromEvent`, no per-domain cell registration, no client-side domain folding — a domain ships projection support with **zero client code** (the `SessionProjectionMap` merge serves both sides through the `/types` outlet). The bespoke `session/title` frame and the manager's title-snapshot map retire into this generic pair. All the per-domain fences (#587's three layers, #527's write revision) dissolve into the one seq rule. + +### Plan through the standard command channel (worked example) + +Plan mode demonstrates the full pattern — trigger path, run plane, and replay plane, cleanly separated: + +- **Trigger path**: the web plan toggle sends `/plan` / `/plan off` through `command.execute` like any other command; the dedicated `setPlanMode`/`planMode` RPCs are retired. The user's *request* is durably recorded as that command's `command/run { name: 'plan', args: 'off' | '' }` — structured fields, no line parsing. +- **Run plane** (unchanged): the plan-mode service keeps its in-memory pending intent and flushes `plan/mode` at the next turn boundary. On cold start the service rebuilds its intent queue from the replay plane ("empty run state means the replay state"). +- **Replay plane**: plan's projection unit folds **two** event types — its own `command/run` records set `wanted`; `plan/mode` sets `active` and clears `wanted`; `view` derives `{ active, pending: wanted !== null && wanted !== active }`. Pending is thereby a pure replay quantity: host restarts recover it, other tabs fold the same events (cross-tab pending for free), and a cold read answering `{ active: false, pending: true }` is accurate ("an unfulfilled selection awaits resume"). + +A domain's input event set is its own choice — that is the general rule this example instantiates. Whether "the user asked for X" appears in a projection (plan folds its command records) or only in the flow (the command node renders anyway) is per-domain semantics, never a framework concern. + +### React: `useProjection`, the fifth framework hook seat + +The existing four seats cannot host this state (store discipline bans business objects; inject bans hooks; `ConversationSnapshot` is being evacuated). `useProjection` becomes a framework seat, minted in web-react (the one hook constructor), delivered through the same standard-kit channel as `useSession` (`provideInfo` → SessionProvider → props): + +```ts ignore-check +type UseProjection = { + (key: K): SessionProjectionMap[K] | undefined + ( + key: K, selector: (v: SessionProjectionMap[K] | undefined) => S, + eq?: (a: S, b: S) => boolean): S +} +``` + +`undefined` uniformly means capability absent (host plugin unmounted, or no baseline/frame has carried the key). The value store exposes bare per-key `{subscribe, getSnapshot}` faces; `bindSnapshotSelector` with per-key caching does the rest — reference stability holds because a key's value reference changes only when a frame or baseline lands. Write paths are unchanged: mutation callbacks stay in the inject share (callbacks out of inject, live state out of `useProjection`). + +The one existing violation of "no hooks through inject" — `DetailsInjected.useSelection` — is folded in with this change: selection is viewing state living in the chat store, so the details registration declares the shared store handle and the component reads `props.useStore(s => s.selection)`; `useSelection` leaves the inject contract. + +### Command lifecycle in the log + +Two log-only (non-surface, model-invisible) events, mirroring the `tool/call`/`tool/result` pairing: + +```ts ignore-check +'command/run': { commandId: string; name: string; args: string; source: CommandSource } +'command/done': { commandId: string; kind: 'success' | 'error'; text?: string } +``` + +The host command executor (`packages/ui/commands`) appends `command/run` before invoking the handler and `command/done` at settlement — direct standalone appends on the receiving agent's session, in the same shape as every other plugin-owned log-only event after the [synthetic-turn removal](../../implemented/simplification/2026-07-28-remove-synthetic-log-only-turns.md): no turn wraps them (turns describe model-loop executions only), persistence drains them at ordinary checkpoints, and the commands package's own invariant companion enforces the run/done pairing. The payload is structured — `name` and `args` are the parser's own split (`parseCommand`'s name and rawInput), so a consumer (a projection unit folding its own command records, a rich command card) never re-parses a line. `text` is the handler's verbatim outcome — factual data of the same nature as `tool/result.content`, not presentation (how it is laid out remains client-computed at render time, satisfying the "presentation never enters the log" red line). Domains that want the model to know the outcome keep doing what they do today (plan's narration, goal's inject) — that is a domain decision, unchanged. + +Because committed events broadcast on the mux stream, refresh persistence, multi-tab sync, and fork/resume recovery all come for free. The `command.execute` RPC degrades to admission — `{ matched, commandId? }`: whether the line resolved, and the minted pairing id when it did, so the issuing client can correlate its request with the flow node the lifecycle events produce. The one-shot notice channel (`runDetached` → `noticeFor`) is retired. + +The client flow builder gains one generic command node (run/done paired by `commandId`; cross-window cuts soft-fall like tool pairs). Rendering goes through a new keyed slot `'conversation.chat.commandview'`, key = command name, **fallback = a generic command card** (zero registration required — the former notice text now renders durably in the flow). A domain upgrades by registering one row component, drawing on `command/run`'s structured fields and its own projection value (`useProjection`) — the same shape as tool rows after the toolview dissolution. + +## Delivery plan + +Infrastructure first; the three in-flight PRs are left untouched and re-target after the base lands (their migration mapping is the guide): + +1. **Host base**: `dsh-session-projection` (unit contract, eager drive, watermark cache) + api-proxy projections block + the `session/projection` push frame. Mergeable with zero domains registered (block and frames simply absent). +2. **Client base**: the generic value store + `useProjection` seat; retire the per-domain cell machinery and, with title's unit registered, the `session/title` frame and title-snapshot map. Depends on 1 for the frame shape (fixtures feed synthetic frames meanwhile). +3. **Command channel**: the two events, executor logging, generic node + keyed slot, notice retirement, `{matched, commandId?}` admission. Parallel with 1. +4. **Domain re-targets** (after 1+2): todo (unit in `tool-todo`, drop the rider field), then plan (two-event unit, RPCs retired, toggle → `/plan`), then goal (`goal/change` unit, drop `goals.get`, move the six `Session` methods into the domain plugin's inject). +5. **Persisted projection cache** (later phase, after the domain-KV storage seam): the `(sessionId, key, stateVersion, observedSeq, state)` rows, throttled writes with turn/end + detach mandatory points, and the persistence read-from-seq primitive for cold tail replay. + +## Alternatives considered + +**A dedicated `session.projections` RPC** — rejected: baseline-refresh moments coincide exactly with tail-page pulls, so a separate unary buys a second round-trip, a second seq to reconcile, and a client-side "when to refetch" decision that the rider design deletes outright. + +**An opaque `get(agent)` provider contract** — rejected after being the first draft: with the computation model hidden inside the domain, the framework can never checkpoint the state, serve cold sessions (no agent, no loaded log — `get` has nothing to run against), or resume from a mid-log position. Registering the `(init, apply, view)` unit hands the framework the drive and keeps the domain to pure mathematics; a domain with host-side behavioral needs still keeps its own service subscriptions independently of the projection unit. + +**A live-only overlay hook (`live?(agent, base)`) for plan's pending intent** — rejected: it existed solely because the user's plan *selection* was not in the log. Routing the selection through the standard command channel puts `command/run` on the account, pending becomes a pure replay quantity, and the projection contract stays exactly three pure functions. + +**Naming the seam `registerFold`** — superseded by the unit contract: the registered object now genuinely is a fold, but `fold*` in this repo names pure `(events) => state` helper functions while this seam registers a keyed, schema'd, versioned unit. Projection remains the event-sourcing term for the read-model role, and both #587's note title and #497's comments already use it. + +**Client-side folding (per-domain projection cells with a `fromEvent`)** — rejected after being the second draft: once plan's unit folds two event types, a client cell must duplicate the host's transition logic in the browser — the same fold written twice, evolving separately. Pushing finished values (the title-frame precedent, generalized) keeps one computation site and reduces the client to a generic seq-guarded value store; domains write zero client code. + +**Bounded reverse scan over the log tail (absorber declarations)** — rejected for now: nothing supports it today, it only serves domains whose every event carries the full folded state, and the persisted projection cache covers the same cold-read need uniformly (cache row + forward tail replay — the same recipe as the client's baseline + catch-up, and as paged loading). Revisit only if a real cold-read path emerges that checkpointing cannot serve. + +**An `invalidate`-style cell (mark dirty, refetch on domain events)** — rejected: it exists only to serve delta events. The whole-value rule makes every domain last-wins; goal's refetch loop, its coalescing, and its stale-read fence all disappear. + +**Hanging the registry off `ctx.apiProxy`** — rejected: session projections are not web-specific (TUI, ACP, headless are future consumers), and domain packages must not depend on the apiproxy package. The independent seam also deletes #587's type-only import edge from api-proxy into the plan package. + +**A separate client-side `SessionProjectionViews` type table** — rejected: one `SessionProjectionMap` typed end to end is the wire-passthrough discipline (no second DTO vocabulary); values are JSON payloads and rendering belongs to slots. + +**Event-broadcast collection instead of a registry walk** — rejected: async listeners cannot yield the single synchronous cut that makes `asOfSeq` one consistent snapshot across all keys; registries are this repo's shape for contributions (`ctx.tools`, prompt sections, slots). + +**A dedicated `plan/select` selection event (structured domain event instead of folding command records)** — rejected in favor of the command channel: `command/run`'s structured `{name, args}` already records the selection, the `/plan` grammar and its fold live in the same plugin (domain-internal coupling, not cross-domain), and one less event type. The handler must call `set()` before any failable path so the logged request and the run plane cannot diverge — a domain-internal ordering constraint, documented at the handler. + +**Keeping `setPlanMode` as a dedicated RPC** — rejected: plan selection is a user command like any other; the command channel gives it durable recording, flow rendering, multi-tab visibility, and admission semantics without a bespoke wire method. Web UI affordances (a toggle) compose the command line internally. + +**Making mutation RPC responses feed cell state** — rejected: the committed mux event arrives immediately and carries the same whole value with a seq; responses feeding state is what required #527's write-revision fence. + +## Acceptance criteria + +- A domain plugin ships per-session log-derived state to React by writing only: the whole-value event declaration, one host unit `register`, its `SessionProjectionMap` merge, and inject callbacks — zero client-side code, no edits to the client `Session` class, `ConversationSnapshot`, api-proxy, or the wire schema files. +- The history tail page carries `projections` with `asOfSeq` equal to the window tail seq; loadOlder pages never carry it; a deployment without the registry serves histories without the block and clients treat every key as absent. +- A stale baseline cannot overwrite a newer `session/projection` frame, and a replayed frame cannot regress the value store (higher-seq-wins tests on both paths). +- A slash command executed on one tab renders a durable node in the flow on refresh, on a second tab, and after resume; unregistered commands render the generic card; the composer notice path for command outcomes is gone. +- `useProjection` reaches components through the standard props kit; no hook crosses an inject contract (including `useSelection`). +- Session titles ride the generic pair (baseline block + projection frame); the bespoke `session/title` frame and the client title-snapshot map are gone. + +## Risks + +- **Whole-value rule is load-bearing**: a future domain logging bare deltas cannot serve consumers from its latest event and complicates its own unit. Mitigation: the rule is stated here and in the projection package README; the unit contract makes the full state explicit at every transition. +- **Synchronous unit discipline**: `init`/`apply`/`view` that await would tear the consistency cut. The registry documents and the invariant companion asserts synchronicity as far as practical; review owns the rest. +- **Live registry churn is not pushed**: loading or unloading a domain plugin mid-session changes the key set, but no session event fires and no frame is pushed; open clients hold the stale key until the next tail pull (reconnect, gap repair, open). Accepted as a dev-only (HMR) staleness window — a registry-change push can be added to the change feed later without contract impact. +- **Eager drive costs on busy sessions**: every committed event passes every registered unit's `apply`. Units are cheap per-event by construction (whole-value rule), non-matching events return the same reference, and the count of registered domains is small; if a hot path ever shows, per-unit event-type prefilters can be added without contract change. +- **Projection payload growth**: every tail page carries every registered key. Payloads are whole values of UI-scale state (a todo list, a goal snapshot); if a future domain's value is large, per-key opt-out or lazy keys can be added to the request without changing the model. +- **Command log volume**: two log-only events per slash command; bounded by human command frequency, negligible against chunk volume. +- **Re-target churn**: three open PRs rebase onto a moved foundation. Accepted cost of infrastructure-first; the migration mapping section in the design ledger names each PR's keep/drop list. diff --git a/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.zh.md b/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.zh.md new file mode 100644 index 0000000000..71f6f6ea94 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-27-session-projection-and-command-log.zh.md @@ -0,0 +1,183 @@ +# Agent Note: Session projections and command lifecycle logging + +Status: proposed + +[English](2026-07-27-session-projection-and-command-log.md) | 中文 + +## Problem + +三个在途的 web 功能——todo(#497)、goal(#527)、plan mode(#587)——都要从会话日志推导按会话的状态并呈现到浏览器客户端,而三者各自发明了一套同样的机制: + +- **客户端核心类吸收每一个领域。** 三者都往客户端运行时的 `Session` 类里添加私有字段、拉取编排和事件 switch 分支,并经 `ConversationSnapshot` 投出各自的值。仅 plan 一家就加了七个私有字段和三层栅栏(请求版本、事件版本、最新活值缓存);goal 加了写 revision 栅栏外加一个合并式重取循环;todo 加了一个投影(projection)字段和一条事件 case 分支。再来第四个领域,就要第四次改动核心类。 +- **三条基线通道。** todo 搭在历史尾页的 `todos` 字段上——由 **api-proxy 内部**的 `backscanTodos` 计算,业务折叠(fold)逻辑寄居在载体里;plan 加了一个专用的 `session.planMode` 一元 RPC;goal 加了 `goals.get`。同一个问题,三种协议格式(wire format)。 +- **命令结果不可恢复。** `/goal`、`/plan` 以及其余所有斜杠命令都只在 `command.execute` RPC 响应里返回结果,以一条转瞬即逝的 composer 通知呈现在发起命令的标签页上。会话日志里什么也留不下:刷新、另开标签页、恢复或 fork 都会丢掉「该命令曾经运行过」的记录。领域*状态*变更是持久的(goal 提交 `goal/change` 元数据,plan 提交 `plan/mode`),但命令调用本身及其结论不是。 + +底层缺口是架构性的:客户端没有一个 seam 让插件在会话 scope 内观察会话事件并维护自己的派生状态;host 侧也没有统一的方式把日志派生状态的当前值交给客户端——而该状态的历史可能已被分页挤出客户端窗口之外。 + +## Proposal + +先立四件基础设施,之后各领域都退化为纯贡献方。 + +### 全量值事件规则 + +携带状态的日志事件必须携带变更后的完整状态,绝不携带裸增量。三个领域现状已然合规:`todo/write` 是整表快照,`plan/mode` 是一个完整布尔值,`goal/change` 元数据是完整的 `GoalSnapshot`(或一个全量值清除墓碑)。该规则让每个领域的状态转移始终足够廉价(框架逐事件驱动它),让值在协议层自描述,并让任何消费方都可以把最近推送的值当作最终值——靠 seq 比较获得乱序免疫,且自愈:漏掉的更新会被下一次更新纠正。 + +### host 侧投影注册表(`dsh-session-projection`,新包) + +一个轻量的接口包(package):merge-extensible 类型表、注册表服务、边界上的 zod 校验。能力 seam 三方拆分:领域 host 插件负责贡献,载体负责消费,两侧互不相识。 + +领域注册的是一个**状态驱动计算单元(state-driven computation unit)**——三个纯函数外加若干声明——绝不是一个不透明的 getter。驱动它是框架的职责(订阅、水位线(watermark)、缓存,以及后续的检查点机制),领域只负责数学本身。投影服务于所有业务领域(会话标题、plan、goal、权限、todos);命令只是其中一条触发路径,在本契约中没有任何特殊地位。 + +```ts ignore-check +export interface SessionProjectionMap {} // the single type table for the whole chain + +export interface ProjectionDefinition { + key: K + schema: ZodType // validates the payload before it leaves the host + /** State for the empty log. */ + init(): S + /** Pure transition: previous state + one event → next state. The framework drives it; domains hold no subscriptions. */ + apply(state: S, event: SessionEvent): S + /** State → wire payload (the read-side projection). */ + view(state: S): SessionProjectionMap[K] + /** State must be plain JSON (persisted-cache precondition); bump to invalidate persisted rows. */ + stateVersion: number +} + +declare module 'cordis' { + interface Context { sessionProjections: SessionProjectionRegistry } +} +``` + +- 值就是协议层的 JSON 载荷;同一张类型表经 `import type` 端到端贯通(host 侧单元、协议块、React 钩子)——没有第二张 DTO 表,也没有独立的客户端「views」表。值如何*渲染*是 slot 体系的事,永远不归投影层管。 +- **host 是投影唯一的计算地点。** 框架正向驱动(eager drive)每个已注册的单元:每个已提交的会话事件都经过 `apply`;对某事件不感兴趣的单元返回同一个状态引用,而引用未变(`Object.is`)就不产生任何下游工作。客户端从不折叠领域事件——它们收到的是成品值(基线块 + 下文的推送帧)。这消除了双重实现陷阱(plan 的双事件折叠只在 host 写一遍),也消除了一切客户端侧领域代码。 +- **状态永远靠计算得出,绝不入日志。** 日志只存事件;单元的状态住在框架的按会话水位线缓存里(每单元一份 `{state, observedSeq}`),并在后续阶段进入 domain-KV 存储 seam 上的**持久投影缓存(persisted projection cache)**:形如 `(sessionId, key, stateVersion, observedSeq, stateJson)` 的行。一行永远不会是错的,至多是陈旧的——`observedSeq` 精确说明陈旧到哪。冷读与活读共用同一套读取配方:取缓存状态(或 `init()`),只对超出其水位线的事件做正向 `apply`,再对结果做 `view`。冷列表(跨全部 workspace 列出每个会话的标题)变成一次索引读,至多外加一小段尾部回放;session-persistence seam 在同一后续阶段为这段尾部补一个按 seq 起读的原语。写入策略:节流(次数/间隔,可配置)外加两个强制点——`turn/end` 与 detach(由活转冷的时刻)。两次写入之间崩溃的代价是尾部回放更长一些,绝不会是值出错。 +- 领域的输入事件集由领域自己选择:todos 只折叠 `todo/write`;plan 折叠 `plan/mode` 外加它自己的 `/plan` `command/run` 记录(见 plan 一节);goal 折叠 `goal/change` 元数据;会话标题折叠其标题事件(顺带下线专设的 `session/title` 帧与客户端的标题快照表——这是该 seam 收编的第四个手工投影)。 +- 注册是 effect(disposer 随 fiber 走):插件卸载后其 key 从后续响应中消失,客户端将其读作能力缺失——HMR(热模块替换)语义随之自动成立。key 重复直接 throw。领域插件在 `ctx.inject(['sessionProjections'], …)` 下注册,因此不带注册表的 headless 组装完全不受影响。 +- 该包拥有 `./invariant`(每个被服务的 key 都有一条存活的注册)。 + +### 协议层:历史尾页上的 projections 块 + +```ts ignore-check +// session.history response, tail page only (beforeSeq absent): +{ events, hasMore, + projections?: { asOfSeq: number, values: Partial } } +``` + +api-proxy 的历史处理器切出尾页后同步遍历注册表——全程没有一个 `await`,因此所有 key 的值与 `asOfSeq` 构成同一个一致切面。`asOfSeq` 是**最后一个事件的 seq**(`session.seq - 1`;空日志为 `-1`,与 `session/subscribed.lastSeq` 同一套词汇),因此携带基线之后首个变更的推送帧在比较时恒严格更大。api-proxy 不持有任何领域知识(与 `viewFor` 面向 `ctx.tools` 是同一种载体/贡献方关系)。 + +不新增 RPC 方法。时机上的重合是精确的:客户端每一个需要新基线的时刻(打开、重连重同步、缺口修补)本来就要拉尾页,而唯一永远不需要基线的路径(loadOlder)恰好是唯一传 `beforeSeq` 的路径。因此客户端**完全没有**独立的「重取基线」决策。窗口内容从不充当信号:「窗口里没有该领域的事件」这个问题在窗口内从构造上就无法回答,只有基线能回答它。 + +随此块下线的旧通道:`session.planMode` 与 `setPlanMode`(读写两侧——plan 选择改走标准命令通道,见 plan 一节)、`goals.get`(读侧;六个变更 RPC 保留,但其响应不再喂状态——mux 事件反正会到)、`todos` 搭载字段,以及 api-proxy 里的 `backscanTodos`(移入 todo 领域的单元,落在 `tool-todo`)。 + +### 推送帧与客户端值仓(领域零客户端代码) + +既然 host 是唯一计算地点,成品值经一个新的 mux 帧送达客户端: + +```ts ignore-check +// MuxFrame union + schema branch: +{ type: 'session/projection', sessionId, key: string, value: unknown, seq: number } +``` + +只要某单元的状态引用发生变化(上文的 `Object.is` 闸门),框架就发出该帧;`seq` 是发出时该单元的水位线。这是实时推送状态,绝不入日志——与 tool-view 的 `view` slot 同一姿态:回放时在 host 重新计算。 + +客户端对象层为每个会话维护一个**通用值仓(value store)**:`key → { value, seq }`,由尾页的 projections 块播种、由该帧更新,唯一规则是 **seq 高者胜**。重放的基线无法把更新的帧往回滚;丢失一个帧的代价只是陈旧——到下一个帧或基线为止——绝不会出错。没有 `fromEvent`,没有按领域的 cell 注册,没有客户端侧领域折叠——领域交付投影支持只需**零客户端代码**(`SessionProjectionMap` merge 经 `/types` 出口同时服务两侧)。专设的 `session/title` 帧与 manager 的标题快照表都收编进这对通用机制。所有按领域自造的栅栏(#587 的三层、#527 的写 revision)都消融进这一条 seq 规则。 + +### plan 走标准命令通道(完整示例) + +plan mode 完整演示了这套模式——触发路径、运行面、回放面,三者干净分离: + +- **触发路径**:web 的 plan 开关像任何其他命令一样经 `command.execute` 发送 `/plan` / `/plan off`;专设的 `setPlanMode`/`planMode` RPC 下线。用户的*请求*被持久记录为该命令的 `command/run { name: 'plan', args: 'off' | '' }`——结构化字段,无需解析行文本。 +- **运行面**(不变):plan-mode 服务在内存里保持待定意图,并在下一个轮次边界落下 `plan/mode`。冷启动时服务从回放面重建其意图队列(「运行态为空即以回放态为准」)。 +- **回放面**:plan 的投影单元折叠**两**种事件——它自己的 `command/run` 记录设置 `wanted`;`plan/mode` 设置 `active` 并清除 `wanted`;`view` 推导出 `{ active, pending: wanted !== null && wanted !== active }`。待定态由此成为纯回放量:host 重启能恢复它,其他标签页折叠同样的事件(跨标签页待定态随之自动获得),冷读回答 `{ active: false, pending: true }` 也是准确的(「一个未兑现的选择正等待恢复」)。 + +领域的输入事件集由领域自己选择——本示例落实的正是这条一般规则。「用户请求过 X」是出现在投影里(plan 折叠自己的命令记录),还是只出现在 flow 里(命令节点反正会渲染),属于各领域自己的语义,永远不是框架的关切。 + +### React:`useProjection`,第五个框架钩子席位 + +既有四个席位都装不下这份状态(store 纪律禁止业务对象;inject 禁止钩子;`ConversationSnapshot` 正在被清退)。`useProjection` 成为一个框架席位,在 web-react(唯一的钩子铸造点)铸造,经与 `useSession` 相同的标准套件通道(`provideInfo` → SessionProvider → props)送达: + +```ts ignore-check +type UseProjection = { + (key: K): SessionProjectionMap[K] | undefined + ( + key: K, selector: (v: SessionProjectionMap[K] | undefined) => S, + eq?: (a: S, b: S) => boolean): S +} +``` + +`undefined` 统一表示能力缺失(host 插件未挂载,或尚无任何基线/帧携带过该 key)。值仓只暴露按 key 的裸 `{subscribe, getSnapshot}` 面;其余交给带逐 key 缓存的 `bindSnapshotSelector`——引用稳定性成立,因为一个 key 的值引用只在帧或基线落地时才变化。写路径不变:变更回调留在 inject 共享面(回调出自 inject,活状态出自 `useProjection`)。 + +「钩子不得穿过 inject」的唯一既有违例——`DetailsInjected.useSelection`——随本变更一并收编:选中态是住在聊天 store 里的查看状态,因此 details 注册声明共享 store 句柄,组件改读 `props.useStore(s => s.selection)`;`useSelection` 退出 inject 契约。 + +### 日志中的命令生命周期 + +两个仅日志(非 surface、模型不可见)事件,镜像 `tool/call`/`tool/result` 的配对: + +```ts ignore-check +'command/run': { commandId: string; name: string; args: string; source: CommandSource } +'command/done': { commandId: string; kind: 'success' | 'error'; text?: string } +``` + +host 侧命令执行器(`packages/ui/commands`)在调用处理器前追加 `command/run`,在结算时追加 `command/done`——在接收 agent 的会话上直接独立追加,与[合成轮次移除](../../implemented/simplification/2026-07-28-remove-synthetic-log-only-turns.md)之后所有插件自有 log-only 事件同一形状:没有轮次包裹它们(轮次只描述模型循环执行),持久化在常规检查点排空它们,run/done 配对由 commands 包自己的 invariant 伴生插件把守。载荷是结构化的——`name` 与 `args` 就是解析器自己的切分(`parseCommand` 的 name 与 rawInput),因此消费方(折叠自己命令记录的投影单元、富命令卡片)永远无需重新解析行文本。`text` 是处理器的原样结果——与 `tool/result.content` 同一性质的事实数据,不是呈现(版式如何编排仍由客户端在渲染时计算,满足「呈现永不入日志」这条红线)。想让模型知道结果的领域继续做它们今天在做的事(plan 的旁白、goal 的注入)——那是领域自己的决定,保持不变。 + +由于已提交事件会在 mux 流上广播,刷新后仍在、多标签页同步、fork/恢复后可还原这三件事随之全部自动获得。`command.execute` RPC 退化为准入判定——`{ matched, commandId? }`:该行是否匹配命中,以及命中时新铸的配对 id,发起命令的客户端据此把自己的请求与生命周期事件产出的 flow 节点关联起来。一次性通知通道(`runDetached` → `noticeFor`)就此下线。 + +客户端 flow 构建器新增一个通用命令节点(run/done 按 `commandId` 配对;跨窗口截断时与工具配对同样软降级)。渲染走一个新的 keyed slot `'conversation.chat.commandview'`,key = 命令名,**兜底 = 通用命令卡片**(零注册即可用——从前的通知文本现在持久地渲染在 flow 里)。领域要升级展示,只需注册一个行组件,取材于 `command/run` 的结构化字段与自己的投影值(`useProjection`)——与 toolview 解散之后的工具行同一形状。 + +## Delivery plan + +基础设施先行;三个在途 PR(Pull Request)原样不动,待基座落地后重新对接(它们的迁移映射即指南): + +1. **host 基座**:`dsh-session-projection`(单元契约、正向驱动、水位线缓存)+ api-proxy 的 projections 块 + `session/projection` 推送帧。零领域注册也可合入(此时块与帧直接缺席)。 +2. **客户端基座**:通用值仓 + `useProjection` 席位;下线按领域的 cell 机制,并在标题单元注册后一并下线 `session/title` 帧与标题快照表。帧的形状依赖 1(在此之前 fixture(测试前置数据)喂合成帧)。 +3. **命令通道**:两个事件、执行器落日志、通用节点 + keyed slot、通知通道下线、`{matched, commandId?}` 准入。与 1 并行。 +4. **领域重新对接**(在 1+2 之后):先 todo(单元进 `tool-todo`,删掉搭载字段),再 plan(双事件单元、RPC 下线、开关改发 `/plan`),最后 goal(`goal/change` 单元,删掉 `goals.get`,把六个 `Session` 方法移入领域插件的 inject)。 +5. **持久投影缓存**(后续阶段,待 domain-KV 存储 seam 就绪后):`(sessionId, key, stateVersion, observedSeq, state)` 行、带 turn/end 与 detach 强制点的节流写入,以及持久化侧供冷尾部回放用的按 seq 起读原语。 + +## Alternatives considered + +**专设一个 `session.projections` RPC**——不予采纳:基线刷新时刻与尾页拉取精确重合,单独的一元 RPC 只会换来第二次往返、第二个待调和的 seq,以及一个客户端「何时重取」决策——而搭载设计把这个决策整个删掉了。 + +**不透明的 `get(agent)` 提供方契约**——曾是第一稿,后被否决:计算模型藏在领域内部时,框架永远无法为状态做检查点、无法服务冷会话(没有 agent、没有已加载的日志——`get` 无处可跑)、也无法从日志中段续算。注册 `(init, apply, view)` 单元把驱动权交给框架,领域只留纯数学;有 host 侧行为需求的领域,其服务订阅照旧自持,与投影单元互不牵连。 + +**为 plan 待定意图专设的仅实时叠加钩子(`live?(agent, base)`)**——不予采纳:它存在的唯一理由是用户的 plan *选择*不在日志里。让选择走标准命令通道后,`command/run` 上了账,待定态成为纯回放量,投影契约保持恰好三个纯函数。 + +**把 seam 命名为 `registerFold`**——已被单元契约取代:注册对象如今确实是一个折叠,但本仓库里 `fold*` 专指纯 `(events) => state` 辅助函数,而该 seam 注册的是带 key、带 schema、带版本的单元。投影仍是事件溯源中指称读模型角色的术语,#587 的 Note 标题与 #497 的评论也都已在使用它。 + +**客户端侧折叠(带 `fromEvent` 的按领域投影 cell)**——曾是第二稿,后被否决:一旦 plan 的单元要折叠两种事件,客户端 cell 就必须在浏览器里复刻 host 的状态转移逻辑——同一个折叠写两遍、各自演化。推送成品值(标题帧先例的泛化)保住唯一计算地点,并把客户端简化为一个由 seq 把守的通用值仓;领域零客户端代码。 + +**对日志尾部的有界反向扫描(absorber 声明)**——暂不采纳:今天没有任何东西需要它,它只服务于「每个事件都携带完整折叠状态」的领域,而持久投影缓存以统一方式覆盖同一冷读需求(缓存行 + 正向尾部回放——与客户端的基线 + 追赶、与分页加载是同一套配方)。只有当出现检查点机制服务不了的真实冷读路径时才重议。 + +**`invalidate` 式 cell(标脏,遇领域事件就重取)**——不予采纳:它的存在只为伺候增量事件。全量值规则让每个领域都是 last-wins;goal 的重取循环、合并逻辑、陈旧读栅栏随之全部消失。 + +**把注册表挂到 `ctx.apiProxy` 名下**——不予采纳:会话投影并非 web 专属(TUI、ACP(Agent Client Protocol)、headless 都是未来消费方),且领域包不得依赖 apiproxy 包。独立 seam 还顺带删掉了 #587 从 api-proxy 指向 plan 包的 type-only 导入边。 + +**独立的客户端 `SessionProjectionViews` 类型表**——不予采纳:一张 `SessionProjectionMap` 端到端贯通正是协议直通纪律(不设第二套 DTO 词汇);值就是 JSON 载荷,渲染归 slot 管。 + +**用事件广播收集、替代注册表遍历**——不予采纳:异步监听器给不出那个单一的同步切面,而正是它让 `asOfSeq` 成为横跨所有 key 的一致快照;注册表才是本仓库承接贡献的通行形状(`ctx.tools`、提示词片段、slot)。 + +**专设 `plan/select` 选择事件(用结构化领域事件替代折叠命令记录)**——不予采纳,改用命令通道:`command/run` 的结构化 `{name, args}` 已经记录了选择,`/plan` 的语法与其折叠逻辑同住一个插件(领域内耦合,非跨领域),还少一种事件类型。处理器必须在任何可能失败的路径之前调用 `set()`,使已入日志的请求与运行面不可能分叉——这是领域内部的顺序约束,文档写在处理器处。 + +**保留 `setPlanMode` 专用 RPC**——不予采纳:plan 选择就是一条普通的用户命令;命令通道给它持久记录、flow 渲染、多标签页可见性与准入语义,不需要专设协议方法。Web UI 的交互组件(一个开关)在内部拼出命令行即可。 + +**让变更 RPC 的响应喂 cell 状态**——不予采纳:已提交的 mux 事件即刻到达,携带同一个全量值外加 seq;「响应喂状态」正是当初逼出 #527 写 revision 栅栏的根源。 + +## Acceptance criteria + +- 领域插件把按会话的日志派生状态送达 React,只需写:全量值事件声明、一次 host 侧单元 `register`、自己那份 `SessionProjectionMap` merge、以及 inject 回调——零客户端侧代码,不改客户端 `Session` 类、`ConversationSnapshot`、api-proxy 或任何协议 schema 文件。 +- 历史尾页携带 `projections`,其 `asOfSeq` 等于窗口尾部 seq;loadOlder 页永不携带;未装注册表的部署照常返回不带该块的历史,客户端把所有 key 视为缺席。 +- 陈旧的基线不能覆盖更新的 `session/projection` 帧,重放的帧也不能让值仓倒退(两条路径都做 seq 高者胜测试)。 +- 在一个标签页执行的斜杠命令,刷新后、在第二个标签页上、恢复之后都在 flow 中渲染出持久节点;未注册的命令渲染通用卡片;命令结果的 composer 通知路径彻底移除。 +- `useProjection` 经标准 props 套件抵达组件;没有任何钩子穿过 inject 契约(包括 `useSelection`)。 +- 会话标题搭乘这对通用机制(基线块 + 投影帧);专设的 `session/title` 帧与客户端标题快照表彻底移除。 + +## Risks + +- **全量值规则是承重结构**:未来某个领域若只记裸增量,就无法凭其最新事件服务消费方,还会让自己的单元复杂化。缓解:该规则写明在本 Note 与投影包的 README 里;单元契约让完整状态在每次转移处都是显式的。 +- **单元的同步纪律**:`init`/`apply`/`view` 一旦 await 就会撕裂一致性切面。注册表在文档中申明这条纪律,invariant 配套在可行范围内断言同步性;其余由评审把关。 +- **注册表的实时增删不做推送**:会话中途加载或卸载领域插件会改变键集,但不会触发任何会话事件、也不会推任何帧;开着的客户端持有陈旧的 key 直到下次尾页拉取(重连、缺口修补、打开)。接受为仅开发期(HMR)的陈旧时窗——日后可以在变更流上加一个注册表变更推送,契约不受影响。 +- **忙碌会话上的正向驱动开销**:每个已提交事件都要过每个已注册单元的 `apply`。按构造,单元的逐事件开销很低(全量值规则),不匹配的事件返回同一引用,且已注册领域的数量很小;若真出现热点路径,可以加按单元的事件类型预过滤,契约不变。 +- **投影载荷膨胀**:每个尾页携带每个已注册的 key。载荷是 UI 量级状态的全量值(一张 todo 清单、一份 goal 快照);将来若某领域的值很大,可以在请求上加逐 key 的 opt-out 或惰性 key,模型本身不用改。 +- **命令日志体量**:每条斜杠命令两个仅日志事件;上限由人敲命令的频率决定,相对分片体量可忽略不计。 +- **重新对接的返工**:三个未合入的 PR 要变基到挪动后的地基上。这是基础设施先行的既定代价;设计台账中的迁移映射一节逐一列出每个 PR 的保留/删除清单。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index b3c64813e3..7428f56b60 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -22,6 +22,13 @@ - id: session name: '@deepseek-ai/dsh-session' +# Projection registry: drives every registered domain unit over committed +# session events and serves finished values (history-tail projections block + +# session/projection frames). Without this row every domain's optional unit +# injection stays silent — no block, no frames, no titles/todos on the web. +- id: session-projection + name: '@deepseek-ai/dsh-session-projection' + - id: session-title name: '@deepseek-ai/dsh-session-title' config: diff --git a/apps/cli/package.json b/apps/cli/package.json index e21c093499..2de87a4691 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -56,9 +56,9 @@ "@deepseek-ai/dsh-llm-retry": "workspace:^", "@deepseek-ai/dsh-paths": "workspace:^", "@deepseek-ai/dsh-plan-mode": "workspace:^", - "@deepseek-ai/dsh-subprocess-local": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-session-title-first-message-llm": "workspace:^", "@deepseek-ai/dsh-skill": "workspace:^", @@ -71,6 +71,7 @@ "@deepseek-ai/dsh-subagent": "workspace:^", "@deepseek-ai/dsh-subagent-fork": "workspace:^", "@deepseek-ai/dsh-subagent-spawn": "workspace:^", + "@deepseek-ai/dsh-subprocess-local": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tasks-local": "workspace:^", "@deepseek-ai/dsh-timeout-policy": "workspace:^", diff --git a/apps/web/tests/code-mode-fixture.snapshot.ts b/apps/web/tests/code-mode-fixture.snapshot.ts index f53777fff8..ce5a98b2eb 100644 --- a/apps/web/tests/code-mode-fixture.snapshot.ts +++ b/apps/web/tests/code-mode-fixture.snapshot.ts @@ -5,7 +5,7 @@ // the code-variant parent row titled by the model-authored description, its // three always-visible nested sub-rows (bash through the sample registration, // read through GenericToolCard, the failing read wearing the error state), -// the expanded program body, details-panel resolution of a sub-callId, and +// the expanded program body, inert bash / file-link sub-row gestures, and // the trajectory/waterfall tabs' sub-call cells and timing lanes. import { readFileSync } from 'node:fs' import { join } from 'node:path' @@ -152,7 +152,7 @@ it('renders the fixture run_code turn: code parent row, nested sub-rows, error s `) }) -it('expands the code row into the program body and resolves a sub-row through the details panel', async () => { +it('expands the code row into the program body; sub-row clicks do not open details', async () => { boot() await openFixtureSession() @@ -171,26 +171,28 @@ it('expands the code row into the program body and resolves a sub-row through th } }) - // Sub-row click → details panel resolves the sub-callId with FULL output. + // Tool rows no longer drive the details panel: bash is inert, file paths + // are host-open links (fixture openPath is a no-op success). const nest = document.querySelector('[data-subcalls]') if (nest === null) throw new Error('sub-call nest missing') const bashRow = nest.querySelector('[data-sample="bash-global"]') if (bashRow === null) throw new Error('bash sample sub-row missing') + const fileLink = nest.querySelector('button') + if (fileLink === null) throw new Error('file-path summary link missing on a read sub-row') + const frame = document.querySelector('[data-details-collapsed]') + if (frame === null) throw new Error('app frame missing') + expect(frame.getAttribute('data-details-collapsed')).toBe('true') fireEvent.click(bashRow) - const details = await screen.findByText('Input') - const panel = details.closest('[class*="root"]') - if (panel === null) throw new Error('details panel missing') + expect(frame.getAttribute('data-details-collapsed')).toBe('true') + fireEvent.click(fileLink) + expect(frame.getAttribute('data-details-collapsed')).toBe('true') expect({ - title: visibleText(within(panel as HTMLElement).getByText('bash')), - inputEchoesArgs: visibleText(panel).includes('ls notes'), - outputComplete: visibleText(panel).includes('demo.txt new-demo.txt') - || visibleText(panel).includes('demo.txt\nnew-demo.txt') - || (panel.textContent ?? '').includes('demo.txt\nnew-demo.txt'), + fileLink: visibleText(fileLink), + detailsCollapsed: frame.getAttribute('data-details-collapsed'), }).toMatchInlineSnapshot(` { - "inputEchoesArgs": true, - "outputComplete": true, - "title": "bash", + "detailsCollapsed": "true", + "fileLink": "notes/demo.txt", } `) }) diff --git a/apps/web/tests/code-mode-round.e2e.ts b/apps/web/tests/code-mode-round.e2e.ts index 32c51a2a2a..a7f493e448 100644 --- a/apps/web/tests/code-mode-round.e2e.ts +++ b/apps/web/tests/code-mode-round.e2e.ts @@ -118,19 +118,14 @@ describe('web e2e: Code Mode round renders nested sub-calls', () => { expect(await nest.locator('[data-state="error"]').count()).toBeGreaterThanOrEqual(1) }, 60_000) - it.skipIf(MODE === 'record')('a sub-row click opens the details panel on the sub-call material', async () => { + it.skipIf(MODE === 'record')('a bash sub-row click leaves the details panel collapsed', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-code-mode-details')) const nest = page.locator('[data-subcalls]').first() + const frame = page.locator('[data-details-collapsed], [class*="frame"]').first() + expect(await frame.getAttribute('data-details-collapsed')).not.toBeNull() await nest.locator('[data-sample="bash-global"]').first().click() - // The details column opens (width > 0) and shows the sub-call's complete - // output — the full-content log contract, no truncation marker anywhere. - await page.waitForFunction(() => { - const frame = document.querySelector('[class*="frame"]') - if (frame === null) return false - return Number(getComputedStyle(frame).gridTemplateColumns.split(' ').pop()!.replace('px', '')) > 0 - }, undefined, { timeout: 10_000 }) - await expect.poll(() => page.getByText('CODE_ROUND_OK', { exact: false }).count(), { timeout: 5_000 }) - .toBeGreaterThanOrEqual(1) + // Tool rows no longer open details; the column stays width 0. + await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 5_000 }).not.toBeNull() }) it.skipIf(MODE === 'record')('matches the conversation aria golden with stable anchors', async () => { diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index bbae7363df..a27a61f80f 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -1,12 +1,11 @@ // Web e2e scenarios: navigation & panes — the view tabs (Trajectory / -// Waterfall), the details column, and sidebar search, all over ONE rich -// two-turn seeded fixture rendered purely from the log (the seeded-history -// pattern: zero model calls in replay, so every surface here is the client -// fold + host history RPC, not replay binding). The seed is recorded live -// under the standard discipline: turn 1 produces a bash call plus two -// parallel reads in one assistant message (tool-call density for the -// trajectory/waterfall lanes and a details-capable bash row), turn 2 a -// markdown-rich reply (a second turn so the waterfall has two lanes). +// Waterfall) and sidebar search, all over ONE rich two-turn seeded fixture +// rendered purely from the log (the seeded-history pattern: zero model calls +// in replay, so every surface here is the client fold + host history RPC, +// not replay binding). The seed is recorded live under the standard +// discipline: turn 1 produces a bash call plus two parallel reads in one +// assistant message (tool-call density for the trajectory/waterfall lanes), +// turn 2 a markdown-rich reply (a second turn so the waterfall has two lanes). import { mkdir, readFile, writeFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' @@ -25,7 +24,6 @@ const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/navigation-panes', impor const SEED = join(SNAPSHOT_DIR, 'seed.jsonl') const TRAJECTORY_EXPECTED = join(SNAPSHOT_DIR, 'trajectory.expected.md') const WATERFALL_EXPECTED = join(SNAPSHOT_DIR, 'waterfall.expected.md') -const DETAILS_EXPECTED = join(SNAPSHOT_DIR, 'details-open.expected.md') const MODE = webSnapshotMode() const SEED_ID = 'navigation-panes-web-e2e' @@ -155,36 +153,27 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { await compareOrRefreshGolden(WATERFALL_EXPECTED, snapshot, MODE) }, 60_000) - it.skipIf(MODE === 'record')('opens the details column from the bash row and closes it', async () => { + it.skipIf(MODE === 'record')('bash and file-path rows leave the details column collapsed', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-details')) await page.getByRole('tab', { name: 'Chat' }).click() - // The bash toolview row routes its click to openDetails (read rows are - // expand-in-place instead — the seeded-history scenario owns that fold). const bashRow = page.locator('[data-sample="bash-global"]').first() await bashRow.waitFor({ timeout: 15_000 }) - // Open/closed is the frame's collapsed attribute: the column collapses to - // width 0 but its subtree deliberately never unmounts (hidden, not - // absent), so element presence/visibility cannot express the state. const frame = page.locator('[data-details-collapsed], [class*="frame"]').first() expect(await frame.getAttribute('data-details-collapsed')).not.toBeNull() await bashRow.click() - await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 10_000 }).toBeNull() - // The open panel shows the selected call's name, arguments, and durable - // result (NAVIGATION_OK appears in the chat row too, hence >= 2 total). - await expect.poll(() => page.getByText('NAVIGATION_OK', { exact: false }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2) - // Golden of the open panel: tool name header, Input args, Output result. - const snapshot = (await captureStableAria(page, '[class*="detailsCol"]', scaffold.workspaceCwd)) - .split(SEED_ID).join('{{seededId}}') - await compareOrRefreshGolden(DETAILS_EXPECTED, snapshot, MODE) - await page.getByRole('button', { name: '关闭详情' }).click() - await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 10_000 }).not.toBeNull() + await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 5_000 }).not.toBeNull() + // Read summaries are host-open file links; they also must not open details. + const fileLink = page.locator('[data-variant="read"] button').first() + await fileLink.waitFor({ timeout: 10_000 }) + await fileLink.click() + await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 5_000 }).not.toBeNull() }, 60_000) it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => { expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, [ - 'seed.jsonl', 'trajectory.expected.md', 'waterfall.expected.md', 'details-open.expected.md', + 'seed.jsonl', 'trajectory.expected.md', 'waterfall.expected.md', ]) }) }) diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index 265bb20d07..d30b3d7c39 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -71,6 +71,35 @@ describe('web e2e: seeded history renders through cold resume', () => { await recordFixture(scaffold, sessionId, SEED) }, 200_000) + it.skipIf(MODE === 'record')('serves the projections baseline on the real composition tail page', async () => { + // Composition regression tripwire: the projection registry must be a row + // in the SHIPPED cordis.yml — with it absent every domain unit's optional + // injection stays silent and this block disappears (no titles/todos on + // the web), while fixture-level suites stay green. Assert through the + // real HTTP wire against the booted real host. + const response = await fetch(`${scaffold.baseUrl}/api/session.history`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + type: 'client-request', rpcId: 'seeded-projections', method: 'session.history', + payload: { sessionId: SEED_ID }, + }), + }) + expect(response.ok).toBe(true) + const body = await response.json() as { + result: { ok: boolean; value?: { projections?: { asOfSeq: number; values: Record } } } + } + expect(body.result.ok).toBe(true) + const projections = body.result.value?.projections + expect(projections).toBeDefined() + expect(projections?.asOfSeq).toBeGreaterThanOrEqual(0) + // The seed carries a session/title event: the title unit must serve it. + expect(typeof projections?.values.title).toBe('string') + // tool-todo is composed but the seed has no todo/write: whole-value null, + // key PRESENT (absence would mean the unit never registered). + expect(projections?.values).toHaveProperty('todos', null) + }) + it.skipIf(MODE === 'record')('lists the seeded session cold and renders its history from the log', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-history')) // The sidebar tree collapses workspace groups by default: click the group @@ -103,21 +132,19 @@ describe('web e2e: seeded history renders through cold resume', () => { await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) }) - it.skipIf(MODE === 'record')('expands and collapses a tool row rebuilt from the cold log', async () => { + it.skipIf(MODE === 'record')('file-path tool rows rebuilt from the cold log stay details-inert', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-toolrow')) - // Interaction over cold-resumed history: read rows are expand-in-place - // rows (rowExpands routes the click to toggleExpand, not openDetails), so - // the gesture under test is the inline fold over log-rebuilt content. - // Runs after the golden capture; still zero model calls. - const row = page.locator('[data-variant] [data-clickable][role="button"]').first() - await row.waitFor({ timeout: 10_000 }) - expect(await row.getAttribute('aria-expanded')).toBe('false') - await row.click() - await expect.poll(() => row.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true') - // The expanded body renders the recorded tool result (a.txt's contents). - await expect.poll(() => page.getByText('alpha', { exact: false }).count(), { timeout: 5_000 }).toBeGreaterThan(0) - await row.click() - await expect.poll(() => row.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false') + // Interaction over cold-resumed history: read summaries are host-open + // file links (not expand-in-place / not details). Runs after the golden + // capture; still zero model calls. + const fileLink = page.locator('[data-variant="read"] button').first() + await fileLink.waitFor({ timeout: 10_000 }) + const frame = page.locator('[data-details-collapsed], [class*="frame"]').first() + expect(await frame.getAttribute('data-details-collapsed')).not.toBeNull() + await fileLink.click() + await expect.poll(() => frame.getAttribute('data-details-collapsed'), { timeout: 5_000 }).not.toBeNull() + // Path label survives from the recorded args (a.txt). + await expect.poll(() => page.getByText('a.txt', { exact: false }).count(), { timeout: 5_000 }).toBeGreaterThan(0) }) it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => { diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index 58db1beafd..47d6ea81f7 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -7,7 +7,7 @@ // // Selector convention: CSS Modules hash as [hash]_[local], so class-substring // selectors are unreliable — anchor on data-* attributes (data-variant / -// data-clickable / data-sample) or visible text. The one [class*=] use below +// data-sample) or visible text. The one [class*=] use below // (frame/handle) rides local names that survive hashing as suffixes; prefer // data-* for anything new. // @@ -448,7 +448,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke await screen(page, '07-back-to-chat') }) - it('5 bash differential rendering: tool row click opens the details column', async () => { + it('5 bash differential rendering: tool row click leaves the details column collapsed', async () => { onTestFailed(() => saveFailureShot(page, 'w5-tool-details')) const input = page.locator('textarea').first() await input.fill('请用 bash 工具运行命令 echo w5marker 然后告诉我结果') @@ -462,13 +462,9 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke await screen(page, '08-bash-round') expect(await detailsTrack(page)).toBe(0) await toolRow.click() - // Selection channel: click writes selection + layout.openDetails. - await page.waitForFunction(() => { - const frame = document.querySelector('[class*="frame"]') - if (frame === null) return false - return Number(getComputedStyle(frame).gridTemplateColumns.split(' ').pop()!.replace('px', '')) > 0 - }, undefined, { timeout: 10_000 }) - await screen(page, '09-details-open') + // Tool rows no longer drive layout.openDetails; the column stays closed. + expect(await detailsTrack(page)).toBe(0) + await screen(page, '09-details-closed') }, 150_000) it('6 sidebar drag widens the column and persists across reload', async () => { diff --git a/apps/web/tests/snapshots/navigation-panes/details-open.expected.md b/apps/web/tests/snapshots/navigation-panes/details-open.expected.md deleted file mode 100644 index d69a95eb2d..0000000000 --- a/apps/web/tests/snapshots/navigation-panes/details-open.expected.md +++ /dev/null @@ -1,5 +0,0 @@ -- text: bash -- button "关闭详情" -- text: Input -- code: "{ \"command\": \"echo NAVIGATION_OK\", \"description\": \"Print NAVIGATION_OK\" }" -- text: Output NAVIGATION_OK diff --git a/docs/capability-seams.md b/docs/capability-seams.md index cea4bf80af..00bfca0c91 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -78,6 +78,9 @@ flowchart LR svc_planMode["ctx.planMode
Plan collaboration state"] pkg_commands["commands"] svc_commands["ctx.commands
Human command registry"] + pkg_session_projection["session-projection"] + svc_sessionProjections["ctx.sessionProjections
Session projection units"] + pkg_host_apiproxy["host-apiproxy"] svc_tui["ctx.tui
Mounted-terminal interaction service"] pkg_skill["skill"] svc_skills["ctx.skills
Skill provider registry"] @@ -186,6 +189,7 @@ flowchart LR pkg_session_persistence --> svc_sessionPersistence pkg_session_persistence_jsonl --> svc_sessionPersistence pkg_session_persistence_sqlite --> svc_sessionPersistence + pkg_session_projection --> svc_sessionProjections pkg_session_query --> svc_sessionQuery pkg_session_query_sqlite --> svc_sessionQuery pkg_session_reference --> svc_sessionReferences @@ -265,6 +269,9 @@ flowchart LR svc_sessionPersistence --> pkg_session_query svc_sessionPersistence --> pkg_session_query_sqlite svc_sessionPersistence --> pkg_tool_bash + svc_sessionProjections --> pkg_host_apiproxy + svc_sessionProjections --> pkg_session_title + svc_sessionProjections --> pkg_tool_todo svc_sessionQuery --> pkg_session_reference svc_sessionQuery --> pkg_tool_session_query svc_sessionReferences --> pkg_tui @@ -337,6 +344,7 @@ flowchart LR | `ctx.userInteraction` | `seam` | [`user-interaction`](../packages/ui/user-interaction) | [`tui`](../packages/ui/tui) | [`tool-ask-user`](../packages/ui/tool-ask-user), [`tui`](../packages/ui/tui) | - | UI front doors provide the active human-answer provider; tool-ask-user pauses a tool call on the provider-neutral ask() promise. | | `ctx.planMode` | `core` | [`plan-mode`](../packages/plan/plan-mode) | - | - | - | Folds logged plan/mode state, flushes user selections at turn boundaries, renders deployment-owned guidance, registers /plan, and keeps the plan-exit schema stable across transitions. | | `ctx.commands` | `core` | [`commands`](../packages/ui/commands) | - | [`tui`](../packages/ui/tui) | - | Plugins register direct human commands; TUI consumes the effective per-agent catalog without sending invocations to the model. | +| `ctx.sessionProjections` | `core` | [`session-projection`](../packages/session-projection/session-projection) | - | [`tool-todo`](../packages/todo/tool-todo), [`session-title`](../packages/session-title/session-title), [`host-apiproxy`](../packages/host/apiproxy) | - | Domains register state-driven fold units; the eager drive keeps per-session watermark states and api-proxy serves baselines and pushes changed values. | | `ctx.tui` | `bundle` | [`tui`](../packages/ui/tui) | - | - | - | One TUI front door provides a FIFO overlay host; injected plugins receive caller-fiber ownership without access to pi-tui or terminal lifecycle state. | | `ctx.skills` | `seam` | [`skill`](../packages/skill/skill) | [`skill-local`](../packages/skill/skill-local) | [`tool-skill`](../packages/skill/tool-skill) | - | Merges provider skill catalogs; tool-skill renders the session-prefix catalog and loads complete skill bodies. | | `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`cli-demo`](../packages/examples/cli-demo), [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`tui-demo`](../packages/examples/tui-demo) | - | Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation. | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 2444a9f3ca..d1b5e5cea8 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1169,7 +1169,7 @@ export interface Config { } ``` -Source: [`packages/session-title/session-title/src/index.ts:67`](../packages/session-title/session-title/src/index.ts) +Source: [`packages/session-title/session-title/src/index.ts:75`](../packages/session-title/session-title/src/index.ts) ## `@deepseek-ai/dsh-session-title-all-messages-llm` @@ -2191,6 +2191,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-pty` ([`packages/pty/pty/src/index.ts`](../packages/pty/pty/src/index.ts)) - `@deepseek-ai/dsh-session` ([`packages/core/session/src/index.ts`](../packages/core/session/src/index.ts)) - `@deepseek-ai/dsh-session-checkpoint-policy` — requires `llm` · `sessionPersistence` · `sessions` · `tools` ([`packages/session-persistence/session-checkpoint-policy/src/index.ts`](../packages/session-persistence/session-checkpoint-policy/src/index.ts)) +- `@deepseek-ai/dsh-session-projection` ([`packages/session-projection/session-projection/src/index.ts`](../packages/session-projection/session-projection/src/index.ts)) - `@deepseek-ai/dsh-storage` ([`packages/storage/storage/src/index.ts`](../packages/storage/storage/src/index.ts)) - `@deepseek-ai/dsh-subagent` ([`packages/subagent/subagent/src/index.ts`](../packages/subagent/subagent/src/index.ts)) - `@deepseek-ai/dsh-subprocess-local` ([`packages/subprocess/subprocess-local/src/index.ts`](../packages/subprocess/subprocess-local/src/index.ts)) diff --git a/docs/cordis-catalog/events.md b/docs/cordis-catalog/events.md index ca0e9b82fc..751124de69 100644 --- a/docs/cordis-catalog/events.md +++ b/docs/cordis-catalog/events.md @@ -419,7 +419,7 @@ A command was registered or unregistered. This is an unfiltered registry notific 'commands/change'(): void ``` -Source: [`packages/ui/commands/src/index.ts:103`](../../packages/ui/commands/src/index.ts) +Source: [`packages/ui/commands/src/index.ts:154`](../../packages/ui/commands/src/index.ts) ## `domain/*` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 44ebd6a8be..a24254481d 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -445,17 +445,29 @@ find(agent: Agent, name: string): CommandDefinition | undefined /** * Parse and execute a known command without sending it to the model. + * + * A resolved command's lifecycle is logged: `command/run` is appended + * before the handler is invoked and `command/done` after settlement (a + * thrown or aborted handler settles as `kind: 'error'`). Both are direct + * log-only appends — no turn wraps them, and persistence drains them at + * ordinary checkpoints. Admission misses (syntax or unknown name) log + * nothing — they never entered a handler. A `command/run` append failure + * fails the execution loud; a `command/done` append failure on the + * handler-failure path is contained so the handler's own error stays the + * reported failure. + * * @param agent - exact receiving agent. * @param line - complete slash-command line. * @param signal - cancellation signal owned by the UI request. - * @returns a detached result, or `undefined` when syntax or name does not resolve. + * @returns the settled execution (result + lifecycle pairing id), or + * `undefined` when syntax or name does not resolve. */ -async execute( agent: Agent, line: string, signal: AbortSignal, ): Promise +async execute( agent: Agent, line: string, signal: AbortSignal, ): Promise ``` -Types: [Agent](../core-data-structures/core.md) · [CommandDefinition](../core-data-structures/commands.md) · [CommandDescriptor](../core-data-structures/commands.md) · [CommandResult](../core-data-structures/commands.md) +Types: [Agent](../core-data-structures/core.md) · [CommandDefinition](../core-data-structures/commands.md) · [CommandDescriptor](../core-data-structures/commands.md) -Source: [`packages/ui/commands/src/index.ts:227`](../../packages/ui/commands/src/index.ts) +Source: [`packages/ui/commands/src/index.ts:278`](../../packages/ui/commands/src/index.ts) ## `ctx.compact` — `CompactService` (abstract seam) @@ -1101,6 +1113,44 @@ Types: [SessionEvent](../core-data-structures/core.md) · [SessionHeader](../cor Source: [`packages/session-persistence/session-persistence/src/index.ts:52`](../../packages/session-persistence/session-persistence/src/index.ts) +## `ctx.sessionProjections` — `SessionProjectionRegistry` + +`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference notifies the change feed with the schema-validated view. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. Duplicate keys throw. Domain plugins register under `ctx.inject(['sessionProjections'], …)` so headless assemblies without the registry stay unaffected. + +```ts cordis-catalog +/** + * Register one domain's unit. The registration is an effect on the calling + * context's fiber: disposing the fiber (or calling the returned disposer) + * removes the key — and the unit's cached cells — from subsequent drives + * and snapshots. + * @param definition - key, boundary schema, pure unit functions, and stateVersion. + * @returns the exact disposer that unregisters this unit. + */ +register(definition: ProjectionDefinition): () => void + +/** + * Subscribe to the change feed. The registration is an effect on the + * calling context's fiber. + * @param listener - called once per unit whose state reference changed, per committed event. + * @returns the exact disposer that unsubscribes. + */ +onChanged(listener: ProjectionChangeListener): () => void + +/** + * One consistent cut over every registered unit for one session, read from + * the watermark cache (missing cells fold lazily over the in-memory log). + * Fully synchronous — every value and `asOfSeq` reflect the same log + * position. Each value passes its unit's schema before leaving. + * @param session - the session whose projection values are read. + * @returns the snapshot; `values` is empty when no unit is registered. + */ +snapshot(session: Session): ProjectionSnapshot +``` + +Types: [Session](../core-data-structures/session.md) + +Source: [`packages/session-projection/session-projection/src/index.ts:136`](../../packages/session-projection/session-projection/src/index.ts) + ## `ctx.sessionQuery` — `SessionQueryService` (abstract seam) Unified live-preferred session query service. @@ -1418,7 +1468,7 @@ register(provider: SessionTitleProvider): () => Promise Types: [Session](../core-data-structures/session.md) · [SessionTitleProvider](../core-data-structures/session-title.md) · [SessionTitleSnapshot](../core-data-structures/session-title.md) -Source: [`packages/session-title/session-title/src/index.ts:232`](../../packages/session-title/session-title/src/index.ts) +Source: [`packages/session-title/session-title/src/index.ts:240`](../../packages/session-title/session-title/src/index.ts) ## `ctx.skills` — `SkillService` diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index e9e5bb6e6a..6d1f4fa730 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -24,7 +24,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/step` | `serial` | [`packages/core/agent/src/types.ts:349`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic), [`plan-mode`](../packages/plan/plan-mode), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`time-context`](../packages/context/time-context), [`tool-skill`](../packages/skill/tool-skill), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/types.ts:396`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | | `approval/request` | `waterfall` | [`packages/ui/user-approval/src/index.ts:30`](../packages/ui/user-approval/src/index.ts) | [`user-approval`](../packages/ui/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp) | -| `commands/change` | `emit` | [`packages/ui/commands/src/index.ts:103`](../packages/ui/commands/src/index.ts) | [`commands`](../packages/ui/commands) (`events.dispatch`) | `apiproxy`, [`tui`](../packages/ui/tui) | +| `commands/change` | `emit` | [`packages/ui/commands/src/index.ts:154`](../packages/ui/commands/src/index.ts) | [`commands`](../packages/ui/commands) (`events.dispatch`) | `apiproxy`, [`tui`](../packages/ui/tui) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `apiproxy`, [`storage-domain`](../packages/storage/storage-domain), [`workspace`](../packages/workspace/workspace) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:62`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:71`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`emit`) | [`fs-policy`](../packages/fs/fs-policy) | @@ -33,7 +33,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:56`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`llm-replay`](../packages/support/llm-replay), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-title`](../packages/session-title/session-title) | | `session/created` | `emit` | [`packages/core/session/src/index.ts:70`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `apiproxy`, [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`llm-retry`](../packages/llm/llm-retry), [`plan-mode`](../packages/plan/plan-mode), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-telemetry`](../packages/telemetry/session-telemetry), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:80`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `apiproxy`, [`session-persistence`](../packages/session-persistence/session-persistence), [`session-telemetry`](../packages/telemetry/session-telemetry), [`session-title`](../packages/session-title/session-title) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:92`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), `apiproxy`, [`cli-demo`](../packages/examples/cli-demo), [`compact`](../packages/compact/compact), [`compact-basic`](../packages/compact/compact-basic), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`plan-mode`](../packages/plan/plan-mode), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-telemetry`](../packages/telemetry/session-telemetry), [`session-title`](../packages/session-title/session-title), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`tui`](../packages/ui/tui), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:92`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), `apiproxy`, [`cli-demo`](../packages/examples/cli-demo), [`compact`](../packages/compact/compact), [`compact-basic`](../packages/compact/compact-basic), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`plan-mode`](../packages/plan/plan-mode), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-projection`](../packages/session-projection/session-projection), [`session-telemetry`](../packages/telemetry/session-telemetry), [`session-title`](../packages/session-title/session-title), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`tui`](../packages/ui/tui), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:102`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence`](../packages/session-persistence/session-persistence), [`session-telemetry`](../packages/telemetry/session-telemetry) | | `slash/input-begin-command` | `bail` | [`packages/client/ui-slash/src/types.ts:230`](../packages/client/ui-slash/src/types.ts) | - | `ui-conversation` | | `slash/input-consume-token` | `bail` | [`packages/client/ui-slash/src/types.ts:244`](../packages/client/ui-slash/src/types.ts) | - | `ui-conversation` | @@ -65,7 +65,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | --- | --- | --- | | `commands/changed` | `runtime` (`emit`) | - | | `connection/reset` | `runtime` (`emit`) | - | -| `internal/dispatch` | - | [`compact`](../packages/compact/compact), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`pty-local`](../packages/pty/pty-local), `runtime`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`workflow`](../packages/workflow/workflow) | +| `internal/dispatch` | - | [`commands`](../packages/ui/commands), [`compact`](../packages/compact/compact), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`pty-local`](../packages/pty/pty-local), `runtime`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`workflow`](../packages/workflow/workflow) | | `internal/plugin` | - | `hmr`, `modules`, `webserver` | | `internal/status` | - | [`agent`](../packages/core/agent) | | `locale/change` | `locale` (`emit`) | `locale`, `ui-models`, `ui-settings-general` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 761064596b..5170b87eba 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -213,6 +213,9 @@ flowchart TD pkg_sdk_protocol["sdk-protocol"] pkg_telemetry["telemetry"] end + subgraph group_session_projection["packages/session-projection"] + pkg_session_projection["session-projection"] + end subgraph group_storage["packages/storage"] pkg_storage["storage"] pkg_storage_domain["storage-domain"] @@ -410,10 +413,6 @@ flowchart TD pkg_session_persistence --> pkg_brand pkg_session_persistence --> pkg_invariants pkg_session_persistence --> pkg_session - pkg_session_title --> pkg_brand - pkg_session_title --> pkg_invariants - pkg_session_title --> pkg_llm - pkg_session_title --> pkg_session pkg_llm_replay --> pkg_invariants pkg_llm_replay --> pkg_llm pkg_llm_replay --> pkg_session @@ -444,6 +443,8 @@ flowchart TD pkg_sandbox_policy --> pkg_invariants pkg_sandbox_policy --> pkg_sandbox pkg_sandbox_policy --> pkg_session + pkg_session_projection --> pkg_invariants + pkg_session_projection --> pkg_session pkg_llm_retry --> pkg_agent pkg_llm_retry --> pkg_invariants pkg_llm_retry --> pkg_llm @@ -485,20 +486,16 @@ flowchart TD pkg_session_persistence_sqlite --> pkg_invariants pkg_session_persistence_sqlite --> pkg_session pkg_session_persistence_sqlite --> pkg_session_persistence - pkg_session_query --> pkg_brand - pkg_session_query --> pkg_invariants - pkg_session_query --> pkg_llm - pkg_session_query --> pkg_session - pkg_session_query --> pkg_session_persistence - pkg_session_query --> pkg_session_title - pkg_session_title_llm --> pkg_invariants - pkg_session_title_llm --> pkg_llm - pkg_session_title_llm --> pkg_session - pkg_session_title_llm --> pkg_session_title - pkg_session_title_llm --> pkg_timeout + pkg_session_title --> pkg_brand + pkg_session_title --> pkg_invariants + pkg_session_title --> pkg_llm + pkg_session_title --> pkg_session + pkg_session_title --> pkg_session_projection pkg_commands --> pkg_agent + pkg_commands --> pkg_brand pkg_commands --> pkg_invariants pkg_commands --> pkg_scope + pkg_commands --> pkg_session pkg_user_approval --> pkg_agent pkg_user_approval --> pkg_brand pkg_user_approval --> pkg_invariants @@ -561,20 +558,17 @@ flowchart TD pkg_fs_sandbox --> pkg_invariants pkg_fs_sandbox --> pkg_sandbox pkg_fs_sandbox --> pkg_sandbox_policy - pkg_session_query_sqlite --> pkg_invariants - pkg_session_query_sqlite --> pkg_session - pkg_session_query_sqlite --> pkg_session_persistence - pkg_session_query_sqlite --> pkg_session_query - pkg_session_title_all_messages_llm --> pkg_invariants - pkg_session_title_all_messages_llm --> pkg_llm - pkg_session_title_all_messages_llm --> pkg_session - pkg_session_title_all_messages_llm --> pkg_session_title - pkg_session_title_all_messages_llm --> pkg_session_title_llm - pkg_session_title_first_message_llm --> pkg_invariants - pkg_session_title_first_message_llm --> pkg_llm - pkg_session_title_first_message_llm --> pkg_session - pkg_session_title_first_message_llm --> pkg_session_title - pkg_session_title_first_message_llm --> pkg_session_title_llm + pkg_session_query --> pkg_brand + pkg_session_query --> pkg_invariants + pkg_session_query --> pkg_llm + pkg_session_query --> pkg_session + pkg_session_query --> pkg_session_persistence + pkg_session_query --> pkg_session_title + pkg_session_title_llm --> pkg_invariants + pkg_session_title_llm --> pkg_llm + pkg_session_title_llm --> pkg_session + pkg_session_title_llm --> pkg_session_title + pkg_session_title_llm --> pkg_timeout pkg_acp --> pkg_agent pkg_acp --> pkg_invariants pkg_acp --> pkg_session @@ -585,13 +579,6 @@ flowchart TD pkg_permission --> pkg_sandbox_policy pkg_permission --> pkg_session pkg_permission --> pkg_user_approval - pkg_session_reference --> pkg_agent - pkg_session_reference --> pkg_compact - pkg_session_reference --> pkg_invariants - pkg_session_reference --> pkg_llm - pkg_session_reference --> pkg_retention - pkg_session_reference --> pkg_session - pkg_session_reference --> pkg_session_query pkg_pty_local --> pkg_agent pkg_pty_local --> pkg_invariants pkg_pty_local --> pkg_pty @@ -681,6 +668,7 @@ flowchart TD pkg_tool_todo --> pkg_agent pkg_tool_todo --> pkg_invariants pkg_tool_todo --> pkg_session + pkg_tool_todo --> pkg_session_projection pkg_tool_todo --> pkg_tools pkg_plan_mode --> pkg_agent pkg_plan_mode --> pkg_commands @@ -705,6 +693,10 @@ flowchart TD pkg_session_checkpoint_policy --> pkg_session pkg_session_checkpoint_policy --> pkg_session_persistence pkg_session_checkpoint_policy --> pkg_tools + pkg_session_query_sqlite --> pkg_invariants + pkg_session_query_sqlite --> pkg_session + pkg_session_query_sqlite --> pkg_session_persistence + pkg_session_query_sqlite --> pkg_session_query pkg_tool_session_query --> pkg_invariants pkg_tool_session_query --> pkg_llm pkg_tool_session_query --> pkg_session @@ -712,6 +704,16 @@ flowchart TD pkg_tool_session_query --> pkg_system_prompt pkg_tool_session_query --> pkg_timeout pkg_tool_session_query --> pkg_tools + pkg_session_title_all_messages_llm --> pkg_invariants + pkg_session_title_all_messages_llm --> pkg_llm + pkg_session_title_all_messages_llm --> pkg_session + pkg_session_title_all_messages_llm --> pkg_session_title + pkg_session_title_all_messages_llm --> pkg_session_title_llm + pkg_session_title_first_message_llm --> pkg_invariants + pkg_session_title_first_message_llm --> pkg_llm + pkg_session_title_first_message_llm --> pkg_session + pkg_session_title_first_message_llm --> pkg_session_title + pkg_session_title_first_message_llm --> pkg_session_title_llm pkg_agent_loop_testkit --> pkg_agent pkg_agent_loop_testkit --> pkg_invariants pkg_agent_loop_testkit --> pkg_llm @@ -722,6 +724,13 @@ flowchart TD pkg_tool_ask_user --> pkg_invariants pkg_tool_ask_user --> pkg_tools pkg_tool_ask_user --> pkg_user_interaction + pkg_session_reference --> pkg_agent + pkg_session_reference --> pkg_compact + pkg_session_reference --> pkg_invariants + pkg_session_reference --> pkg_llm + pkg_session_reference --> pkg_retention + pkg_session_reference --> pkg_session + pkg_session_reference --> pkg_session_query pkg_workspace_context --> pkg_agent pkg_workspace_context --> pkg_fs pkg_workspace_context --> pkg_invariants @@ -982,7 +991,6 @@ flowchart TD | [`web-search-perplexity`](../packages/web/web-search-perplexity) | `web` | [`invariants`](../packages/support/invariants), [`web`](../packages/web/web) | | [`spill`](../packages/spill/spill) | `spill` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`session-persistence`](../packages/session-persistence/session-persistence) | `session-persistence` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | -| [`session-title`](../packages/session-title/session-title) | `session-title` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-replay`](../packages/support/llm-replay) | `support` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`app-boot`](../packages/ui/app-boot) | `ui` | [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`system-prompt`](../packages/core/system-prompt) | | [`client-ui-model`](../packages/client/ui-model) | `client` | [`client-connection`](../packages/client/connection), [`client-runtime`](../packages/client/runtime), [`client-ui-command`](../packages/client/ui-command), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | @@ -990,6 +998,7 @@ flowchart TD | [`lsp-local`](../packages/lsp/lsp-local) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | +| [`session-projection`](../packages/session-projection/session-projection) | `session-projection` | [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | | [`llm-retry`](../packages/llm/llm-retry) | `llm` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session) | | [`bash-local`](../packages/bash/bash-local) | `bash` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | @@ -1001,9 +1010,8 @@ flowchart TD | [`hook-protocol`](../packages/hooks/hook-protocol) | `hooks` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | | [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl) | `session-persistence` | [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence) | | [`session-persistence-sqlite`](../packages/session-persistence/session-persistence-sqlite) | `session-persistence` | [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence) | -| [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title) | -| [`session-title-llm`](../packages/session-title/session-title-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`timeout`](../packages/util/timeout) | -| [`commands`](../packages/ui/commands) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`scope`](../packages/core/scope) | +| [`session-title`](../packages/session-title/session-title) | `session-title` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session-projection/session-projection) | +| [`commands`](../packages/ui/commands) | `ui` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`scope`](../packages/core/scope), [`session`](../packages/core/session) | | [`user-approval`](../packages/ui/user-approval) | `ui` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt) | | [`user-interaction`](../packages/ui/user-interaction) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | @@ -1018,12 +1026,10 @@ flowchart TD | [`goal-session`](../packages/goal/goal-session) | `goal` | [`agent`](../packages/core/agent), [`goal`](../packages/goal/goal), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`bash-sandbox`](../packages/bash/bash-sandbox) | `bash` | [`bash`](../packages/bash/bash), [`bash-local`](../packages/bash/bash-local), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | -| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-query`](../packages/session-query/session-query) | -| [`session-title-all-messages-llm`](../packages/session-title/session-title-all-messages-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`session-title-llm`](../packages/session-title/session-title-llm) | -| [`session-title-first-message-llm`](../packages/session-title/session-title-first-message-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`session-title-llm`](../packages/session-title/session-title-llm) | +| [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title) | +| [`session-title-llm`](../packages/session-title/session-title-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`timeout`](../packages/util/timeout) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`user-approval`](../packages/ui/user-approval) | | [`permission`](../packages/ui/permission) | `ui` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`user-approval`](../packages/ui/user-approval) | -| [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query) | | [`pty-local`](../packages/pty/pty-local) | `pty` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`pty`](../packages/pty/pty), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess) | | [`tasks-local`](../packages/tasks/tasks-local) | `tasks` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`tasks`](../packages/tasks/tasks), [`timeout`](../packages/util/timeout) | | [`session-telemetry-otel`](../packages/telemetry/session-telemetry-otel) | `telemetry` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-telemetry`](../packages/telemetry/session-telemetry) | @@ -1037,14 +1043,18 @@ flowchart TD | [`tool-web`](../packages/web/tool-web) | `web` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) | | [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`tools`](../packages/core/tools) | | [`timeout-policy`](../packages/timeout/timeout-policy) | `timeout` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | -| [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | +| [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`session-projection`](../packages/session-projection/session-projection), [`tools`](../packages/core/tools) | | [`plan-mode`](../packages/plan/plan-mode) | `plan` | [`agent`](../packages/core/agent), [`commands`](../packages/ui/commands), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | | [`tool-cordis`](../packages/cordis/tool-cordis) | `cordis` | [`invariants`](../packages/support/invariants), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/hooks/hooks-codex) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`tools`](../packages/core/tools) | | [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy) | `session-persistence` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`tools`](../packages/core/tools) | +| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-query`](../packages/session-query/session-query) | | [`tool-session-query`](../packages/session-query/tool-session-query) | `session-query` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | +| [`session-title-all-messages-llm`](../packages/session-title/session-title-all-messages-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`session-title-llm`](../packages/session-title/session-title-llm) | +| [`session-title-first-message-llm`](../packages/session-title/session-title-first-message-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`session-title-llm`](../packages/session-title/session-title-llm) | | [`agent-loop-testkit`](../packages/support/agent-loop-testkit) | `support` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-ask-user`](../packages/ui/tool-ask-user) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | +| [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query) | | [`workspace-context`](../packages/context/workspace-context) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | | [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | `guard` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`tools`](../packages/core/tools) | | [`tool-lsp`](../packages/lsp/tool-lsp) | `lsp` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 8b51586912..fc5aa48b59 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -168,6 +168,38 @@ Types: [ContentBlock](core-data-structures/core.md) · [TokenUsage](core-data-st Source: [`packages/core/session/src/types.ts:222`](../packages/core/session/src/types.ts) +### `command/*` + +#### `command/done` — log-only + +```ts persistence-catalog +/** + * The paired command settled. `kind`/`text` carry the handler's verbatim + * outcome (a thrown/aborted handler settles as `kind: 'error'` with the + * rendered failure); presentation stays client-computed at render time. + */ +'command/done': { commandId: CommandId; kind: 'success' | 'error'; text?: string } +``` + +Source: [`packages/ui/commands/src/index.ts:138`](../packages/ui/commands/src/index.ts) + +#### `command/run` — log-only + +```ts persistence-catalog +/** + * A resolved slash command entered its handler. Log-only (never model + * surface); paired with `command/done` by `commandId`, mirroring the + * `tool/call`↔`tool/result` pairing. The payload is structured — `name` + * and `args` are `parseCommand`'s own split (name and verbatim rawInput, + * separator whitespace included), so a consumer (a projection unit + * folding its own command records, a rich command card) never re-parses + * a line. + */ +'command/run': { commandId: CommandId; name: string; args: string; source: CommandSource } +``` + +Source: [`packages/ui/commands/src/index.ts:132`](../packages/ui/commands/src/index.ts) + ### `compact/*` #### `compact/end` — log-only @@ -373,7 +405,7 @@ Source: [`packages/sandbox/sandbox-policy/src/session-mode.ts:34`](../packages/s Types: [SessionTitleEventData](core-data-structures/session-title.md) -Source: [`packages/session-title/session-title/src/index.ts:88`](../packages/session-title/session-title/src/index.ts) +Source: [`packages/session-title/session-title/src/index.ts:96`](../packages/session-title/session-title/src/index.ts) #### `session/title-llm-request` — log-only diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 38f61cfa7e..a8feddf0e0 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/README.md -README.md: f95a774ca74dda332fd312044fad3f4fb7695dd2 -README.zh.md: 64bc5051a0938eddd6ca8523a6d19a5374737606 +README.md: 8381c0016ebf843faa5b9e61f6d425671832f0cf +README.zh.md: 1dc452e112333193b2f1c3a72cfc285872a4e2eb diff --git a/packages/README.md b/packages/README.md index f95a774ca7..8381c0016e 100644 --- a/packages/README.md +++ b/packages/README.md @@ -29,21 +29,22 @@ Packages use the `@deepseek-ai/dsh-*` scope. Each is a Cordis `Service` subclass | [`web/`](web/README.md) | Web capability family: seam, search/fetch provider impls, and the model-facing web tools | Product — stable surface | | [`attachment/`](attachment/README.md) | Durable attachments | Product — stable surface | | [`spill/`](spill/README.md) | Spill capability family: storage seam, local impl, tool-result spill policy | Product — stable surface | -| [`todo/`](todo/README.md) | Todo/planning family: the model-facing `todo_write` tool | Product — stable surface | +| [`todo/`](todo/README.md) | The model-facing `todo_write` tool | Product — stable surface | | [`plan/`](plan/README.md) | Plan collaboration state with a direct entry command and reviewed exit | Product — stable surface | | [`timeout/`](timeout/README.md) | Tool-call timeout policy: the `tools/execute` deadline enforcer | Product — stable surface | | [`guard/`](guard/README.md) | Loop-hygiene guards: advisory repeat-call reminders | Product — stable surface | | [`cordis/`](cordis/README.md) | Self-referential runtime toolset: inspect the live runtime's plugins and services, mount/unmount model-written plugins ([design](../.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md)) | Product — stable surface | | [`hooks/`](hooks/README.md) | Hook bridges + the shared Claude Code / Codex wire-protocol library | Product — stable surface | -| [`session-persistence/`](session-persistence/README.md) | Persistence capability family: the seam + JSONL/SQLite backends | Product — stable surface | +| [`session-persistence/`](session-persistence/README.md) | Persistence seam + JSONL/SQLite backends | Product — stable surface | +| [`session-projection/`](session-projection/README.md) | Projection seam: domain fold units serve whole values | Product — stable surface | | [`session-query/`](session-query/README.md) | Session retrieval family: logical corpus, bounded reads, lineage, event relationships, semantic filtering, and SQLite full-text search | Product — stable surface | -| [`session-title/`](session-title/README.md) | Log-backed session titles: fallback service, shared LLM policy, and opt-in providers | Product — stable surface | +| [`session-title/`](session-title/README.md) | Log-backed session titles: fallback service and opt-in LLM providers | Product — stable surface | | [`telemetry/`](telemetry/README.md) | Session reporting: capture/redact seam, OTel backend | Product — stable surface | | [`storage/`](storage/README.md) | Non-session storage hub + backends + domain form | Product — stable surface | | [`workspace/`](workspace/README.md) | Workspace entity | Product — stable surface | | [`sdk/`](sdk/README.md) | Project SDK tooling | Product — stable surface | | [`acp/`](acp/README.md) | Automation-only Agent Client Protocol server | Product — stable surface | -| [`ui/`](ui/README.md) | Human/client integrations: TUI and JSON-RPC, approval/interaction seams, ask-user tool | Product — stable surface | +| [`ui/`](ui/README.md) | TUI and JSON-RPC integrations, approval/interaction seams, ask-user tool | Product — stable surface | | [`examples/`](examples/README.md) | Demo bundles (agent-spine + TUI/CLI/ACP/JSON-RPC bins) leaves load | Support — example infra | | [`support/`](support/README.md) | Support infrastructure (testkits, invariants, replay, Loader smokes) | Support — lower compatibility expectations | | [`util/`](util/README.md) | Low-level zero-dependency utilities shared across groups (`Branded`, Harness home/path helpers, timeout, retention) | Support — small, stable, harness-dep-free | diff --git a/packages/README.zh.md b/packages/README.zh.md index 64bc5051a0..1dc452e112 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -29,21 +29,22 @@ | [`web/`](web/README.md) | Web 能力系列:seam、搜索/获取提供方实现和面向模型的 Web 工具 | 产品:稳定表面 | | [`attachment/`](attachment/README.md) | 持久附件 | 产品:稳定表面 | | [`spill/`](spill/README.md) | 溢出能力系列:存储 seam、本地实现、工具结果溢出策略 | 产品:稳定表面 | -| [`todo/`](todo/README.md) | Todo/规划系列:面向模型的 `todo_write` 工具 | 产品:稳定表面 | +| [`todo/`](todo/README.md) | 面向模型的 `todo_write` 工具 | 产品:稳定表面 | | [`plan/`](plan/README.md) | Plan 协作状态,提供直接进入命令与经评审的退出 | 产品:稳定表面 | | [`timeout/`](timeout/README.md) | 工具调用超时策略:`tools/execute` 截止时间强制执行器 | 产品:稳定表面 | | [`guard/`](guard/README.md) | 循环卫生守卫:建议性重复调用提醒 | 产品:稳定表面 | | [`cordis/`](cordis/README.md) | 自指运行时工具集:检查实时运行时的插件与服务,挂载/卸载模型所写插件([设计](../.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md)) | 产品:稳定表面 | | [`hooks/`](hooks/README.md) | 钩子桥接 + 共享 Claude Code/Codex 协议格式库 | 产品:稳定表面 | -| [`session-persistence/`](session-persistence/README.md) | 持久化能力系列:seam + JSONL/SQLite 后端 | 产品:稳定表面 | +| [`session-persistence/`](session-persistence/README.md) | 持久化 seam + JSONL/SQLite 后端 | 产品:稳定表面 | +| [`session-projection/`](session-projection/README.md) | 投影 seam:领域折叠单元供给全量值 | 产品:稳定表面 | | [`session-query/`](session-query/README.md) | 会话检索系列:逻辑语料库、有界读取、血缘、事件关系、语义过滤和 SQLite 全文搜索 | 产品:稳定表面 | -| [`session-title/`](session-title/README.md) | 日志支撑的会话标题:回退服务、共享 LLM 策略和选用提供方 | 产品:稳定表面 | +| [`session-title/`](session-title/README.md) | 日志支撑的会话标题:回退服务与选用 LLM 提供方 | 产品:稳定表面 | | [`telemetry/`](telemetry/README.md) | 会话上报:捕获/脱敏 seam、OTel 后端 | 产品:稳定表面 | | [`storage/`](storage/README.md) | 非会话存储中枢 + 后端 + 领域形式 | 产品:稳定表面 | | [`workspace/`](workspace/README.md) | Workspace 实体 | 产品:稳定表面 | | [`sdk/`](sdk/README.md) | 项目 SDK 工具 | 产品:稳定表面 | | [`acp/`](acp/README.md) | 仅面向自动化的 Agent Client Protocol 服务器 | 产品:稳定表面 | -| [`ui/`](ui/README.md) | 人类/客户端集成:TUI 与 JSON-RPC、批准/交互 seam、用户问答工具 | 产品:稳定表面 | +| [`ui/`](ui/README.md) | TUI 与 JSON-RPC 集成、批准/交互 seam、用户问答工具 | 产品:稳定表面 | | [`examples/`](examples/README.md) | 演示组合包(agent-spine + TUI/CLI/ACP/JSON-RPC bin),由叶节点加载 | 支持:示例基础设施 | | [`support/`](support/README.md) | 支持基础设施(testkit、不变式、回放、Loader 冒烟测试) | 支持:兼容性预期较低 | | [`util/`](util/README.md) | 组间共享的低层零依赖工具(`Branded`、Harness home/路径辅助函数、超时、保留策略) | 支持:小型、稳定、无 harness 依赖 | diff --git a/packages/client/connection/package.json b/packages/client/connection/package.json index 9f67953b0e..25d1839a6e 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -31,6 +31,7 @@ "dependencies": { "@deepseek-ai/dsh-attachment": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", + "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^" diff --git a/packages/client/connection/src/client/api.ts b/packages/client/connection/src/client/api.ts index 0bac9f0bed..7c99c09b60 100644 --- a/packages/client/connection/src/client/api.ts +++ b/packages/client/connection/src/client/api.ts @@ -9,7 +9,7 @@ export type { ApiProxy, SessionsApi, SessionSummary, PromptContentPart, HostApi, EventsApi, MuxFrame, HostFrame, ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, ResponseValue, WorkspaceApi, WorkspaceId, WorkspaceView, - CommandsApi, CommandDescriptor, CommandExecuteResult, SkillsApi, SkillEntry, + CommandsApi, CommandDescriptor, SkillsApi, SkillEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, ModelReasoningEffort, ModelTarget, SessionModels, } from '@deepseek-ai/dsh-host-apiproxy/api' diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 17cacd9dc8..b6c0f5f6b9 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -8,6 +8,9 @@ import type { ContentBlock } from '@deepseek-ai/dsh-llm/types' import type { AttachmentIdType, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { SessionEvent, SessionId, TodoItem } from '@deepseek-ai/dsh-session/types' +// Type-only: the brand constructor is host-side; the fixture casts at its +// wire-fabrication boundary (the schema layer's one-cast-point posture). +import type { CommandId } from '@deepseek-ai/dsh-commands/brand' import type { ApiProxy, ClientRequest, ClientResponse, HistoryEntry, HostFrame, MuxFrame, RpcReceipt, ModelTarget, RpcRequest, RpcResponse, RpcResult, ServerRequest, ServerResponse, SessionSummary, @@ -304,18 +307,27 @@ function viewFor(event: SessionEvent, log: readonly SessionEvent[]): ToolEventVi return undefined } -/** Fold the latest fixture title into the host's control-frame projection. */ -function titleFrameOf(id: SessionId, log: readonly SessionEvent[]): Extract | undefined { - const event = log.findLast(item => (item as { type: string }).type === 'session/title') - if (event === undefined) return undefined - const titleEvent = event as unknown as { seq: number; time: number; data: { title: string } } - return { - type: 'session/title', - sessionId: id, - title: titleEvent.data.title, - eventSeq: titleEvent.seq, - updatedAt: titleEvent.time, +/** Fixture parallel of the host's projection units: whole current values per key over the full log. */ +function projectionValuesOf(log: readonly SessionEvent[]): Record { + const values: Record = {} + const titleEvent = log.findLast(item => (item as { type: string }).type === 'session/title') + if (titleEvent !== undefined) { + values['title'] = (titleEvent as unknown as { data: { title: string } }).data.title } + const todos = backscanTodos(log) + if (todos !== undefined) values['todos'] = todos + return values +} + +/** Host push-frame parallel: emit one session/projection frame per key the given event advanced. */ +function projectionFramesOf(id: SessionId, log: readonly SessionEvent[], event: SessionEvent): Extract[] { + const type = (event as { type: string }).type + const key = type === 'session/title' ? 'title' : type === 'todo/write' ? 'todos' : undefined + if (key === undefined) return [] + const values = projectionValuesOf(log) + /* v8 ignore next -- the advancing event is in the log, so its key always has a value. */ + if (!Object.hasOwn(values, key)) return [] + return [{ type: 'session/projection', sessionId: id, key, value: values[key], seq: event.seq }] } /** @@ -561,10 +573,8 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { emitMux(view === undefined ? { type: 'session/event', sessionId: id, event } : { type: 'session/event', sessionId: id, event, view }) - if ((event as { type: string }).type === 'session/title') { - // The raw title is already in this log, so the latest-title fold must find it. - emitMux(titleFrameOf(id, log) as Extract) - } + // Host eager-drive parallel: a unit-advancing event pushes its finished value. + for (const frame of projectionFramesOf(id, log, event)) emitMux(frame) } /** At most one in-flight replay per session; cancel clears it. */ @@ -717,14 +727,18 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { const log = logs.get(request.payload.sessionId) ?? [] // Snapshot at request time, deliver after the transit delay (mirrors a real host under latency). const page = pageOf(log, request.payload.beforeSeq, request.payload.maxMessages ?? 50) - // Tail page carries the session-level todo projection (host parallel: full-log backscan). - const todos = request.payload.beforeSeq === undefined ? backscanTodos(log) : undefined + // Tail page carries the projections block (host parallel: one consistent + // cut over the registered units; asOfSeq = window tail seq, -1 on an + // empty log — the host's session.seq-1 convention). + const projections = request.payload.beforeSeq === undefined + ? { asOfSeq: log.length - 1, values: projectionValuesOf(log) } + : undefined const doomed = failNextHistory failNextHistory = false const delay = historyDelayMs if (delay > 0) await new Promise(resolve => setTimeout(resolve, delay)) if (doomed) throw new Error('fixture: simulated history transport failure') - return ok(request, { ...page, ...todos === undefined ? {} : { todos } }) + return ok(request, { ...page, ...projections === undefined ? {} : { projections } }) }, models: request => ok(request, { current: modelTargets.get(request.payload.sessionId) @@ -894,6 +908,7 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { attachedSessions, }), pickDirectory: request => ok(request, { path: null }), + openPath: request => ok(request, { opened: true as const }), }, workspace: { list: request => ok(request, { items: workspaces.map(w => ({ ...w })) }), @@ -997,25 +1012,29 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { ], }) }, + // Pure admission, mirroring the host: an admitted command logs the + // command/run + command/done lifecycle pair (mux-broadcast by append), + // and the response only reports resolution. execute: (request) => { const missing = requireSession(request) if (missing !== undefined) return missing - const line = request.payload.line.trim() - const match = /^\/(\S+)(?:\s+(.*))?$/.exec(line) + const id = request.payload.sessionId + // Structured split mirroring the host parser: name + verbatim rawInput + // (separator whitespace included) — the run payload carries no line. + const match = /^\/(\S+)((?:\s.*)?)$/.exec(request.payload.line.trim()) const name = match?.[1] - if (name === 'compact' || name === 'echo') { - return ok(request, { - matched: true as const, - result: { kind: 'success' as const, text: name === 'echo' ? (match?.[2] ?? '') : 'fixture:已压缩(假动作)' }, - }) + const args = match?.[2] ?? '' + const outcomes: Record = { + compact: 'fixture:已压缩(假动作)', + echo: args.trim(), + 'goal-fixture': `fixture:goal 已设置(${id})`, } - if (name === 'goal-fixture') { - return ok(request, { - matched: true as const, - result: { kind: 'success' as const, text: `fixture:goal 已设置(${request.payload.sessionId})` }, - }) - } - return ok(request, { matched: false as const }) + const text = name === undefined ? undefined : outcomes[name] + if (name === undefined || text === undefined) return ok(request, { matched: false as const }) + const commandId = `fx-cmd-${logOf(id).length}` as CommandId + append(id, { type: 'command/run', data: { commandId, name, args, source: { kind: 'user' } } }) + append(id, { type: 'command/done', data: { commandId, kind: 'success', ...text === '' ? {} : { text } } }) + return ok(request, { matched: true as const, commandId }) }, }, skills: { @@ -1038,9 +1057,13 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { // Open baseline: subscribed sessions + pending interactions replayed with stable rpcIds. for (const s of sessions) { if (!s.running) continue - conn.push({ rpcId: mint(), payload: { type: 'session/subscribed', sessionId: s.sessionId, lastSeq: (logs.get(s.sessionId)?.length ?? 0) - 1 } }) - const title = titleFrameOf(s.sessionId, logs.get(s.sessionId) ?? []) - if (title !== undefined) conn.push({ rpcId: mint(), payload: title }) + const log = logs.get(s.sessionId) ?? [] + conn.push({ rpcId: mint(), payload: { type: 'session/subscribed', sessionId: s.sessionId, lastSeq: log.length - 1 } }) + // Post-subscribe projection baseline (host parallel: recomputed unit values ride push frames). + const values = projectionValuesOf(log) + for (const key of Object.keys(values)) { + conn.push({ rpcId: mint(), payload: { type: 'session/projection', sessionId: s.sessionId, key, value: values[key], seq: log.length - 1 } }) + } } conn.push({ rpcId: pendingApprovalRpcId, @@ -1146,6 +1169,7 @@ export class FixtureApiClient extends AbstractApiClient { case 'session.cancel': return this.api.sessions.cancel(request) case 'host.describe': return this.api.host.describe(request) case 'host.pickDirectory': return this.api.host.pickDirectory(request, new AbortController().signal) + case 'host.openPath': return this.api.host.openPath(request, new AbortController().signal) case 'workspace.list': return this.api.workspace.list(request) case 'workspace.create': return this.api.workspace.create(request) case 'workspace.rename': return this.api.workspace.rename(request) diff --git a/packages/client/connection/src/client/index.ts b/packages/client/connection/src/client/index.ts index 644949ff9f..45bd20f12f 100644 --- a/packages/client/connection/src/client/index.ts +++ b/packages/client/connection/src/client/index.ts @@ -14,7 +14,7 @@ export type { ApiProxy, SessionsApi, SessionSummary, PromptContentPart, HostApi, EventsApi, MuxFrame, HostFrame, ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, ToolCallView, ToolResultView, WorkspaceApi, WorkspaceId, WorkspaceView, - CommandsApi, CommandDescriptor, CommandExecuteResult, SkillsApi, SkillEntry, + CommandsApi, CommandDescriptor, SkillsApi, SkillEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, ModelReasoningEffort, ModelTarget, SessionModels, RpcRequest, RpcResponse, RpcResult, RpcError, RpcErrorCode, diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index 28ef97843e..6ed27ee278 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -33,7 +33,8 @@ export function apply(ctx: Context): void { path: API_PATH, handler: async (req, res) => { const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname - if (pathname === `${API_PATH}/host.pickDirectory` + if ((pathname === `${API_PATH}/host.pickDirectory` + || pathname === `${API_PATH}/host.openPath`) && !isTrustedNativeDialogRequest(req)) { res.writeHead(403) res.end('forbidden') diff --git a/packages/client/connection/src/native-dialog-request.ts b/packages/client/connection/src/native-dialog-request.ts index fe91bbae2d..0eaf09f149 100644 --- a/packages/client/connection/src/native-dialog-request.ts +++ b/packages/client/connection/src/native-dialog-request.ts @@ -1,4 +1,4 @@ -/** Trust check for browser requests that can open an operating-system dialog. */ +/** Trust check for browser requests that can invoke privileged native host actions. */ import type { IncomingHttpHeaders } from 'node:http' diff --git a/packages/client/connection/tests/fake-api.ts b/packages/client/connection/tests/fake-api.ts index bcd5240917..bf6b87e913 100644 --- a/packages/client/connection/tests/fake-api.ts +++ b/packages/client/connection/tests/fake-api.ts @@ -1,8 +1,9 @@ // Test-local programmable IApiClient fake (NOT the fixture: fixture is a demo // data source on a real clock; behavior tests need per-case responses and // deferred-controlled timing). Streams are hand pumps: pushMux/pushHost. +import type { CommandId } from '@deepseek-ai/dsh-commands/brand' import type { - CommandDescriptor, CommandExecuteResult, HostFrame, IApiClient, ModelTarget, MuxFrame, + CommandDescriptor, HostFrame, IApiClient, ModelTarget, MuxFrame, RpcRequest, RpcResponse, SessionId, SessionModels, SkillEntry, } from '../src/client/api.ts' import { RpcId } from '../src/client/api.ts' @@ -68,6 +69,8 @@ export class FakeApiClient implements IApiClient { () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) onPickDirectory: (payload: unknown) => Promise> = () => Promise.resolve(ok({ path: null })) + onOpenPath: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ opened: true as const })) private readonly muxConns: StreamConn[] = [] private readonly hostConns: StreamConn[] = [] @@ -91,6 +94,7 @@ export class FakeApiClient implements IApiClient { readonly host: IApiClient['host'] = { describe: payload => this.record('host.describe', payload, this.onDescribe(payload)), pickDirectory: payload => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)), + openPath: payload => this.record('host.openPath', payload, this.onOpenPath(payload)), } readonly workspace: IApiClient['workspace'] = { @@ -110,10 +114,12 @@ export class FakeApiClient implements IApiClient { // Payloads stay `unknown` (lint-lane note above); response rows are the real // wire shapes so cases can program catalogs and skill lists without casts. - onCommandList: (payload: unknown) => Promise> = () => Promise.resolve(ok({ commands: [] })) - onCommandExecute: (payload: unknown) => Promise> = - () => Promise.resolve(ok({ matched: false })) - onSkillList: (payload: unknown) => Promise> = () => Promise.resolve(ok({ skills: [] })) + onCommandList: (payload: unknown) => Promise> + = () => Promise.resolve(ok({ commands: [] })) + onCommandExecute: (payload: unknown) => Promise> + = () => Promise.resolve(ok({ matched: false })) + onSkillList: (payload: unknown) => Promise> + = () => Promise.resolve(ok({ skills: [] })) readonly commands: IApiClient['commands'] = { list: (payload: unknown) => this.record('command.list', payload, this.onCommandList(payload)), diff --git a/packages/client/connection/tests/fixture-commands.spec.ts b/packages/client/connection/tests/fixture-commands.spec.ts index d3c62e736b..bd66d124a4 100644 --- a/packages/client/connection/tests/fixture-commands.spec.ts +++ b/packages/client/connection/tests/fixture-commands.spec.ts @@ -36,20 +36,37 @@ describe('createFixtureApi commands/skills', () => { expect(response.result).toMatchObject({ ok: false, error: { code: 'session-not-found' } }) }) - it('executes a known command line and reports matched with a result', async () => { + it('executes a known command line: pure admission plus a mux-broadcast lifecycle pair', async () => { const api = createFixtureApi() + const frames: unknown[] = [] + const abort = new AbortController() + const stream = api.events.mux(req({}), abort.signal) + const pump = (async () => { + for await (const frame of stream) { + frames.push(frame.payload) + if (frames.filter(f => (f as { type: string }).type === 'session/event').length >= 2) abort.abort() + } + })() const response = await api.commands.execute(req({ sessionId: sid('fx-alpha'), line: '/echo hello world' }), signal) if (!response.result.ok) throw new Error('execute failed') - expect(response.result.value.matched).toBe(true) - expect(response.result.value.result).toEqual({ kind: 'success', text: 'hello world' }) + expect(response.result.value).toMatchObject({ matched: true }) + expect(response.result.value.commandId).toBeTruthy() + await pump + const events = frames + .filter((f): f is { type: string; event: { type: string; data: Record } } => (f as { type: string }).type === 'session/event') + .map(f => f.event) + expect(events).toMatchObject([ + { type: 'command/run', data: { name: 'echo', args: ' hello world', source: { kind: 'user' } } }, + { type: 'command/done', data: { kind: 'success', text: 'hello world' } }, + ]) + expect(events[0]?.data.commandId).toBe(events[1]?.data.commandId) }) - it('addresses execute to the session (result text carries the id)', async () => { + it('addresses execute to the session; an unknown session errs', async () => { const api = createFixtureApi() const hit = await api.commands.execute(req({ sessionId: sid('fx-alpha'), line: '/goal-fixture ship' }), signal) if (!hit.result.ok) throw new Error('execute failed') expect(hit.result.value.matched).toBe(true) - expect(hit.result.value.result?.text).toContain('fx-alpha') const missing = await api.commands.execute(req({ sessionId: sid('fx-nope'), line: '/goal-fixture ship' }), signal) expect(missing.result).toMatchObject({ ok: false, error: { code: 'session-not-found' } }) @@ -60,8 +77,8 @@ describe('createFixtureApi commands/skills', () => { for (const line of ['/nope', 'plain text', '/']) { const response = await api.commands.execute(req({ sessionId: sid('fx-alpha'), line }), signal) if (!response.result.ok) throw new Error('execute failed') - expect(response.result.value.matched).toBe(false) - expect(response.result.value.result).toBeUndefined() + // Pure admission value: the matched bit is the whole response shape. + expect(response.result.value).toEqual({ matched: false }) } }) diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 0e5f241266..f91fd0be0e 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -65,13 +65,11 @@ describe('createFixtureApi', () => { const clamped = await api.sessions.history(req({ sessionId: sid('fx-alpha'), beforeSeq: -5, maxMessages: 10 })) if (!clamped.result.ok) throw new Error('clamped failed') expect(clamped.result.value.events).toEqual([]) - // Unknown session: empty page, not an error (history of a bare id). + // Unknown session: empty page, not an error (history of a bare id). The + // tail block still rides it — empty-log cut at -1, the host convention. const empty = await api.sessions.history(req({ sessionId: sid('no-such'), maxMessages: 10 })) if (!empty.result.ok) throw new Error('empty failed') - expect(empty.result.value).toEqual({ - events: [], - hasMore: false, - }) + expect(empty.result.value).toEqual({ events: [], hasMore: false, projections: { asOfSeq: -1, values: {} } }) }) it('serves grouped models and keeps a selected target for later history and fixture requests', async () => { @@ -213,11 +211,13 @@ describe('createFixtureApi', () => { const second = await openOnce() expect(first[0]?.payload).toMatchObject({ type: 'session/subscribed', sessionId: 'fx-alpha' }) expect((first[0]?.payload as { lastSeq: number }).lastSeq).toBeGreaterThan(0) - expect(first[1]?.payload).toMatchObject({ type: 'session/title', sessionId: 'fx-alpha', title: 'Fixture 历史会话' }) - expect(first[2]?.payload).toMatchObject({ type: 'approval/requested', toolName: 'dangerous_tool' }) - expect(second[2]?.rpcId).toBe(first[2]?.rpcId) // stable rpcId across replays (host replay semantics) - expect(first[3]?.payload).toMatchObject({ type: 'question/requested', sessionId: 'fx-alpha' }) - expect(second[3]?.rpcId).toBe(first[3]?.rpcId) + // Projection baseline frames follow the subscribed frame (title + todos units). + expect(first[1]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'title', value: 'Fixture 历史会话' }) + expect(first[2]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'todos' }) + expect(first[3]?.payload).toMatchObject({ type: 'approval/requested', toolName: 'dangerous_tool' }) + expect(second[3]?.rpcId).toBe(first[3]?.rpcId) // stable rpcId across replays (host replay semantics) + expect(first[4]?.payload).toMatchObject({ type: 'question/requested', sessionId: 'fx-alpha' }) + expect(second[4]?.rpcId).toBe(first[4]?.rpcId) }) it('steer with no replay in flight promotes image bytes to a session-scoped reference', async () => { @@ -666,11 +666,11 @@ describe('createFixtureApi', () => { hooks.appendTitle('fx-alpha', 'Fixture 修订标题') await vi.waitFor(() => { expect(seen.some(f => f.type === 'session/event' && JSON.stringify(f.event.data).includes('正常直播'))).toBe(true) - expect(seen.some(f => f.type === 'session/title' && f.title === 'Fixture 修订标题')).toBe(true) + expect(seen.some(f => f.type === 'session/projection' && f.key === 'title' && f.value === 'Fixture 修订标题')).toBe(true) }) expect(seen.some(f => f.type === 'session/event' && JSON.stringify(f.event.data).includes('静默丢帧'))).toBe(false) const rawTitleIndex = seen.findIndex(f => f.type === 'session/event' && (f.event as { type: string }).type === 'session/title') - const titleControlIndex = seen.findIndex(f => f.type === 'session/title' && f.title === 'Fixture 修订标题') + const titleControlIndex = seen.findIndex(f => f.type === 'session/projection' && f.key === 'title' && f.value === 'Fixture 修订标题') expect(titleControlIndex).toBe(rawTitleIndex + 1) // But history serves the silent event (the client's repull finds it). const repull = await api.sessions.history(req({ sessionId: sid('fx-alpha'), maxMessages: 5 })) diff --git a/packages/client/connection/tests/node-half.spec.ts b/packages/client/connection/tests/node-half.spec.ts index aca2cc5398..6cde462f47 100644 --- a/packages/client/connection/tests/node-half.spec.ts +++ b/packages/client/connection/tests/node-half.spec.ts @@ -32,22 +32,24 @@ describe('connection node half', () => { expect(routes).toHaveLength(1) expect(routes[0]).toMatchObject({ kind: 'prefix', path: API_PATH }) - let status: number | undefined - let body: unknown - const deniedRequest = { - url: '/api/host.pickDirectory', - headers: { - host: 'harness.example', origin: 'http://harness.example', 'sec-fetch-site': 'same-origin', - }, - socket: { remoteAddress: '192.168.1.8' }, - } as unknown as IncomingMessage - const deniedResponse = { - writeHead(value: number) { status = value; return this }, - end(value?: unknown) { body = value; return this }, - } as unknown as ServerResponse - await routes[0]!.handler(deniedRequest, deniedResponse) - expect(status).toBe(403) - expect(body).toBe('forbidden') + for (const url of ['/api/host.pickDirectory', '/api/host.openPath']) { + let status: number | undefined + let body: unknown + const deniedRequest = { + url, + headers: { + host: 'harness.example', origin: 'http://harness.example', 'sec-fetch-site': 'same-origin', + }, + socket: { remoteAddress: '192.168.1.8' }, + } as unknown as IncomingMessage + const deniedResponse = { + writeHead(value: number) { status = value; return this }, + end(value?: unknown) { body = value; return this }, + } as unknown as ServerResponse + await routes[0]!.handler(deniedRequest, deniedResponse) + expect(status).toBe(403) + expect(body).toBe('forbidden') + } await fiber.dispose() expect(routes).toHaveLength(0) diff --git a/packages/client/connection/tsconfig.json b/packages/client/connection/tsconfig.json index 603a63a142..d484ed9ece 100644 --- a/packages/client/connection/tsconfig.json +++ b/packages/client/connection/tsconfig.json @@ -18,6 +18,9 @@ { "path": "../../core/session" }, + { + "path": "../../ui/commands" + }, { "path": "../../util/brand" }, diff --git a/packages/client/runtime/package.json b/packages/client/runtime/package.json index c9698f103b..3e927377c5 100644 --- a/packages/client/runtime/package.json +++ b/packages/client/runtime/package.json @@ -33,10 +33,13 @@ "dependencies": { "@deepseek-ai/dsh-attachment": "workspace:^", "@deepseek-ai/dsh-client-connection": "workspace:^", + "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", "immer": "^10.1.1", "react": "^18.2.0", "zustand": "~4.4.7" diff --git a/packages/client/runtime/src/client/index.ts b/packages/client/runtime/src/client/index.ts index 0348fc5f98..e1cbc09b49 100644 --- a/packages/client/runtime/src/client/index.ts +++ b/packages/client/runtime/src/client/index.ts @@ -7,6 +7,7 @@ import { SessionsService } from './sessions/service.ts' import type { SessionListState } from './sessions/service.ts' import { WorkspacesService } from './workspaces/service.ts' import type { ConversationSnapshot, RunningToolCall, ToolResultNode } from './sessions/conversation.ts' +import type { UseProjection } from './sessions/projection-store.ts' export { SlotsService } from './slots.ts' export type { RootOwnerProps } from './slots.ts' @@ -28,12 +29,17 @@ export type { EngineStoreHandle, EngineStoreInstance, ObservableSnapshot, SnapshotStore, } from './contract/store.ts' export type { - AssistantBlock, AssistantMessageNode, CodeSubCall, ComposerPhase, ContextMessageNode, ConversationNode, + AssistantBlock, AssistantMessageNode, CodeSubCall, CommandNode, ComposerPhase, ContextMessageNode, ConversationNode, ConversationSnapshot, QueuedMessage, RunningToolCall, SteeringMessageNode, TodoItem, ToolResultNode, UnknownSurfaceNode, UserMessageNode, } from './sessions/conversation.ts' export { PendingWait } from './sessions/pending.ts' export type { PendingInteraction, PendingKind, PendingPayloads } from './sessions/pending.ts' +// Projection value store (session-projection RFC, push model): host-computed +// whole values per key; domains ship projection support with zero client code. +export type { + ProjectionsBaseline, ProjectionValueStore, SessionProjectionMap, UseProjection, +} from './sessions/projection-store.ts' export type { SessionId } from '@deepseek-ai/dsh-client-connection/client' /** Client-side Cordis context after declaration merging. */ @@ -59,12 +65,16 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { useSession: SnapshotSelectorHook /** The framework-resolved session id (owners never pass it). */ sessionId: SessionId + /** The fifth framework hook seat: key-addressed projection reader (undefined = capability absent). */ + useProjection: UseProjection } /** Standard kit for slots that remain mounted while current session changes. */ interface SessionMaybeStandardProps { useSession: MaybeSnapshotSelectorHook /** Current session id; absent in the no-session state. */ sessionId: SessionId | undefined + /** Key-addressed projection reader; every key reads absent while no session is current. */ + useProjection: UseProjection } /** Props injected into every global slot component. */ interface GlobalStandardProps { diff --git a/packages/client/runtime/src/client/sessions/conversation.ts b/packages/client/runtime/src/client/sessions/conversation.ts index e98eaa72da..832ad2f649 100644 --- a/packages/client/runtime/src/client/sessions/conversation.ts +++ b/packages/client/runtime/src/client/sessions/conversation.ts @@ -3,6 +3,7 @@ // substructures keep their references (the React.memo premise). callId/approvalId stay plain // string here (narrow to real brands when convenient). +import type { CommandId } from '@deepseek-ai/dsh-commands/brand' import type { ContentBlock } from '@deepseek-ai/dsh-llm/types' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { TodoItem } from '@deepseek-ai/dsh-session/types' @@ -127,6 +128,31 @@ export interface UnknownSurfaceNode { data: unknown } +/** + * One slash-command lifecycle folded from the log-only `command/run` / + * `command/done` pair (paired by commandId, mirroring tool call↔result). + * Log-only events never enter the surface fold, so the FoldAdapter indexes + * them separately and merges the nodes into the flow by seq. A window cut + * between the pair soft-falls like tool pairs: a done with no in-window run + * still builds a node (name/args null), and a run with no done renders as + * still executing. + */ +export interface CommandNode { + kind: 'command' + /** Seq of the command/run event; the done event's seq when only the done is in-window. */ + seq: number + /** Unix epoch ms of the anchoring event. */ + time: number + /** Pairing id minted by the host executor. */ + commandId: CommandId + /** Command name (run payload's structured field); null when the run fell outside the window. */ + name: string | null + /** Verbatim rawInput after the name, separator whitespace included (run payload); null when the run fell outside the window. */ + args: string | null + /** Settlement outcome (done payload); null while the command is still executing. */ + outcome: { kind: 'success' | 'error'; text?: string } | null +} + /** Finalized conversation node union (kind discriminates; seq is the React key). */ export type ConversationNode = | UserMessageNode @@ -134,6 +160,7 @@ export type ConversationNode = | SteeringMessageNode | ContextMessageNode | ToolResultNode + | CommandNode | UnknownSurfaceNode /** @@ -250,7 +277,4 @@ export interface ConversationSnapshot { */ blank: boolean lastAgentError: string | null - /** Current whole-list `todo/write` projection — the tail page's full-log value, then each live - * write (last write wins); empty = the log holds no plan. */ - todos: readonly TodoItem[] } diff --git a/packages/client/runtime/src/client/sessions/fold-adapter.ts b/packages/client/runtime/src/client/sessions/fold-adapter.ts index d72c1af8e3..874d6b0d88 100644 --- a/packages/client/runtime/src/client/sessions/fold-adapter.ts +++ b/packages/client/runtime/src/client/sessions/fold-adapter.ts @@ -8,8 +8,9 @@ import type { SessionEvent } from '@deepseek-ai/dsh-session/types' // go through it — the package root points at lib/index.js (needs a build) which the vite // browser bundle cannot resolve; surface.ts has no Node dependencies. import { SurfaceManager, isSurfaceEligibleType } from '@deepseek-ai/dsh-session/surface' +import type { CommandId } from '@deepseek-ai/dsh-commands/brand' import type { ToolCallView, ToolEventView, ToolResultView } from '@deepseek-ai/dsh-client-connection/client' -import type { ConversationNode } from './conversation.ts' +import type { CommandNode, ConversationNode } from './conversation.ts' import { toAssistantBlocks } from './conversation.ts' /** In-window tool/call index entry (result-card backfill + runningCalls material). */ @@ -99,6 +100,15 @@ export class FoldAdapter { private callIdx = new Map() /** Wire result views keyed by the tool/result event's seq (views ride the envelope, not the event). */ private resultViews = new Map() + /** + * Command lifecycle nodes by commandId (insertion = run order). The + * `command/run`/`command/done` pair is log-only, so the surface fold never + * emits it; this index folds the pair (done settles its run's node in + * place) and nodes() merges the products into the flow by seq. Window cuts + * soft-fall like tool pairs: a done with no in-window run still builds a + * node. + */ + private commandIdx = new Map() /** Window revision (bumped on reset/append) keying the nodes() result cache: an unchanged * window returns the previous ARRAY reference, not just cached elements — the snapshot's * reference-stability contract (§A.9.4) starts here. */ @@ -128,10 +138,14 @@ export class FoldAdapter { this.degraded = false this.callIdx = new Map() this.resultViews.clear() + this.commandIdx = new Map() for (let i = 0; i < events.length; i++) { const event = events[i] /* v8 ignore next -- dense-array guard: i stays within events.length, so the undefined arm needs a sparse array no caller builds. */ - if (event !== undefined) this.indexCall(event, views?.[i]) + if (event !== undefined) { + this.indexCall(event, views?.[i]) + this.indexCommand(event) + } } } @@ -145,6 +159,7 @@ export class FoldAdapter { this.rev++ this.padded.push(event) this.indexCall(event, view) + this.indexCommand(event) } /** @@ -180,7 +195,23 @@ export class FoldAdapter { this.nodeCache.set(seq, node) out.push(node) } - const value = { nodes: out, degraded: this.degraded } + // Command nodes fold outside the surface (log-only events); merge by seq. + // Both inputs are seq-ascending (surface order and run-index insertion + // order share the log order), so one linear merge keeps flow order. + let nodes = out + if (this.commandIdx.size > 0) { + nodes = [] + const commands = [...this.commandIdx.values()] + let next = 0 + for (const node of out) { + for (let cmd = commands[next]; cmd !== undefined && cmd.seq < node.seq; cmd = commands[++next]) { + nodes.push(cmd) + } + nodes.push(node) + } + for (let cmd = commands[next]; cmd !== undefined; cmd = commands[++next]) nodes.push(cmd) + } + const value = { nodes, degraded: this.degraded } this.nodesResult = { rev: this.rev, value } return value } @@ -195,6 +226,36 @@ export class FoldAdapter { return seqs } + /** Fold one command lifecycle event into its node (run mints, done settles in place; done-only soft-falls). */ + private indexCommand(event: SessionEvent): void { + // Log-only plugin events: the host-side dsh-commands declaration cannot + // enter the client program, so this wire consumer narrows structurally + // (the same posture as tool/code-dispatch in session.ts). + if ((event.type as string) === 'command/run') { + const data = event.data as unknown as { commandId: CommandId; name: string; args: string } + this.commandIdx.set(data.commandId, { + kind: 'command', seq: event.seq, time: event.time, + commandId: data.commandId, name: data.name, args: data.args, outcome: null, + }) + return + } + if ((event.type as string) !== 'command/done') return + const data = event.data as unknown as { commandId: CommandId; kind: 'success' | 'error'; text?: string } + const run = this.commandIdx.get(data.commandId) + const outcome = { kind: data.kind, ...data.text === undefined ? {} : { text: data.text } } + if (run === undefined) { + // Cross-window cut: the run page fell out of the window — build the + // node from the done alone (same soft-fall as a call-less tool result). + this.commandIdx.set(data.commandId, { + kind: 'command', seq: event.seq, time: event.time, + commandId: data.commandId, name: null, args: null, outcome, + }) + return + } + // Settle in place: a fresh node object (published references stay immutable). + this.commandIdx.set(data.commandId, { ...run, outcome }) + } + private indexCall(event: SessionEvent, view?: ToolEventView): void { if (event.type === 'tool/result') { if (view?.for === 'result') this.resultViews.set(event.seq, view.view) diff --git a/packages/client/runtime/src/client/sessions/manager.ts b/packages/client/runtime/src/client/sessions/manager.ts index 694768ebbc..66a0d00dd9 100644 --- a/packages/client/runtime/src/client/sessions/manager.ts +++ b/packages/client/runtime/src/client/sessions/manager.ts @@ -9,7 +9,12 @@ import { transportError } from '@deepseek-ai/dsh-host-apiproxy/api' import { mergeOrderedBaseline } from '../ordered-baseline.ts' import type { SessionListEntry, TitledSessionSummary } from './lineage.ts' import { flattenLineage } from './lineage.ts' +// Type-only merge edge: the title domain's client-namespace outlet declares +// the 'title' projection key this manager projects into list rows (and any +// useProjection('title') consumer reads). Zero value imports by construction. +import type {} from '@deepseek-ai/dsh-session-title/client' import { Notifier } from './notifier.ts' +import { ProjectionValueStore } from './projection-store.ts' import { Session } from './session.ts' /** @@ -43,12 +48,6 @@ type SessionListMutation = /** Per-session cap for pre-instantiation approval/question buffering (low-frequency frames; a few dozen covers any real backlog). */ const PENDING_BUFFER_CAP = 32 -/** Latest title control snapshot retained independently of list/instance arrival. */ -interface SessionTitleSnapshot { - title: string - eventSeq: number - updatedAt: number -} /** Instance cluster + frame entry + the session list (see the web client architecture RFC). */ export class SessionManager { @@ -58,7 +57,11 @@ export class SessionManager { * drop-and-backfill path; replayed and cleared on instantiation. Bounded per session (these * frames are low-frequency; overflow drops oldest) and dropped on session-removed (audit S7). */ private readonly pendingBuffers = new Map[]>() - private readonly titleSnapshots = new Map() + /** Per-session projection value stores, retained independently of instance arrival (the + * title-snapshot precedent, generalized): push frames land here whether or not the Session + * is instantiated (list rows read the 'title' key), and an instantiated Session adopts the + * same store so history-baseline seeding and frames converge on one row set. */ + private readonly projectionStores = new Map() private summaries: SessionSummary[] = [] private listState: 'idle' | 'loading' | 'error' = 'idle' /** Arrival phase; the pending → ready edge fires on the first successful pull (see SessionListPhase). */ @@ -163,9 +166,23 @@ export class SessionManager { onEngaged: (engaged) => { this.recordMutation({ kind: 'engaged', sessionId: engaged.sessionId }) }, + projections: this.projectionStore(sessionId), }) } + /** Resident per-session projection store (create-on-demand; outlives instantiation). */ + private projectionStore(sessionId: SessionId): ProjectionValueStore { + let store = this.projectionStores.get(sessionId) + if (store === undefined) { + store = new ProjectionValueStore() + // List rows project off store keys (title); any-key changes re-enter + // the manager's own batched rebuild channel. + store.subscribeAny(() => { this.notifier.markDirty() }) + this.projectionStores.set(sessionId, store) + } + return store + } + // ---- List surface ---- /** Full refresh via session.list (single-flight: an in-flight call is reused). */ @@ -302,23 +319,20 @@ export class SessionManager { handleMuxEnvelope(envelope: RpcRequest): void { const frame = envelope.payload if (frame.type === 'stream/error') return // Controller already treats this as stream failure - if (frame.type === 'session/title') { - const current = this.titleSnapshots.get(frame.sessionId) - if (current !== undefined && current.eventSeq >= frame.eventSeq) return - this.titleSnapshots.set(frame.sessionId, { - title: frame.title, - eventSeq: frame.eventSeq, - updatedAt: frame.updatedAt, - }) + if (frame.type === 'session/projection') { + // Finished host-computed value: land it in the resident store whether or + // not the Session is instantiated (list rows read the 'title' key). The + // synchronous markDirty keeps the list snapshot same-tick fresh (the + // store's own any-key channel is microtask-batched). + this.projectionStore(frame.sessionId).apply(frame.key, frame.value, frame.seq) this.notifier.markDirty() return } if (frame.type === 'session/subscribed') { - const current = this.titleSnapshots.get(frame.sessionId) - if (current !== undefined && current.eventSeq > frame.lastSeq) { - this.titleSnapshots.delete(frame.sessionId) - this.notifier.markDirty() - } + // Rows past the host's durable baseline rode state a restart lost; drop + // them so last-wins cannot pin a phantom value over recomputed truth. + this.projectionStores.get(frame.sessionId)?.truncate(frame.lastSeq) + this.notifier.markDirty() // New mux-generation baseline: buffered session/queued frames belong to // the previous generation and the host is about to resend the live // snapshot — drop them, or every reconnect appends a duplicate batch @@ -377,7 +391,7 @@ export class SessionManager { this.recordMutation({ kind: 'remove', sessionId: frame.sessionId }) this.sessions.get(frame.sessionId)?.handleRemoved() // instance survives (resident-instance rule), only flagged in the snapshot this.pendingBuffers.delete(frame.sessionId) // a removed session's buffered frames must not replay on a future instantiation - this.titleSnapshots.delete(frame.sessionId) + this.projectionStores.delete(frame.sessionId) // removed sessions drop their projection rows with the instance return } case 'host/session-status': { @@ -402,10 +416,12 @@ export class SessionManager { private buildListSnapshot(): SessionListSnapshot { const merged: TitledSessionSummary[] = this.summaries.map((summary) => { - const title = this.titleSnapshots.get(summary.sessionId) - return title === undefined - ? summary - : { ...summary, title: title.title, updatedAt: Math.max(summary.updatedAt, title.updatedAt) } + // List rows read the generic 'title' projection key (host-computed unit + // value; the bespoke session/title frame is retired). + const title = this.projectionStores.get(summary.sessionId)?.get('title') + return typeof title === 'string' && title !== '' + ? { ...summary, title } + : summary }) const fresh = flattenLineage(merged) const items = fresh.map((entry) => { diff --git a/packages/client/runtime/src/client/sessions/projection-store.ts b/packages/client/runtime/src/client/sessions/projection-store.ts new file mode 100644 index 0000000000..4e6e7dd626 --- /dev/null +++ b/packages/client/runtime/src/client/sessions/projection-store.ts @@ -0,0 +1,183 @@ +/** + * Generic per-session projection value store (session-projection RFC, push + * model): the host is the only computation site; the client holds finished + * whole values per key — `key → { value, seq }` — seeded by the history tail + * page's projections block and updated by `session/projection` push frames, + * under the single rule **higher seq wins**. No client-side domain folding + * exists: a domain ships projection support with zero client code. Per-key + * bare observable faces feed `useProjection` (web-react binds them). + */ +import type { SessionProjectionMap } from '@deepseek-ai/dsh-session-projection/types' +import type { ObservableSnapshot } from '../contract/store.ts' +import { Notifier } from './notifier.ts' + +// The single projection type table, typed end to end (host unit, wire block, +// client store, React hook) — the interface package's pure-type outlet +// (`/types`, zero imports), never the package root: the root's dsh-agent → +// dsh-session chain would drag the host `Context.sessions` merge into the +// client program (one program must not hold both sides). No second +// client-side "views" table (user ruling, RFC Alternatives). +export type { SessionProjectionMap } from '@deepseek-ai/dsh-session-projection/types' + +/** + * The fifth framework hook seat (session-projection RFC): key-addressed + * projection reader delivered through the standard kit. `undefined` uniformly + * means capability absent — host unit unmounted, or no baseline/frame has + * carried the key yet. The selector overload mirrors useSession (per-key uSES + * binding; reference stability holds because a key's value reference changes + * only when a frame or baseline lands). + */ +export type UseProjection = { + >(key: K): SessionProjectionMap[K] | undefined + , S>( + key: K, + selector: (value: SessionProjectionMap[K] | undefined) => S, + eq?: (a: S, b: S) => boolean, + ): S +} + +/** + * Tail-page projections baseline — structurally identical to the wire's + * `SessionProjectionsBlock` (apiproxy api layer), restated here so the + * React-free store depends only on the type table, not the wire package's + * response vocabulary. + */ +export interface ProjectionsBaseline { + /** The consistent-cut seq (equals the window tail seq by construction). */ + asOfSeq: number + /** Whole current values by key; a registered key absent here means the capability is absent. */ + values: Partial +} + +/** One key's row: the latest finished value and the seq it is consistent with. */ +interface Row { + value: unknown + seq: number +} + +/** Per-key notification channel: the bare face plus its batching notifier. */ +interface Channel { + face: ObservableSnapshot + notifier: Notifier +} + +/** + * One session's projection values. Framework semantics, uniform across every + * key: a baseline seeds rows at its cut, a push frame updates one row, and in + * both paths a lower-or-equal seq loses — a replayed frame cannot regress a + * value, a stale baseline cannot overwrite a newer frame. A key the store has + * never seen reads `undefined` (capability absent). Faces are identity-stable + * per key (create-on-demand, cached) so the React side binds each exactly + * once; the store-level channel (`subscribeAny`) serves coarse consumers (the + * manager's list projection reads the `title` key). + */ +export class ProjectionValueStore { + private readonly rows = new Map() + private readonly channels = new Map() + /** Coarse any-key channel (no snapshot cache to rebuild: reads hit rows directly). */ + private readonly anyNotifier = new Notifier(() => {}) + + /** + * Key-addressed bare observable face (the useProjection resolution path). + * Always defined — absence is an `undefined` snapshot, never a missing + * face, so a component may subscribe before the key ever carries a value. + * @param key - projection key. + * @returns the identity-stable face for this key. + */ + faceOf(key: string): ObservableSnapshot { + return this.channel(key).face + } + + /** + * Current whole value for a key (erased framework read; typed reads go + * through `useProjection`'s map lookup). + * @param key - projection key. + * @returns the value, or undefined while the key is absent. + */ + get(key: string): unknown { + return this.rows.get(key)?.value + } + + /** + * Subscribe to any-key changes (microtask-batched) — the manager's list + * rebuild channel. + * @param listener - change callback. + * @returns the unsubscribe function. + */ + subscribeAny(listener: () => void): () => void { + return this.anyNotifier.subscribe(listener) + } + + /** + * Apply one finished value (the `session/projection` push-frame path). + * @param key - projection key. + * @param value - whole value computed by the host unit. + * @param seq - the unit's watermark at emission. + */ + apply(key: string, value: unknown, seq: number): void { + const row = this.rows.get(key) + if (row !== undefined && seq <= row.seq) return // higher seq wins; replays and stale frames drop + this.rows.set(key, { value, seq }) + this.changed(key) + } + + /** + * Seed from a history tail page's projections block: every carried key + * lands under the same seq rule as frames; a key the block omits is + * capability-absent as of the cut — its row clears unless a newer frame + * already superseded the cut (a stale baseline can neither overwrite nor + * clear newer values). + * @param baseline - the response's projections block. + */ + seed(baseline: ProjectionsBaseline): void { + // Erased walk: the framework crosses the open key space; per-key typing + // is re-established at the consumer (useProjection's map lookup). + const values = baseline.values as Record + for (const key of Object.keys(values)) this.apply(key, values[key], baseline.asOfSeq) + for (const [key, row] of this.rows) { + if (Object.hasOwn(values, key)) continue + if (row.seq > baseline.asOfSeq) continue + this.rows.delete(key) + this.changed(key) + } + } + + /** + * Drop rows past a mux-generation baseline (`session/subscribed.lastSeq`): + * a row claiming knowledge beyond the host's own durable baseline rode + * state a restart lost — under last-wins it would wrongly outrank the + * host's recomputed (lower-seq) values forever. Durable replay and the next + * baseline re-seed whatever truly survived (the title-snapshot precedent, + * generalized). + * @param lastSeq - the subscribed frame's durable baseline seq. + */ + truncate(lastSeq: number): void { + for (const [key, row] of this.rows) { + if (row.seq <= lastSeq) continue + this.rows.delete(key) + this.changed(key) + } + } + + private changed(key: string): void { + this.channels.get(key)?.notifier.markDirty() + this.anyNotifier.markDirty() + } + + private channel(key: string): Channel { + let channel = this.channels.get(key) + if (channel === undefined) { + // The notifier only batches (no snapshot cache to rebuild: faces read rows directly). + const notifier = new Notifier(() => {}) + channel = { + notifier, + face: { + getSnapshot: () => this.rows.get(key)?.value, + subscribe: listener => notifier.subscribe(listener), + }, + } + this.channels.set(key, channel) + } + return channel + } +} diff --git a/packages/client/runtime/src/client/sessions/service.ts b/packages/client/runtime/src/client/sessions/service.ts index 997b75ae15..1ab0582f68 100644 --- a/packages/client/runtime/src/client/sessions/service.ts +++ b/packages/client/runtime/src/client/sessions/service.ts @@ -320,7 +320,7 @@ export class SessionsService { props[name] = undefined } } - return { sessionId: undefined, hooks, props } + return { sessionId: undefined, hooks, props } // no projections face: every key reads absent without a session } /** Materialize the standard-props bundle for one session (fails loud on duplicate member names). */ @@ -353,7 +353,14 @@ export class SessionsService { props[name] = contributedProps[name] } } - return { sessionId: binding.sessionId, hooks, props } + return { + sessionId: binding.sessionId, + hooks, + props, + // The useProjection seat: key-addressed bare value faces off the + // session's projection store (open key space — never a static roster member). + projections: { faceOf: key => binding.session.projections.faceOf(key) }, + } } /** diff --git a/packages/client/runtime/src/client/sessions/session.ts b/packages/client/runtime/src/client/sessions/session.ts index 55dd148c50..26a66956cf 100644 --- a/packages/client/runtime/src/client/sessions/session.ts +++ b/packages/client/runtime/src/client/sessions/session.ts @@ -3,7 +3,7 @@ import type { Context } from 'cordis' import type { AttachmentIdType, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { ContentBlock } from '@deepseek-ai/dsh-llm/types' -import type { SessionEvent, TodoItem } from '@deepseek-ai/dsh-session/types' +import type { SessionEvent } from '@deepseek-ai/dsh-session/types' import type { HistoryEntry, IApiClient, MuxFrame, PromptContentPart, RpcError, RpcId, RpcResult, SessionId, ToolEventView, @@ -21,6 +21,8 @@ import { PendingWait } from './pending.ts' import { FoldAdapter } from './fold-adapter.ts' import { Notifier } from './notifier.ts' import { PartialAccumulator } from './partial.ts' +import { ProjectionValueStore } from './projection-store.ts' +import type { ProjectionsBaseline } from './projection-store.ts' /** Messages requested per history page. */ export const PAGE_MESSAGES = 50 @@ -36,6 +38,12 @@ export interface SessionOptions { * (hidden, still reusable by connectWorkspace). */ onEngaged?(session: Session): void + /** + * Manager-owned projection value store to adopt (frames route through the + * manager and values outlive instantiation); omitted, the Session owns a + * private store (bare object-layer construction). + */ + projections?: ProjectionValueStore } /** Queue-row preview cap: the dock renders one line, the full content never leaves the host mirror. */ @@ -100,9 +108,6 @@ export class Session implements ObservableSnapshot { private queueCache: { rev: number; value: QueuedMessage[] } | null = null private frozenRev = 0 private nodesCache: { folded: readonly ConversationNode[]; frozenRev: number; value: readonly ConversationNode[] } | null = null - /** Current whole-list todo/write projection: each tail history response replaces it (an omitted - * field is the authoritative empty list) and every live write overwrites it. */ - private todos: readonly TodoItem[] = [] /** `run_code` sub-dispatches by parent callId (window-derived, like openCalls). Appends * copy-on-write the per-parent array so published snapshot references never mutate. */ private codeDispatches = new Map() @@ -127,6 +132,19 @@ export class Session implements ObservableSnapshot { /** subscribed.lastSeq baseline (gap detection; null when no subscribed frame arrived — degrade to the liveBuffer dedup path). */ private subscribedLastSeq: number | null = null + /** + * Per-session projection value store (session-projection RFC, push model): + * finished whole values computed on the host, seeded by the tail page's + * projections block and updated by `session/projection` frames under the + * one higher-seq-wins rule. Keys are read via `projections.faceOf(key)` + * (the useProjection resolution face); the conversation snapshot never + * carries projection values, and no client-side domain folding exists. + * Manager-owned when constructed through SessionManager (frames route and + * the store outlives instantiation, the title-snapshot precedent); a bare + * construction gets a private store. + */ + readonly projections: ProjectionValueStore + private snapshotCache: ConversationSnapshot private readonly notifier = new Notifier(() => { this.snapshotCache = this.buildSnapshot() @@ -150,6 +168,7 @@ export class Session implements ObservableSnapshot { private readonly api: IApiClient, private readonly options: SessionOptions = {}, ) { + this.projections = options.projections ?? new ProjectionValueStore() this.snapshotCache = this.buildSnapshot() } @@ -505,13 +524,13 @@ export class Session implements ObservableSnapshot { this.openError = result.error return } - this.installWindow(result.value.events, result.value.hasMore, result.value.todos) + this.installWindow(result.value.events, result.value.hasMore, result.value.projections) // Gap detection (§D.3-4): baseline past the window tail and liveBuffer did not cover it -> pull the tail page once more. const tailSeq = this.windowTailSeq() if (this.subscribedLastSeq !== null && tailSeq !== null && this.subscribedLastSeq > tailSeq) { result = (await this.api.sessions.history({ sessionId: this.sessionId, maxMessages: PAGE_MESSAGES })).result if (generation !== this.openGeneration) return - if (result.ok) this.installWindow(result.value.events, result.value.hasMore, result.value.todos) + if (result.ok) this.installWindow(result.value.events, result.value.hasMore, result.value.projections) } this.openState = 'open' } catch (error) { @@ -528,22 +547,18 @@ export class Session implements ObservableSnapshot { /** Install the history window + stitch the liveBuffer (seq is the sole dedup key). * Stitching MUST NOT route through acceptLiveEvent: openState is still 'loading' here * (doOpen flips it after install), so recursing would push every buffered event straight - * back into liveBuffer where nothing ever drains it — a silent drop loop (audit S1). */ - private installWindow(entries: HistoryEntry[], hasMore: boolean, todos: readonly TodoItem[] | undefined): void { + * back into liveBuffer where nothing ever drains it — a silent drop loop (audit S1). + * A carried projections block seeds the value store (higher seq wins, so a stale + * baseline cannot overwrite a newer push frame); the window events themselves are + * never folded — the host is the only computation site. */ + private installWindow(entries: HistoryEntry[], hasMore: boolean, projections?: ProjectionsBaseline): void { this.events = entries.map(e => e.event) this.views = entries.map(e => e.view) this.baseSeq = this.events[0]?.seq ?? 0 this.hasMore = hasMore - // Session-level projection from the tail page (full-log latest todo/write, - // independent of the window); an in-window write below re-derives the same - // value, and later live events keep overwriting it. Every caller here is a - // tail request (no beforeSeq), which the host answers with the projection - // or omits it only when the full log holds no todo/write — so an absent - // field is the authoritative empty list, not a missing carrier. Assigning - // it clears a plan the log never kept (a write lost to a host crash). - this.todos = todos ?? [] this.foldAdapter.reset(this.events, this.baseSeq, this.views) this.rebuildDerivedFromWindow() + if (projections !== undefined) this.projections.seed(projections) const buffered = this.liveBuffer this.liveBuffer = [] for (const item of buffered) this.appendLive(item.event, item.view) @@ -592,7 +607,7 @@ export class Session implements ObservableSnapshot { const { result } = await this.api.sessions.history({ sessionId: this.sessionId, maxMessages: PAGE_MESSAGES }) // Failure or superseded by a full resync: drop — the resync path rebuilds and clears the buffer itself. if (result.ok && generation === this.openGeneration && this.openState === 'open') { - this.installWindow(result.value.events, result.value.hasMore, result.value.todos) + this.installWindow(result.value.events, result.value.hasMore, result.value.projections) } } catch (error) { console.error('[web-runtime] gap repair failed:', error) @@ -712,10 +727,6 @@ export class Session implements ObservableSnapshot { if (this.openCalls.delete(String(event.data.callId))) this.callsRev++ return } - case 'todo/write': { - this.todos = event.data.todos - return - } case 'turn/end': { // Aborted turns never finalize. The accumulated partial is VALUE, not residue: freeze it // into an interrupted terminal node (pulse stops, text survives) instead of deleting it. @@ -760,10 +771,7 @@ export class Session implements ObservableSnapshot { /** Re-derive state (partial/openCalls/frozenNodes) from raw window events after a rebuild — keeps * paging/stitching consistent, and makes the live freeze and the history replay converge on the - * same interrupted nodes (chunks are logged, so the replayed sweep re-freezes identical text). - * todos is deliberately NOT reset: it is session-level (seeded by the tail page's full-log - * projection, not derivable from an arbitrary window). The window always extends to the log - * tail, so an in-window todo/write can only overwrite it with the same latest value. */ + * same interrupted nodes (chunks are logged, so the replayed sweep re-freezes identical text). */ private rebuildDerivedFromWindow(): void { this.partial = null this.openCalls.clear() @@ -833,7 +841,6 @@ export class Session implements ObservableSnapshot { promptError: this.promptError, blank: this.blankBit, lastAgentError: this.lastAgentError, - todos: this.todos, } } } diff --git a/packages/client/runtime/src/client/workspaces/service.ts b/packages/client/runtime/src/client/workspaces/service.ts index fe345801c6..97f01d0bf1 100644 --- a/packages/client/runtime/src/client/workspaces/service.ts +++ b/packages/client/runtime/src/client/workspaces/service.ts @@ -182,6 +182,17 @@ export class WorkspacesService { return response.result.value.path } + /** + * Open a filesystem path with the Host operating system's default application. + * @param path - absolute or host-resolvable path. + */ + async openPath(path: string): Promise { + const response = await this.api.host.openPath({ path }) + if (!response.result.ok) { + throw new Error(`path open failed: ${response.result.error.message}`) + } + } + /** * Rename a Workspace. * @param workspaceId - target workspace. diff --git a/packages/client/runtime/tests/event-script.ts b/packages/client/runtime/tests/event-script.ts index ada8550136..8d9569055f 100644 --- a/packages/client/runtime/tests/event-script.ts +++ b/packages/client/runtime/tests/event-script.ts @@ -40,8 +40,10 @@ export const ev = { at(seq, { type: 'step/end', data: { turn, step } }), turnEnd: (seq: number, turn: number, reason: 'completed' | 'cancelled' = 'completed'): SessionEvent => at(seq, { type: 'turn/end', data: { turn, reason: { kind: reason } } }), - todoWrite: (seq: number, todos: { content: string; status: 'pending' | 'in_progress' | 'completed' }[]): SessionEvent => - at(seq, { type: 'todo/write', data: { todos } }), + commandRun: (seq: number, commandId: string, name: string, args = ''): SessionEvent => + at(seq, { type: 'command/run', data: { commandId, name, args, source: { kind: 'user' } } }), + commandDone: (seq: number, commandId: string, kind: 'success' | 'error' = 'success', text?: string): SessionEvent => + at(seq, { type: 'command/done', data: { commandId, kind, ...text === undefined ? {} : { text } } }), } /** One complete plain turn (turn/start → user → step → assistant → turn/end), 6 events from startSeq. */ diff --git a/packages/client/runtime/tests/fake-api.ts b/packages/client/runtime/tests/fake-api.ts index 8098ee8714..cd592205c1 100644 --- a/packages/client/runtime/tests/fake-api.ts +++ b/packages/client/runtime/tests/fake-api.ts @@ -1,8 +1,9 @@ // Test-local programmable IApiClient fake (NOT the fixture: fixture is a demo // data source on a real clock; behavior tests need per-case responses and // deferred-controlled timing). Streams are hand pumps: pushMux/pushHost. +import type { CommandId } from '@deepseek-ai/dsh-commands/brand' import type { - ClientResponse, CommandDescriptor, CommandExecuteResult, HostFrame, IApiClient, ModelTarget, MuxFrame, + ClientResponse, CommandDescriptor, HostFrame, IApiClient, ModelTarget, MuxFrame, RpcError, RpcReceipt, RpcRequest, RpcResponse, SessionId, SessionModels, SkillEntry, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-connection/client' @@ -63,7 +64,7 @@ export class FakeApiClient implements IApiClient { onCreate: (payload: unknown) => Promise> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId })) readonly defaultModel: ModelTarget = { provider: 'deepseek', model: 'deepseek-v4-flash' } onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) - => Promise> = + => Promise> = () => Promise.resolve(ok({ events: [], hasMore: false })) onModels: (payload: unknown) => Promise> = () => Promise.resolve(ok({ @@ -86,6 +87,8 @@ export class FakeApiClient implements IApiClient { () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) onPickDirectory: (payload: unknown) => Promise> = () => Promise.resolve(ok({ path: null })) + onOpenPath: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ opened: true as const })) private readonly muxConns: StreamConn[] = [] private readonly hostConns: StreamConn[] = [] @@ -109,6 +112,7 @@ export class FakeApiClient implements IApiClient { readonly host: IApiClient['host'] = { describe: (payload: unknown) => this.record('host.describe', payload, this.onDescribe(payload)), pickDirectory: (payload: unknown) => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)), + openPath: (payload: unknown) => this.record('host.openPath', payload, this.onOpenPath(payload)), } onWorkspaceList: (payload: unknown) => Promise> = () => Promise.resolve(ok({ items: [] })) @@ -136,10 +140,12 @@ export class FakeApiClient implements IApiClient { // Payloads stay `unknown` (lint-lane note above); response rows are the real // wire shapes so cases can program requires-bearing catalogs and dual-address // skill lists without casts. - onCommandList: (payload: unknown) => Promise> = () => Promise.resolve(ok({ commands: [] })) - onCommandExecute: (payload: unknown) => Promise> = - () => Promise.resolve(ok({ matched: false })) - onSkillList: (payload: unknown) => Promise> = () => Promise.resolve(ok({ skills: [] })) + onCommandList: (payload: unknown) => Promise> + = () => Promise.resolve(ok({ commands: [] })) + onCommandExecute: (payload: unknown) => Promise> + = () => Promise.resolve(ok({ matched: false })) + onSkillList: (payload: unknown) => Promise> + = () => Promise.resolve(ok({ skills: [] })) readonly commands: IApiClient['commands'] = { list: (payload: unknown) => this.record('command.list', payload, this.onCommandList(payload)), diff --git a/packages/client/runtime/tests/fold-adapter.spec.ts b/packages/client/runtime/tests/fold-adapter.spec.ts index bb360e2a67..88a597063e 100644 --- a/packages/client/runtime/tests/fold-adapter.spec.ts +++ b/packages/client/runtime/tests/fold-adapter.spec.ts @@ -142,4 +142,75 @@ describe('FoldAdapter', () => { const node = adapter.nodes().nodes[0] expect(node).toMatchObject({ kind: 'tool-result', call: null, callView: null, resultView: { title: '孤儿' } }) }) + + describe('command lifecycle nodes', () => { + it('folds a run/done pair into one settled node merged into flow order by seq', () => { + const adapter = new FoldAdapter() + adapter.reset([ + ev.user(0, '先说话'), + ev.commandRun(1, 'cmd-1', 'plan'), + ev.commandDone(2, 'cmd-1', 'success', '已进入 plan mode'), + ev.assistant(3, 0, '然后回答'), + ], 0) + const { nodes } = adapter.nodes() + expect(nodes.map(n => [n.kind, n.seq])).toEqual([['user', 0], ['command', 1], ['assistant', 3]]) + expect(nodes[1]).toMatchObject({ + kind: 'command', commandId: 'cmd-1', name: 'plan', args: '', + outcome: { kind: 'success', text: '已进入 plan mode' }, + }) + }) + + it('renders a run with no done as still executing (outcome null)', () => { + const adapter = new FoldAdapter() + adapter.reset([ev.commandRun(0, 'cmd-2', 'goal', ' ship it')], 0) + expect(adapter.nodes().nodes[0]).toMatchObject({ + kind: 'command', name: 'goal', args: ' ship it', outcome: null, + }) + }) + + it('soft-falls a done-only window into a node built from the done (cross-window cut)', () => { + const adapter = new FoldAdapter() + adapter.reset([ev.commandDone(80, 'cmd-3', 'error', '失败了')], 80) + expect(adapter.nodes().nodes[0]).toMatchObject({ + kind: 'command', seq: 80, commandId: 'cmd-3', name: null, args: null, + outcome: { kind: 'error', text: '失败了' }, + }) + }) + + it('settles a live-appended done in place, keeping the node at the run seq', () => { + const adapter = new FoldAdapter() + adapter.reset(plainTurn(0, 0, 'q', 'a'), 0) + adapter.append(ev.commandRun(6, 'cmd-4', 'clear')) + const running = adapter.nodes().nodes.find(n => n.kind === 'command') + expect(running).toMatchObject({ outcome: null }) + adapter.append(ev.commandDone(7, 'cmd-4')) + const settled = adapter.nodes().nodes.find(n => n.kind === 'command') + expect(settled).toMatchObject({ seq: 6, outcome: { kind: 'success' } }) + // Settlement replaced the node object rather than mutating the published one. + expect(settled).not.toBe(running) + }) + + it('tails command nodes whose seq is past every surface node', () => { + const adapter = new FoldAdapter() + adapter.reset([ev.user(0, '问'), ev.commandRun(1, 'cmd-tail', 'plan')], 0) + expect(adapter.nodes().nodes.map(n => n.kind)).toEqual(['user', 'command']) + }) + + it('command nodes survive the degraded linear-scan branch', () => { + const adapter = new FoldAdapter() + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + adapter.reset([ + ev.commandRun(0, 'cmd-5', 'plan'), + ev.commandDone(1, 'cmd-5'), + at(2, { type: 'assistant/message', surfaceOp: 'bogus-op', data: { turn: 0, step: 0, content: [{ type: 'text', text: '坏 op' }], provenance: { provider: 'x', model: 'y' } } }), + ], 0) + const { nodes, degraded } = adapter.nodes() + expect(degraded).toBe(true) + expect(nodes.some(n => n.kind === 'command')).toBe(true) + } finally { + errorSpy.mockRestore() + } + }) + }) }) diff --git a/packages/client/runtime/tests/manager.spec.ts b/packages/client/runtime/tests/manager.spec.ts index 039a48894c..2923cd0d3c 100644 --- a/packages/client/runtime/tests/manager.spec.ts +++ b/packages/client/runtime/tests/manager.spec.ts @@ -133,21 +133,18 @@ describe('list lifecycle', () => { expect(manager.getListSnapshot().items.map(i => i.sessionId)).toEqual([S2]) }) - it('retains monotonic title snapshots before list arrival, merges recency, and clears them on removal', async () => { + it('retains title projections before list arrival, keeps last-wins by seq, and clears them on removal', async () => { const api = new FakeApiClient() const manager = new SessionManager(api) - manager.handleMuxEnvelope({ - rpcId: 'title-new' as never, - payload: { type: 'session/title', sessionId: S1, title: 'Newest', eventSeq: 4, updatedAt: 300 }, - }) - manager.handleMuxEnvelope({ - rpcId: 'title-stale' as never, - payload: { type: 'session/title', sessionId: S1, title: 'Stale', eventSeq: 3, updatedAt: 900 }, - }) - manager.handleMuxEnvelope({ - rpcId: 'title-equal' as never, - payload: { type: 'session/title', sessionId: S1, title: 'Equal', eventSeq: 4, updatedAt: 901 }, - }) + const titleFrame = (rpcId: string, title: string, seq: number) => { + manager.handleMuxEnvelope({ + rpcId: rpcId as never, + payload: { type: 'session/projection', sessionId: S1, key: 'title', value: title, seq } as never, + }) + } + titleFrame('title-new', 'Newest', 4) + titleFrame('title-stale', 'Stale', 3) + titleFrame('title-equal', 'Equal', 4) api.onList = () => Promise.resolve(ok({ items: [summary(S1), summary(S2, { updatedAt: 200 })] as never[], })) @@ -155,7 +152,7 @@ describe('list lifecycle', () => { const titled = manager.getListSnapshot() expect(titled.items.map(item => item.sessionId)).toEqual([S1, S2]) - expect(titled.items[0]).toMatchObject({ title: 'Newest', updatedAt: 300 }) + expect(titled.items[0]?.title).toBe('Newest') expect(titled.items[1]?.title).toBeUndefined() manager.handleHostEnvelope({ rpcId: 'removed' as never, payload: { type: 'host/session-removed', sessionId: S1 } }) @@ -163,34 +160,27 @@ describe('list lifecycle', () => { expect(manager.getListSnapshot().items.find(item => item.sessionId === S1)?.title).toBeUndefined() }) - it('drops a retained title beyond the subscription baseline before accepting its durable replay', async () => { + it('drops a projection row beyond the subscription baseline before accepting its durable replay', async () => { const api = new FakeApiClient() api.onList = () => Promise.resolve(ok({ items: [summary(S1)] as never[] })) const manager = new SessionManager(api) await manager.refreshList() - manager.handleMuxEnvelope({ - rpcId: 'title-unflushed' as never, - payload: { type: 'session/title', sessionId: S1, title: 'Unflushed', eventSeq: 4, updatedAt: 400 }, - }) + const frame = (rpcId: string, payload: object) => { + manager.handleMuxEnvelope({ rpcId: rpcId as never, payload: payload as never }) + } + frame('title-unflushed', { type: 'session/projection', sessionId: S1, key: 'title', value: 'Unflushed', seq: 4 }) - manager.handleMuxEnvelope({ - rpcId: 'subscribed-recovered' as never, - payload: { type: 'session/subscribed', sessionId: S1, lastSeq: 2 }, - }) + // The durable baseline says the host only knows up to seq 2: the phantom + // row rode lost state and must drop, or last-wins pins it forever. + frame('subscribed-recovered', { type: 'session/subscribed', sessionId: S1, lastSeq: 2 }) expect(manager.getListSnapshot().items[0]?.title).toBeUndefined() - expect(manager.getListSnapshot().items[0]?.updatedAt).toBe(100) - manager.handleMuxEnvelope({ - rpcId: 'title-durable' as never, - payload: { type: 'session/title', sessionId: S1, title: 'Durable', eventSeq: 2, updatedAt: 200 }, - }) - expect(manager.getListSnapshot().items[0]).toMatchObject({ title: 'Durable', updatedAt: 200 }) + frame('title-durable', { type: 'session/projection', sessionId: S1, key: 'title', value: 'Durable', seq: 2 }) + expect(manager.getListSnapshot().items[0]?.title).toBe('Durable') - manager.handleMuxEnvelope({ - rpcId: 'subscribed-current' as never, - payload: { type: 'session/subscribed', sessionId: S1, lastSeq: 2 }, - }) - expect(manager.getListSnapshot().items[0]).toMatchObject({ title: 'Durable', updatedAt: 200 }) + // A baseline at or past the row's seq keeps it (nothing phantom to drop). + frame('subscribed-current', { type: 'session/subscribed', sessionId: S1, lastSeq: 2 }) + expect(manager.getListSnapshot().items[0]?.title).toBe('Durable') }) }) diff --git a/packages/client/runtime/tests/projection-store.spec.ts b/packages/client/runtime/tests/projection-store.spec.ts new file mode 100644 index 0000000000..eea43b67f3 --- /dev/null +++ b/packages/client/runtime/tests/projection-store.spec.ts @@ -0,0 +1,187 @@ +/** + * Projection value store (session-projection RFC, push model): the single + * higher-seq-wins rule on both paths (a stale baseline cannot overwrite a + * newer push frame; a replayed frame cannot regress), capability absence as + * undefined, generation truncation, and the Session/manager wiring (tail-page + * seeding, session/projection frame routing pre- and post-instantiation, the + * list rows' title projection). + */ +import { describe, expect, it } from 'vitest' +import type { SessionId } from '@deepseek-ai/dsh-client-connection/client' +import { ProjectionValueStore } from '../src/client/sessions/projection-store.ts' +import { Session } from '../src/client/sessions/session.ts' +import { SessionManager } from '../src/client/sessions/manager.ts' +import { FakeApiClient, ok } from './fake-api.ts' +import { entries, plainTurn } from './event-script.ts' + +// Test-domain keys merged into the projection map (the interface package's +// pure-type outlet), the same way domain host plugins merge theirs. +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionMap { + 'test/marks': { marks: string[] } + } +} + +const SID = 'fk-s1' as SessionId + +describe('ProjectionValueStore semantics', () => { + it('reads undefined until a value lands (capability absence)', () => { + const store = new ProjectionValueStore() + expect(store.get('test/marks')).toBeUndefined() + expect(store.faceOf('test/marks').getSnapshot()).toBeUndefined() + }) + + it('applies frames last-wins by seq: replayed and stale frames drop', () => { + const store = new ProjectionValueStore() + store.apply('test/marks', { marks: ['a'] }, 5) + store.apply('test/marks', { marks: ['a', 'b'] }, 9) + expect(store.get('test/marks')).toEqual({ marks: ['a', 'b'] }) + store.apply('test/marks', { marks: ['stale'] }, 5) + store.apply('test/marks', { marks: ['equal'] }, 9) + expect(store.get('test/marks')).toEqual({ marks: ['a', 'b'] }) + }) + + it('a stale baseline can neither overwrite nor clear a newer frame; a fresh one reseeds and clears', () => { + const store = new ProjectionValueStore() + store.apply('test/marks', { marks: ['frame-20'] }, 20) + // Stale cut: carried key loses to the newer frame; omitted key survives. + store.seed({ asOfSeq: 10, values: { 'test/marks': { marks: ['baseline-10'] } } }) + expect(store.get('test/marks')).toEqual({ marks: ['frame-20'] }) + store.seed({ asOfSeq: 15, values: {} }) + expect(store.get('test/marks')).toEqual({ marks: ['frame-20'] }) + // Fresh cut: carried key reseeds… + store.seed({ asOfSeq: 30, values: { 'test/marks': { marks: ['baseline-30'] } } }) + expect(store.get('test/marks')).toEqual({ marks: ['baseline-30'] }) + // …and an omitting fresh cut clears (capability absent as of the cut). + store.seed({ asOfSeq: 40, values: {} }) + expect(store.get('test/marks')).toBeUndefined() + }) + + it('truncate drops rows past the durable baseline and keeps the rest', () => { + const store = new ProjectionValueStore() + store.apply('test/marks', { marks: ['durable'] }, 5) + store.apply('other', 'phantom', 50) + store.truncate(10) + expect(store.get('test/marks')).toEqual({ marks: ['durable'] }) + expect(store.get('other')).toBeUndefined() + }) + + it('notifies the key face on change (batched) and not on dropped applications', async () => { + const store = new ProjectionValueStore() + let keyTicks = 0 + let anyTicks = 0 + store.faceOf('test/marks').subscribe(() => { keyTicks += 1 }) + store.subscribeAny(() => { anyTicks += 1 }) + store.apply('test/marks', { marks: ['a'] }, 5) + await Promise.resolve() + expect(keyTicks).toBe(1) + expect(anyTicks).toBe(1) + store.apply('test/marks', { marks: ['replay'] }, 3) + await Promise.resolve() + expect(keyTicks).toBe(1) + expect(anyTicks).toBe(1) + }) + + it('faces are identity-stable per key (the React binding cache premise)', () => { + const store = new ProjectionValueStore() + expect(store.faceOf('test/marks')).toBe(store.faceOf('test/marks')) + }) +}) + +describe('Session tail-page seeding', () => { + it('seeds the store from a history response carrying a projections block', async () => { + const api = new FakeApiClient() + const session = new Session(SID, api) + api.onHistory = () => Promise.resolve(ok({ + events: entries(plainTurn(0, 0, '问', '答')) as never[], hasMore: false, + projections: { asOfSeq: 5, values: { 'test/marks': { marks: ['from-baseline'] } } }, + } as never)) + await session.open() + expect(session.projections.get('test/marks')).toEqual({ marks: ['from-baseline'] }) + }) + + it('a resync serving a stale block keeps the newer pushed value (seq rule end to end)', async () => { + const api = new FakeApiClient() + const session = new Session(SID, api) + api.onHistory = () => Promise.resolve(ok({ + events: entries(plainTurn(0, 0, 'a', 'b')) as never[], hasMore: false, + projections: { asOfSeq: 5, values: { 'test/marks': { marks: ['baseline'] } } }, + } as never)) + await session.open() + session.projections.apply('test/marks', { marks: ['pushed-9'] }, 9) + await session.resync() + expect(session.projections.get('test/marks')).toEqual({ marks: ['pushed-9'] }) + }) + + it('treats a blockless response as no reset: pushed values survive', async () => { + const api = new FakeApiClient() + const session = new Session(SID, api) + api.onHistory = () => Promise.resolve(ok({ events: entries(plainTurn(0, 0, 'a', 'b')) as never[], hasMore: false })) + await session.open() + session.projections.apply('test/marks', { marks: ['pushed'] }, 9) + await session.resync() + expect(session.projections.get('test/marks')).toEqual({ marks: ['pushed'] }) + }) +}) + +describe('manager frame routing', () => { + const sid = (s: string): SessionId => s as SessionId + + it('lands session/projection frames before instantiation and the Session adopts the same store', async () => { + const api = new FakeApiClient() + const manager = new SessionManager(api) + manager.handleMuxEnvelope({ + rpcId: 'p1' as never, + payload: { type: 'session/projection', sessionId: sid('s1'), key: 'test/marks', value: { marks: ['early'] }, seq: 7 } as never, + }) + const session = manager.get(sid('s1')) + expect(session.projections.get('test/marks')).toEqual({ marks: ['early'] }) + // Frames after instantiation land in the same store. + manager.handleMuxEnvelope({ + rpcId: 'p2' as never, + payload: { type: 'session/projection', sessionId: sid('s1'), key: 'test/marks', value: { marks: ['later'] }, seq: 9 } as never, + }) + expect(session.projections.get('test/marks')).toEqual({ marks: ['later'] }) + }) + + it('projects the title key into list rows and truncates phantom rows on the subscribed baseline', async () => { + const api = new FakeApiClient() + const manager = new SessionManager(api) + api.onList = () => Promise.resolve(ok({ + items: [{ sessionId: sid('s1'), updatedAt: 1, running: false, blank: false }], + }) as never) + await manager.refreshList() + manager.handleMuxEnvelope({ + rpcId: 't1' as never, + payload: { type: 'session/projection', sessionId: sid('s1'), key: 'title', value: 'Projected title', seq: 4 } as never, + }) + await Promise.resolve() + expect(manager.getListSnapshot().items[0]?.title).toBe('Projected title') + // The durable baseline says the host only knows up to seq 2: the row rode + // lost state and must drop (the un-flushed title precedent). + manager.handleMuxEnvelope({ + rpcId: 'sub' as never, + payload: { type: 'session/subscribed', sessionId: sid('s1'), lastSeq: 2 } as never, + }) + await Promise.resolve() + expect(manager.getListSnapshot().items[0]?.title).toBeUndefined() + }) + + it('drops the projection store with the removed session', async () => { + const api = new FakeApiClient() + const manager = new SessionManager(api) + api.onList = () => Promise.resolve(ok({ + items: [{ sessionId: sid('s1'), updatedAt: 1, running: false, blank: false }], + }) as never) + await manager.refreshList() + manager.handleMuxEnvelope({ + rpcId: 't1' as never, + payload: { type: 'session/projection', sessionId: sid('s1'), key: 'title', value: 'Doomed', seq: 4 } as never, + }) + manager.handleHostEnvelope({ + rpcId: 'rm' as never, + payload: { type: 'host/session-removed', sessionId: sid('s1') } as never, + }) + expect(manager.get(sid('s1')).projections.get('title')).toBeUndefined() + }) +}) diff --git a/packages/client/runtime/tests/session.spec.ts b/packages/client/runtime/tests/session.spec.ts index 89894e2504..84b62ea530 100644 --- a/packages/client/runtime/tests/session.spec.ts +++ b/packages/client/runtime/tests/session.spec.ts @@ -22,9 +22,9 @@ function makeSession(api = new FakeApiClient()): { api: FakeApiClient; session: return { api, session: new Session(SID, api) } } -function histResponse(events: SessionEvent[], hasMore = false, todos?: { content: string; status: 'pending' | 'in_progress' | 'completed' }[]) { +function histResponse(events: SessionEvent[], hasMore = false) { // history now returns HistoryEntry[] ({event, view?}); these tests are view-less. - return Promise.resolve(ok({ events: entries(events) as never[], hasMore, ...todos === undefined ? {} : { todos } })) + return Promise.resolve(ok({ events: entries(events) as never[], hasMore })) } describe('open', () => { @@ -104,6 +104,28 @@ describe('live event path', () => { expect(session.getSnapshot().nodes).toEqual(before.nodes) }) + it('materializes a command node from live lifecycle frames and reproduces it from a history window', async () => { + // Live path: run mints an executing node, done settles it in the flow. + const { session } = await opened() + const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) } + feed(ev.commandRun(6, 'cmd-live', 'plan')) + let command = session.getSnapshot().nodes.at(-1) + expect(command).toMatchObject({ kind: 'command', name: 'plan', args: '', outcome: null }) + feed(ev.commandDone(7, 'cmd-live', 'success', '已进入 plan mode')) + command = session.getSnapshot().nodes.at(-1) + expect(command).toMatchObject({ kind: 'command', seq: 6, outcome: { kind: 'success', text: '已进入 plan mode' } }) + + // Replay path (refresh): the same pair inside the history window folds identically. + const replayed = await opened([ + ...plainTurn(0, 0, 'a', 'b'), + ev.commandRun(6, 'cmd-live', 'plan'), + ev.commandDone(7, 'cmd-live', 'success', '已进入 plan mode'), + ]) + expect(replayed.session.getSnapshot().nodes.at(-1)).toMatchObject({ + kind: 'command', seq: 6, name: 'plan', outcome: { kind: 'success', text: '已进入 plan mode' }, + }) + }) + it('accumulates chunks into partial, then finalize swaps partial out as the node lands', async () => { const { session } = await opened() const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) } @@ -158,42 +180,6 @@ describe('live event path', () => { }) }) - it('folds todo/write into snapshot.todos last-write-wins, live and on window replay', async () => { - const listA = [{ content: '搭骨架', status: 'completed' as const }, { content: '写组件', status: 'in_progress' as const }] - const listB = [{ content: '搭骨架', status: 'completed' as const }, { content: '写组件', status: 'completed' as const }] - const { session } = await opened() - expect(session.getSnapshot().todos).toEqual([]) - const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) } - feed(ev.todoWrite(6, listA)) - expect(session.getSnapshot().todos).toEqual(listA) - feed(ev.todoWrite(7, listB)) - expect(session.getSnapshot().todos).toEqual(listB) - // Window replay converges on the same last snapshot (history contains both writes). - const replayed = makeSession() - replayed.api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ev.todoWrite(6, listA), ev.todoWrite(7, listB)]) - await replayed.session.open() - expect(replayed.session.getSnapshot().todos).toEqual(listB) - }) - - it('seeds todos from the tail page projection when the last write precedes the window', async () => { - const list = [{ content: '窗口外的计划', status: 'in_progress' as const }] - // Cold open: the page window carries NO todo/write; the projection rides the response. - const { api, session } = makeSession() - api.onHistory = () => histResponse(plainTurn(100, 9, '问', '答'), true, list) - await session.open() - expect(session.getSnapshot().todos).toEqual(list) - // Paging an older window in must not clear the session-level projection. - api.onHistory = () => histResponse(plainTurn(94, 8, '旧问', '旧答'), false) - await session.loadOlder() - expect(session.getSnapshot().todos).toEqual(list) - // A later live write still overrides the seeded projection. - session.handleMuxEnvelope('r' as never, { - type: 'session/event', sessionId: SID, - event: ev.todoWrite(106, [{ content: '新计划', status: 'pending' as const }]), - }) - expect(session.getSnapshot().todos).toEqual([{ content: '新计划', status: 'pending' }]) - }) - it('repairs a seq gap by repulling the tail page instead of appending a hole', async () => { const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5 const repaired = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')] @@ -207,37 +193,6 @@ describe('live event path', () => { const seqs = session.getSnapshot().nodes.map(n => n.seq) expect(seqs).toEqual([1, 3, 7, 9]) // both turns' user/assistant, no hole, no duplicate 9 }) - - it('gap repair adopts the repull response projection (a missed todo/write outside the new tail page)', async () => { - const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5 - expect(session.getSnapshot().todos).toEqual([]) - // The missed range contained a todo/write that the repulled page no longer - // covers; the response's session-level projection is the only carrier. - const current = [{ content: '断线期间写的', status: 'in_progress' as const }] - api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(8, 1, 'c', 'd')], false, current) - session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.assistant(11, 1, 'd') }) - await vi.waitFor(() => { - expect(api.callsOf('session.history').length).toBe(2) - }) - await Promise.resolve() - expect(session.getSnapshot().todos).toEqual(current) - }) - - it('clears the plan when a tail response omits the projection (a write the log never kept)', async () => { - // Live write lands, then the host crashes before persisting it: the - // authoritative log holds no todo/write, so the resync tail response - // carries no projection — an omitted field on a tail request is the empty - // list, not a missing carrier, and the rolled-back plan must disappear. - const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) - session.handleMuxEnvelope('r' as never, { - type: 'session/event', sessionId: SID, - event: ev.todoWrite(6, [{ content: '丢失的计划', status: 'in_progress' as const }]), - }) - expect(session.getSnapshot().todos).toEqual([{ content: '丢失的计划', status: 'in_progress' }]) - api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b')) - await session.resync() - expect(session.getSnapshot().todos).toEqual([]) - }) }) describe('paging', () => { diff --git a/packages/client/runtime/tests/sessions-service.spec.ts b/packages/client/runtime/tests/sessions-service.spec.ts index 45539d3b99..09076bace7 100644 --- a/packages/client/runtime/tests/sessions-service.spec.ts +++ b/packages/client/runtime/tests/sessions-service.spec.ts @@ -47,7 +47,7 @@ describe('list store projection', () => { const b = bench() b.svc.handleMuxEnvelope({ rpcId: 'title' as never, - payload: { type: 'session/title', sessionId: sid('s1'), title: 'Durable title', eventSeq: 2, updatedAt: 3 }, + payload: { type: 'session/projection', sessionId: sid('s1'), key: 'title', value: 'Durable title', seq: 2 } as never, }) await feedList(b, [ { id: 's1', cwd: '/home/u/proj-a/' }, diff --git a/packages/client/runtime/tests/workspaces-service.spec.ts b/packages/client/runtime/tests/workspaces-service.spec.ts index 5327066651..6768fddff7 100644 --- a/packages/client/runtime/tests/workspaces-service.spec.ts +++ b/packages/client/runtime/tests/workspaces-service.spec.ts @@ -236,6 +236,17 @@ describe('WorkspacesService', () => { expect(api.callsOf('host.pickDirectory')).toEqual([{}, {}]) }) + it('opens a filesystem path through the host without local state', async () => { + const ctx = new Context() + const api = new FakeApiClient() + const sessions = new SessionsService(ctx, api) + const workspaces = new WorkspacesService(ctx, api, sessions) + await expect(workspaces.openPath('/w/alpha/a.ts')).resolves.toBeUndefined() + expect(api.callsOf('host.openPath')).toEqual([{ path: '/w/alpha/a.ts' }]) + api.onOpenPath = () => Promise.resolve(err({ code: 'internal', message: 'boom', details: {} })) + await expect(workspaces.openPath('/missing')).rejects.toThrow(/path open failed/) + }) + it('deletes a Workspace or preserves it when the Host rejects deletion', async () => { const ctx = new Context() const api = new FakeApiClient() diff --git a/packages/client/runtime/tsconfig.json b/packages/client/runtime/tsconfig.json index cd29519e92..2195b3c0a0 100644 --- a/packages/client/runtime/tsconfig.json +++ b/packages/client/runtime/tsconfig.json @@ -26,6 +26,15 @@ { "path": "../../host/apiproxy" }, + { + "path": "../../ui/commands" + }, + { + "path": "../../session-projection/session-projection" + }, + { + "path": "../../session-title/session-title" + }, { "path": "../../llm/llm" }, diff --git a/packages/client/ui-command/src/client/service.ts b/packages/client/ui-command/src/client/service.ts index df59ad2dcd..22f4a911b3 100644 --- a/packages/client/ui-command/src/client/service.ts +++ b/packages/client/ui-command/src/client/service.ts @@ -227,7 +227,15 @@ export class CommandService extends Service implements CommandServiceContract { } } - /** The command.execute transaction, addressed to the session's agent. */ + /** + * The command.execute transaction, addressed to the session's agent — pure + * admission semantics. An unmatched line reports an error outcome (the + * composer's immediate admission feedback); an admitted command reports + * plain success regardless of its handler outcome, because the host + * executor durably logged the lifecycle (`command/run`/`command/done`) and + * the outcome renders as a persistent flow node — the composer never + * echoes it. Transport failures throw. + */ private async execute( session: ClientSessionContext, line: string, @@ -236,25 +244,25 @@ export class CommandService extends Service implements CommandServiceContract { const { result } = await connection.api.commands.execute({ sessionId: session.sessionId, line }) if (!result.ok) throw new Error(`command.execute failed: ${result.error.code}: ${result.error.message}`) if (!result.value.matched) return { kind: 'error', text: `unknown or malformed command: ${line}` } - const detached = result.value.result - return detached === undefined - ? { kind: 'success' } - : { kind: detached.kind, ...(detached.text !== undefined ? { text: detached.text } : {}) } + return { kind: 'success' } } /** - * Fire-and-forget execute for the internal ('handled') paths. The detached - * result surfaces as a notice routed to the triggering session's composer, - * so a late result lands on its own session after a switch. + * Fire-and-forget execute for the internal ('handled') paths. Outcomes are + * NOT surfaced here: the host executor durably logs the command lifecycle + * (`command/run`/`command/done`), and the mux-broadcast events render as a + * persistent flow node on every tab. Only a transport/admission failure — + * which never entered a handler and therefore never logged — falls back to + * the composer notice as immediate feedback. */ private runDetached(desc: CommandDescriptor, session: ClientSessionContext, line: string): void { void this.execute(session, line).then( (outcome) => { - if (outcome.kind === 'error') this.noticeFor(session.sessionId, desc.name, 'error', outcome.text ?? `/${desc.name} failed`) - else if (outcome.text !== undefined) this.noticeFor(session.sessionId, desc.name, 'info', outcome.text) + // matched:false maps to an error outcome with no logged lifecycle. + if (outcome.kind === 'error') this.noticeFor(session.sessionId, 'error', outcome.text ?? `/${desc.name} failed`) }, (error: unknown) => { - this.noticeFor(session.sessionId, desc.name, 'error', error instanceof Error ? error.message : String(error)) + this.noticeFor(session.sessionId, 'error', error instanceof Error ? error.message : String(error)) }, ) } @@ -270,8 +278,8 @@ export class CommandService extends Service implements CommandServiceContract { }) } - /** Route a detached result to the session's composer notice channel (scope gone = attempt died with it). */ - private noticeFor(id: SessionId, _name: string, level: 'info' | 'error', text: string): void { + /** Route an admission/transport failure to the session's composer notice channel (scope gone = attempt died with it). */ + private noticeFor(id: SessionId, level: 'info' | 'error', text: string): void { const actx = this.scopeFor(id) if (actx === undefined) return const conversation = actx.get('conversation') diff --git a/packages/client/ui-command/tests/service.spec.ts b/packages/client/ui-command/tests/service.spec.ts index 0cf94e2f82..d3e6b5d34c 100644 --- a/packages/client/ui-command/tests/service.spec.ts +++ b/packages/client/ui-command/tests/service.spec.ts @@ -31,7 +31,7 @@ const S2_CMDS: CommandDescriptor[] = [ { name: 'attach', description: 'scoped shadow', input: { hint: 'path' } }, ] -type ExecuteValue = { matched: boolean; result?: { kind: 'success' | 'error'; text?: string } } +type ExecuteValue = { matched: boolean } interface BenchOptions { /** Scripted catalog per list payload; default serves the fixed catalogs by session. */ @@ -361,16 +361,18 @@ describe('matchEnter (enter column)', () => { }) describe('execute payload', () => { - it('claim.submit addresses the session and maps the detached result', async () => { + it('claim.submit addresses the session; admitted outcomes stay off the composer (flow card owns them)', async () => { const { source, warm, executeCalls } = await bench({ - execute: () => Promise.resolve({ matched: true, result: { kind: 'success', text: 'goal set' } }), + execute: () => Promise.resolve({ matched: true }), }) await warm(proj('s1')) const outcome = source.matchSpace!(proj('s1'), '/goal') if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim') const settled = await outcome.claim.submit('ship it', new Context()) expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/goal ship it' }]) - expect(settled).toEqual({ kind: 'success', text: 'goal set' }) + // Pure admission: no outcome text ever rides the submit result — the + // durable command lifecycle events render the outcome in the flow. + expect(settled).toEqual({ kind: 'success' }) }) it('maps matched:false to an error outcome and a matched bare result to success', async () => { @@ -389,33 +391,29 @@ describe('execute payload', () => { }) }) -describe('detached result notices', () => { +describe('detached admission notices', () => { const flush = () => new Promise(resolve => setTimeout(resolve, 0)) - it('success text → info; error result → error; rejection → error, all on the triggering session', async () => { - let mode: 'info' | 'error' | 'reject' = 'info' + it('admitted outcomes stay silent; admission miss and transport rejection notice as errors', async () => { + let mode: 'admitted' | 'miss' | 'reject' = 'admitted' const { source, mint, warm, notices } = await bench({ execute: () => { if (mode === 'reject') return Promise.reject(new Error('network down')) - return Promise.resolve({ - matched: true, - result: mode === 'info' - ? { kind: 'success' as const, text: 'compacted 12 messages' } - : { kind: 'error' as const, text: 'plan mode refused' }, - }) + return Promise.resolve({ matched: mode === 'admitted' }) }, }) mint('s1') await warm(proj('s1')) + // Admitted: the durable lifecycle events own the outcome — no notice. menuPick(source, 'plan', proj('s1')) await flush() - expect(notices).toEqual([{ scope: sid('s1'), level: 'info', text: 'compacted 12 messages' }]) + expect(notices).toEqual([]) - notices.length = 0 - mode = 'error' + // Admission miss (matched:false): immediate composer feedback stays. + mode = 'miss' await source.matchEnter!(proj('s1'), '/plan', new AbortController().signal) await flush() - expect(notices).toEqual([{ scope: sid('s1'), level: 'error', text: 'plan mode refused' }]) + expect(notices).toEqual([{ scope: sid('s1'), level: 'error', text: 'unknown or malformed command: /plan' }]) notices.length = 0 mode = 'reject' @@ -424,9 +422,9 @@ describe('detached result notices', () => { expect(notices).toEqual([{ scope: sid('s1'), level: 'error', text: 'network down' }]) }) - it('success without text stays silent; a torn-down scope drops the notice', async () => { + it('a torn-down scope drops the failure notice', async () => { const { source, warm, notices } = await bench({ - execute: () => Promise.resolve({ matched: true, result: { kind: 'success' as const, text: 'orphan' } }), + execute: () => Promise.reject(new Error('orphan failure')), }) await warm(proj('ghost')) // never minted: scopeFor misses menuPick(source, 'plan', proj('ghost')) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index db40c98d21..f86f250627 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md -README.md: 6e90e79465e12b32c404cb90b5ed833a4dffe1b3 -README.zh.md: f8b64878707d8434c2b33b607cc05f4734a825d6 +README.md: 1fa93076c019ee795d057ecb00763c99294d8858 +README.zh.md: eae9dfce2b883ec27b6608876016220eb73f7985 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 6e90e79465..1fa93076c0 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -8,9 +8,9 @@ The resident conversation shell survives no-session and session transitions. Wit The view ring IS a slot: the conversation registration declares the `'conversation.view'` list slot (session scope) in its `children` table, ConversationRoot renders the active entry through its renderSlot share (`only: `), and view tabs project from the ring ledger's registration options (`id`/`order`/`label`). The chat view is this package's own ring entry; other plugins (ui-trajectory) contribute tabs through plain `ctx.slots.register` — the former package-local view registry (`registerView`/`ViewEntry`/`ConversationViewMap` and the chrome attachment table) is retired, with per-view chrome dissolved into the view components themselves. -Generic tool rows classify the built-in bash, read, search, write, edit, and run_code names into dedicated visual variants. The filesystem variants render the edit icon and `Write · ` or `Edit · ` summary while retaining the shared row-to-details interaction. The code variant summarizes with the model-authored `description` and expands to the program itself; its logged sub-dispatches render as always-visible nested rows through the SAME keyed toolview hole (custom registrations and the GenericToolCard fallback apply to sub-rows unchanged), and the details panel resolves a selected sub-call id to its full logged args and complete output. Cordis lifecycle tools reuse those generic variants while presenting `Inspect`, `Mount temporary Plugin`, and `Unmount temporary Plugin` with a shared Cordis accent; mount keeps the code variant's expandable source rendering. +Generic tool rows classify the built-in bash, read, search, write, edit, and run_code names into dedicated visual variants. The filesystem variants render the edit icon and a path summary; that path is a hover-underline link that opens the file with the host OS default application (`host.openPath`, relative paths resolve against the session cwd). Tool rows are not whole-row click targets and do not open the details panel. The code variant summarizes with the model-authored `description` and expands to the program itself; its logged sub-dispatches render as always-visible nested rows through the SAME keyed toolview hole (custom registrations and the GenericToolCard fallback apply to sub-rows unchanged). Cordis lifecycle tools reuse those generic variants while presenting `Inspect`, `Mount temporary Plugin`, and `Unmount temporary Plugin` with a shared Cordis accent; mount keeps the code variant's expandable source rendering. -Tool rows are slots too — the standalone tool ring (`ToolViewRegistry`/`ctx.toolviews`/outlet) is retired. The chat entry declares the keyed `'conversation.chat.toolview'` hole (session scope; the key space is runtime-open); its render site dispatches per row via `entryKey: toolName` with `GenericToolCard` as the call-site `fallback`. The owner payload is the uniform `ToolRowOwnerProps` (`callId`/`toolName`/`block`/`openDetails`) and `ToolRowProps` pre-composes it with the session standard kit. A registrant is a plain plugin: `ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)` with `inject: ['slots', 'conversation']` as the load-order seam (apply mounts ConversationService after the chat registration, so the service being present guarantees the slot is declared); session differentiation happens inside the component (`useSessions` reading `parentId` — the bash sample is the third-party-posture exemplar). Trajectory/waterfall toolview slots share this shape and land with their own render sites (RendersCheck rejects a declaration nobody renders). +Tool rows are slots too — the standalone tool ring (`ToolViewRegistry`/`ctx.toolviews`/outlet) is retired. The chat entry declares the keyed `'conversation.chat.toolview'` hole (session scope; the key space is runtime-open); its render site dispatches per row via `entryKey: toolName` with `GenericToolCard` as the call-site `fallback`. The owner payload is the uniform `ToolRowOwnerProps` (`callId`/`toolName`/`block`/`openFile`) and `ToolRowProps` pre-composes it with the session standard kit. A registrant is a plain plugin: `ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)` with `inject: ['slots', 'conversation']` as the load-order seam (apply mounts ConversationService after the chat registration, so the service being present guarantees the slot is declared); session differentiation happens inside the component (`useSessions` reading `parentId` — the bash sample is the third-party-posture exemplar). Trajectory/waterfall toolview slots share this shape and land with their own render sites (RendersCheck rejects a declaration nobody renders). The todo surfaces are two registrations over that shape, both plain registrant plugins with `inject: ['slots', 'conversation']`. `TodoRow` takes the `'conversation.chat.toolview'` key `todo_write` and summarizes what the call attempted (`/ 已完成 · ` parsed from its args, falling back to the generic summary on malformed or wrongly-shaped model JSON, and keeping the generic dot for non-ok execution states so a cancelled call never reads as a completed update). `TodoDock` takes the `'conversation.input.dock'` list slot at `order: -1` — above the queue rows — and is the durable plan strip: it selects `todos` off the session snapshot and renders `TodoPanel`, which takes the plain list, hides itself while the list is empty, and collapses to a header of title plus `"/ tasks · in progress"` (status glyphs are the figma check / progress / dashed-pending set). The dock adapter owns the selection so the panel stays a pure function of its props; the persistent list lives here rather than in the row so the row stays one line. Anything the input-zone composer chain hides (a `conversation.composer` takeover such as ui-question's) hides the whole dock, this strip included. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index f8b6487870..eae9dfce2b 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -8,9 +8,9 @@ 视图环本身就是 slot:会话注册声明 `'conversation.view'` 列表 slot(Session scope),并将其列在 `children` 表中;ConversationRoot 通过 renderSlot share 渲染活跃配置项(`only: `);视图标签页从环账本的注册选项(`id`/`order`/`label`)投影而来。聊天视图是该包自身的环配置项;其他插件(ui-trajectory)通过普通的 `ctx.slots.register` 贡献标签页。先前包内的视图注册表(`registerView`/`ViewEntry`/`ConversationViewMap` 及 chrome 附加表)已退役,逐视图 chrome 则被拆入视图组件自身。 -通用工具行把内置的 bash、read、search、write、edit 和 run_code 名称归入专用视觉变体。文件系统变体会渲染 edit 图标和 `Write · ` 或 `Edit · ` 摘要,同时保留共享的行到详情交互。code 变体以模型撰写的 `description` 作摘要,展开后显示程序本身;其已记录的子调用经由同一个键控 toolview 空位渲染为始终可见的嵌套行(自定义注册和 GenericToolCard fallback 原样适用于子行),details 面板则会根据选中的子调用 id 解析出其完整记录的参数与完整输出。Cordis 生命周期工具复用这些通用变体,同时以统一的 Cordis 强调色呈现 `Inspect`、`Mount temporary Plugin` 和 `Unmount temporary Plugin`;mount 行保留 code 变体的可展开源码渲染。 +通用工具行把内置的 bash、read、search、write、edit 和 run_code 名称归入专用视觉变体。文件系统变体会渲染 edit 图标和路径摘要;该路径是悬停下划线链接,点击后通过宿主操作系统的默认应用打开文件(`host.openPath`,相对路径相对会话 cwd 解析)。工具行不再是整行点击目标,也不会打开 details 面板。code 变体以模型撰写的 `description` 作摘要,展开后显示程序本身;其已记录的子调用经由同一个键控 toolview 空位渲染为始终可见的嵌套行(自定义注册和 GenericToolCard fallback 原样适用于子行)。Cordis 生命周期工具复用这些通用变体,同时以统一的 Cordis 强调色呈现 `Inspect`、`Mount temporary Plugin` 和 `Unmount temporary Plugin`;mount 行保留 code 变体的可展开源码渲染。 -工具行同样是 slot:独立工具环(`ToolViewRegistry`/`ctx.toolviews`/outlet)已经退役。聊天配置项声明键控的 `'conversation.chat.toolview'` 空位(Session scope;key 空间在运行时开放);其渲染点逐行通过 `entryKey: toolName` 分发,并以 `GenericToolCard` 作为调用点 `fallback`。owner 载荷是统一的 `ToolRowOwnerProps`(`callId`/`toolName`/`block`/`openDetails`),`ToolRowProps` 则预先将其与 Session 标准工具包组合。注册方只是普通插件:`ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)`,以 `inject: ['slots', 'conversation']` 作为加载顺序 seam(apply 在聊天注册后挂载 ConversationService,因此服务存在即可保证 slot 已声明);Session 区分在组件内部完成(`useSessions` 读取 `parentId`,bash 示例是第三方姿态的范例)。Trajectory/waterfall 工具视图 slot 共享此形状,并随各自的渲染点落地(RendersCheck 会拒绝没有任何渲染方的声明)。 +工具行同样是 slot:独立工具环(`ToolViewRegistry`/`ctx.toolviews`/outlet)已经退役。聊天配置项声明键控的 `'conversation.chat.toolview'` 空位(Session scope;key 空间在运行时开放);其渲染点逐行通过 `entryKey: toolName` 分发,并以 `GenericToolCard` 作为调用点 `fallback`。owner 载荷是统一的 `ToolRowOwnerProps`(`callId`/`toolName`/`block`/`openFile`),`ToolRowProps` 则预先将其与 Session 标准工具包组合。注册方只是普通插件:`ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)`,以 `inject: ['slots', 'conversation']` 作为加载顺序 seam(apply 在聊天注册后挂载 ConversationService,因此服务存在即可保证 slot 已声明);Session 区分在组件内部完成(`useSessions` 读取 `parentId`,bash 示例是第三方姿态的范例)。Trajectory/waterfall 工具视图 slot 共享此形状,并随各自的渲染点落地(RendersCheck 会拒绝没有任何渲染方的声明)。 todo 两个面就是在该形状上的两个注册项,都是普通注册方插件,`inject: ['slots', 'conversation']`。`TodoRow` 占用 `'conversation.chat.toolview'` 的 `todo_write` key,摘要该次调用「试图写入」的内容(从其 args 解析出 `<已完成>/<总数> 已完成 · <进行中条目>`;模型 JSON 残缺或形状不对时回落到通用摘要;非 ok 执行状态保留通用状态点,使被取消的调用绝不读成一次已完成的更新)。`TodoDock` 以 `order: -1` 占用 `'conversation.input.dock'` 列表 slot(位于队列行之上),是常驻的计划条:它从会话快照中选取 `todos` 并渲染 `TodoPanel`,后者接收纯列表,在列表为空时自我隐藏,折叠时收成标题加 `"<已完成>/<总数> tasks · in progress"` 的表头(状态图标为 figma 的勾选/进行中/虚线未开始一组)。选取由 dock 适配器负责,因此面板保持为其 props 的纯函数;常驻列表放在此处而非行内,行才能保持单行。输入区 composer 链隐藏的一切(例如 ui-question 对 `conversation.composer` 的接管)也会隐藏整个 dock,包括这条计划条。 diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index f5e8e82d79..d6f61cb858 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -51,6 +51,8 @@ "devDependencies": { "@deepseek-ai/dsh-attachment": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-tool-todo": "workspace:^", "@deepseek-ai/dsh-client-ui-layout": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-slash": "workspace:^", diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 8f413f0100..bfef48e960 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -7,6 +7,7 @@ import type { ViewTab } from './contract/views.ts' import type { ChatViewInjected, ComposerBarInjected, ConversationInjected, ConversationSessionInjected, DetailsInjected, } from './contract/slots.ts' +import { resolveToolPath } from './contract/tool-call-model.ts' import { createChatStore } from './stores.ts' import { ConversationService } from './service.ts' import { InputHub } from './input/hub.ts' @@ -185,7 +186,10 @@ export function apply(ctx: Context): void { id: 'chat', order: 0, label: 'Chat', - children: { 'conversation.chat.toolview': { kind: 'keyed', scope: 'session' } }, + children: { + 'conversation.chat.toolview': { kind: 'keyed', scope: 'session' }, + 'conversation.chat.commandview': { kind: 'keyed', scope: 'session' }, + }, store: chatStore, inject: (sessionId: SessionId, actions: BoundActions): ChatViewInjected => { const conversation = ctx.get('conversation') @@ -196,6 +200,13 @@ export function apply(ctx: Context): void { actions.select(target) layout.openDetails() }, + openFile: (path) => { + const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd + void workspaces.openPath(resolveToolPath(cwd, path)).catch(() => { + // Host/OS open failures stay silent in the chat row; the native + // app surfaces its own error dialog when the path is unusable. + }) + }, loadOlder: () => { void scoped.loadOlder() }, loadImage: attachment => conversation.resolveImage(sessionId, attachment), } diff --git a/packages/client/ui-conversation/src/client/chat/ChatView.tsx b/packages/client/ui-conversation/src/client/chat/ChatView.tsx index f4c74100f4..870f2724c0 100644 --- a/packages/client/ui-conversation/src/client/chat/ChatView.tsx +++ b/packages/client/ui-conversation/src/client/chat/ChatView.tsx @@ -20,14 +20,14 @@ import { memo, useLayoutEffect, useMemo, useRef, useState, type ReactNode, } from 'react' import type { - CodeSubCall, ConversationNode, ConversationSnapshot, RunningToolCall, ToolResultNode, + CodeSubCall, CommandNode, ConversationNode, ConversationSnapshot, RunningToolCall, ToolResultNode, } from '@deepseek-ai/dsh-client-runtime/client' import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives' import type { ChatViewSlotProps } from '../contract/slots.ts' -import type { SelectionTarget } from '../contract/views.ts' import { deriveChatFlow, type ChatFlowItem } from './chat-flow.ts' import { AssistantMarkdown } from './AssistantMarkdown.tsx' +import { GenericCommandCard } from './GenericCommandCard.tsx' import { GenericToolCard } from './GenericToolCard.tsx' import { MessageItem } from './MessageItem.tsx' import type { ImageLoader } from './MessageImage.tsx' @@ -37,7 +37,7 @@ import css from './ChatView.module.css' const FOLLOW_THRESHOLD = 24 -type OpenDetails = (target: SelectionTarget) => void +type OpenFile = (path: string) => void /** The declared toolview hole's render share (stable framework binding, passed through memoized rows). */ type RenderToolRow = ChatViewSlotProps['renderSlot'] @@ -50,20 +50,18 @@ type UseConversation = SnapshotSelectorHook * top-level call (same registrations, same fallback), nested by the parent. * A started-but-unsettled sub-call arrives as the RunningToolCall shape and * renders the running state exactly as a native in-flight row. */ -const SubCallRow = memo(function SubCallRow({ renderSlot, node, onOpenDetails, selected, cwd }: { +const SubCallRow = memo(function SubCallRow({ renderSlot, node, openFile, selected, cwd }: { renderSlot: RenderToolRow node: CodeSubCall - onOpenDetails: OpenDetails + openFile: OpenFile selected: boolean cwd: string | undefined }) { const settled = 'kind' in node const toolName = settled ? node.call?.name ?? '' : node.name - const seq = settled ? node.seq : node.time const owner = useMemo(() => ({ - callId: node.callId, toolName, block: node, cwd, - openDetails: () => { onOpenDetails({ turnSeq: seq, callId: node.callId, toolName }) }, - }), [node, toolName, seq, cwd, onOpenDetails]) + callId: node.callId, toolName, block: node, openFile, cwd, + }), [node, toolName, openFile, cwd]) return (
{renderSlot('conversation.chat.toolview', owner, { @@ -80,15 +78,13 @@ const SubCallRow = memo(function SubCallRow({ renderSlot, node, onOpenDetails, s * renders its logged sub-dispatches as always-visible indented rows — * each one the same keyed-slot dispatch as a native top-level call. */ const CallRow = memo(function CallRow({ - renderSlot, callId, toolName, block, seq, onOpenDetails, selected, subCalls, selectedCallId, cwd, + renderSlot, callId, toolName, block, openFile, selected, subCalls, selectedCallId, cwd, }: { renderSlot: RenderToolRow callId: string toolName: string block: ToolResultNode | RunningToolCall - /** Surface seq for finalized results; the call's turn for running calls. */ - seq: number - onOpenDetails: OpenDetails + openFile: OpenFile selected: boolean /** `run_code` sub-dispatches in dispatch order (reference-stable per * parent; running entries settle in place); undefined for ordinary calls. */ @@ -99,9 +95,8 @@ const CallRow = memo(function CallRow({ cwd: string | undefined }) { const owner = useMemo(() => ({ - callId, toolName, block, cwd, - openDetails: () => { onOpenDetails({ turnSeq: seq, callId, toolName }) }, - }), [callId, toolName, block, seq, cwd, onOpenDetails]) + callId, toolName, block, openFile, cwd, + }), [callId, toolName, block, openFile, cwd]) return (
{renderSlot('conversation.chat.toolview', owner, { @@ -115,7 +110,7 @@ const CallRow = memo(function CallRow({ key={node.callId} renderSlot={renderSlot} node={node} - onOpenDetails={onOpenDetails} + openFile={openFile} selected={node.callId === selectedCallId} cwd={cwd} /> @@ -127,10 +122,10 @@ const CallRow = memo(function CallRow({ }) /** Consecutive tool results as one step-run group (uniform 16px rhythm). */ -const ToolGroup = memo(function ToolGroup({ renderSlot, results, onOpenDetails, selectedCallId, codeDispatches, cwd }: { +const ToolGroup = memo(function ToolGroup({ renderSlot, results, openFile, selectedCallId, codeDispatches, cwd }: { renderSlot: RenderToolRow results: readonly ToolResultNode[] - onOpenDetails: OpenDetails + openFile: OpenFile /** Only set when the selected call lives in THIS group, top-level or nested (memo economy). */ selectedCallId: string | undefined /** Sub-dispatch index off the snapshot (map reference is chunk-storm stable). */ @@ -147,8 +142,7 @@ const ToolGroup = memo(function ToolGroup({ renderSlot, results, onOpenDetails, callId={node.callId} toolName={node.call?.name ?? ''} block={node} - seq={node.seq} - onOpenDetails={onOpenDetails} + openFile={openFile} selected={node.callId === selectedCallId} subCalls={codeDispatches.get(node.callId)} selectedCallId={selectedCallId} @@ -159,6 +153,24 @@ const ToolGroup = memo(function ToolGroup({ renderSlot, results, onOpenDetails, ) }) +/** One command lifecycle row: keyed dispatch on the command name with the + * generic card as the render-site fallback (zero registration required). A + * run-less cross-window node has no name and always lands on the fallback. */ +const CommandRow = memo(function CommandRow({ renderSlot, node }: { + renderSlot: RenderToolRow + node: CommandNode +}) { + const owner = useMemo(() => ({ node }), [node]) + return ( +
+ {renderSlot('conversation.chat.commandview', owner, { + entryKey: node.name ?? '', + fallback: , + })} +
+ ) +}) + /** Turn loader: one row of four 2.5px pixels (half a notch above the StateDot * 2px cell, same blue) chasing left to right with a stepped trail — flat * keyframe holds, no tweening, no rotation. Phase offsets come from @@ -213,7 +225,7 @@ function StreamingTail({ useSession, onGrow, loadImage }: { * render through the declared keyed hole's renderSlot share). */ export function ChatView({ - useSession, useSessions, useStore, renderSlot, sessionId, openDetails, loadOlder, loadImage, + useSession, useSessions, useStore, renderSlot, sessionId, openFile, loadOlder, loadImage, }: ChatViewSlotProps) { const nodes = useSession(s => s.nodes) // Workspace root off the session list row: path summaries display relative to it. @@ -315,7 +327,7 @@ export function ChatView({ key={item.key} renderSlot={renderSlot} results={item.results} - onOpenDetails={openDetails} + openFile={openFile} selectedCallId={inGroup ? selectedCallId : undefined} codeDispatches={codeDispatches} cwd={cwd} @@ -334,6 +346,9 @@ export function ChatView({ /> ) } + if (node.kind === 'command') { + return + } /* v8 ignore next -- tool-result never reaches here: deriveChatFlow folds them into groups. */ if (node.kind === 'tool-result') return null return @@ -363,8 +378,7 @@ export function ChatView({ callId={call.callId} toolName={call.name} block={call} - seq={call.turn} - onOpenDetails={openDetails} + openFile={openFile} selected={call.callId === selectedCallId} subCalls={codeDispatches.get(call.callId)} selectedCallId={selectedCallId} diff --git a/packages/client/ui-conversation/src/client/chat/GenericCommandCard.tsx b/packages/client/ui-conversation/src/client/chat/GenericCommandCard.tsx new file mode 100644 index 0000000000..1dfea5488b --- /dev/null +++ b/packages/client/ui-conversation/src/client/chat/GenericCommandCard.tsx @@ -0,0 +1,38 @@ +// GenericCommandCard: the default command row — a stripped-down +// GenericToolCard rendering the dispatched command line and the settlement +// text. Supplied by the chat view as the keyed commandview slot's render-site +// fallback (an unregistered command name lands here); registrants may compose +// it as a base, feeding the same owner payload through. + +import { ToolRow } from './ToolRow.tsx' +import type { ToolRowState } from '../contract/tool-call-model.ts' +import type { CommandRowOwnerProps } from '../contract/slots.ts' +import { IconApiOutline14 } from '@deepseek-ai/dsh-client-ui-primitives' + +/** Node state → row state semantic (running while unsettled; outcome kind after). */ +function stateOf(outcome: CommandRowOwnerProps['node']['outcome']): ToolRowState { + if (outcome === null) return 'running' + return outcome.kind === 'error' ? 'error' : 'ok' +} + +export function GenericCommandCard({ node }: CommandRowOwnerProps) { + const text = node.outcome?.text + const summary = node.outcome === null + ? '执行中…' + : text ?? (node.outcome.kind === 'error' ? '命令失败' : '已完成') + // Display line rebuilt from the structured payload (args carries its own + // separator whitespace verbatim); a cross-window node whose run page fell + // out of the window has neither. + const title = node.name === null ? '命令' : `/${node.name}${node.args ?? ''}` + return ( + } + title={title} + summary={summary} + // Expandable only when the outcome text overflows a one-line summary. + body={text !== undefined && text.includes('\n') ? text : null} + state={stateOf(node.outcome)} + /> + ) +} diff --git a/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx b/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx index e5b5fb541b..7bd4f22b06 100644 --- a/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx +++ b/packages/client/ui-conversation/src/client/chat/GenericToolCard.tsx @@ -25,8 +25,9 @@ const VARIANT_ICONS: Record = { others: , } -export function GenericToolCard({ toolName, block, cwd, openDetails }: ToolRowOwnerProps) { +export function GenericToolCard({ toolName, block, cwd, openFile }: ToolRowOwnerProps) { const model = toolRowModel(toolName, block, cwd) + const singleFile = model.filePath !== undefined return ( ) } diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css index 018529961f..7e2ed4db21 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.module.css +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.module.css @@ -41,10 +41,9 @@ 90%, 100% { left: 100%; } } -/* Clickable rows keep only the cursor affordance — no hover fill. */ -.row[data-clickable] { +/* Expand-on-row (Think / code): pointer only — no row fill hover. */ +.row[data-expandable] { cursor: pointer; - border-radius: 6px; } .leading { @@ -143,6 +142,29 @@ button.leading { color: var(--dsw-alias-label-tertiary); } +/* File-tool path: same geometry as .summary; hover underline + pointer. */ +.fileLink { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + margin: 0; + padding: 0; + border: none; + background: none; + font: inherit; + text-align: left; + font-size: 14px; + line-height: 24px; + color: var(--dsw-alias-label-tertiary); + cursor: pointer; +} + +.fileLink:hover { + text-decoration: underline; +} + /* Expanded body: pad-left 22 indented gray text, no border, no fill. */ .body { padding: 4px 0 4px 22px; diff --git a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx index 5c5d059292..9395813910 100644 --- a/packages/client/ui-conversation/src/client/chat/ToolRow.tsx +++ b/packages/client/ui-conversation/src/client/chat/ToolRow.tsx @@ -2,9 +2,8 @@ // 16px leading slot (state dot / tool icon, chevron on hover or expanded) + title + // separator dot + FILL-truncated summary. Expanded body is indented gray text; // no inline output (full results live in the details panel). Expand state is -// component-local view state; row click hands the selection off to the owner. -// TODO(ux): converge every chat-tab tool row on in-place expansion for its -// expandable content, retiring the details-panel handoff where feasible. +// component-local view state. File-tool summaries are path links that open +// through the host; the row itself is not a details-panel control. import { useState, type KeyboardEvent, type MouseEvent, type ReactNode } from 'react' import clsx from 'clsx' @@ -26,8 +25,13 @@ export interface ToolRowProps { state: ToolRowState /** Makes the row itself the expand control instead of only its leading icon. */ expandOnRowClick?: boolean | undefined - /** Selection handoff (row click), already bound to this call by the owner. */ - onOpenDetails?: (() => void) | undefined + /** + * Filesystem path from tool args; when set with onOpenFile, the summary + * renders as a hover-underline link that opens the host default app. + */ + filePath?: string | undefined + /** Open the path with the host OS default application (already cwd-resolved). */ + onOpenFile?: ((path: string) => void) | undefined } /** Leading-slot state substitution: the tool icon yields to the terminal state @@ -50,10 +54,15 @@ export function ToolRow({ body, state, expandOnRowClick = false, - onOpenDetails, + filePath, + onOpenFile, }: ToolRowProps) { const [expanded, setExpanded] = useState(false) - const expandable = body !== null + // A row that names a single file keeps one interaction (open that path); + // args expand is off whether or not the open callback is wired yet. + const singleFile = filePath !== undefined + const fileLink = singleFile && onOpenFile !== undefined + const expandable = body !== null && !singleFile const open = expanded && expandable const rowExpands = expandable && expandOnRowClick const toggleExpand = () => { @@ -68,6 +77,10 @@ export function ToolRow({ event.preventDefault() toggleExpand() } + const openFile = (event: MouseEvent) => { + event.stopPropagation() + if (filePath !== undefined) onOpenFile?.(filePath) + } // Expandable rows preview the toggle on hover: the tool icon yields to a // down chevron (CSS swap on .row:hover); state dots still take precedence. const collapsedIcon = expandable @@ -85,11 +98,11 @@ export function ToolRow({
{expandable && !rowExpands ? ( @@ -110,7 +123,17 @@ export function ToolRow({ {!open && ( <> - {summary} + {fileLink ? ( + + ) : ( + {summary} + )} )}
diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index ca17d04f62..f73ebf4560 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -4,7 +4,7 @@ import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { InjectFace, MaybeSnapshotSelectorHook, PropsRenderSlots, PropsRuntime, PropsStore, SnapshotSelectorHook, } from '@deepseek-ai/dsh-client-ui-slots' -import type { ConversationSnapshot, ObservableSnapshot, PendingInteraction, SessionId, ToolCallBlock, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' +import type { CommandNode, ConversationSnapshot, ObservableSnapshot, PendingInteraction, SessionId, ToolCallBlock, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { ComposerKeyboard, InputActions, InputNotice, InputState } from '../input/contract.ts' import type { createChatStore } from '../stores.ts' @@ -42,6 +42,15 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * `fallback` for unregistered tools. */ 'conversation.chat.toolview': { kind: 'keyed'; scope: 'session'; owner: ToolRowOwnerProps } + /** + * The chat view's per-command row hole: keyed dispatch on the command + * name (`command/run.name`; a run-less cross-window node has none and + * always lands on the fallback). Declared by the chat view entry; the + * render site dispatches via `entryKey: name` with GenericCommandCard as + * the `fallback` — a slash command renders durably with zero + * registration, and a domain upgrades by registering one row component. + */ + 'conversation.chat.commandview': { kind: 'keyed'; scope: 'session'; owner: CommandRowOwnerProps } /** * The composer takeover chain: entries are selector-routed replacements * of the default InputBar. Declared by this package's 'conversation' @@ -154,8 +163,11 @@ export interface ToolRowOwnerProps { block: ToolCallBlock /** Session workspace root; path summaries display relative to it. */ cwd?: string | undefined - /** Open the details panel for this call (session-level facility, supplied by the view). */ - openDetails: () => void + /** + * Open a tool-arg filesystem path with the host OS default application. + * The chat view resolves relative paths against the session cwd. + */ + openFile: (path: string) => void } /** @@ -167,6 +179,22 @@ export interface ToolRowOwnerProps { */ export type ToolRowProps = PropsRuntime<'conversation.chat.toolview'> +/** + * Owner share of the per-command row slot: the frozen {@link CommandNode} + * slice off the snapshot (cache-stable reference — memo premise). The node + * carries the whole lifecycle (structured name/args, pairing id, + * outcome-or-executing), so a + * registrant needs no second data channel; domain state arrives through its + * own projection cell. + */ +export interface CommandRowOwnerProps { + /** Folded command lifecycle node (run + optional done). */ + node: CommandNode +} + +/** Full props of a registered command-row component (same shape rule as {@link ToolRowProps}). */ +export type CommandRowProps = PropsRuntime<'conversation.chat.commandview'> + /** * Base props of a conversation view entry: the framework standard kit for the * session-scope 'conversation.view' slot (useSession narrowed to the @@ -302,14 +330,19 @@ export type ConversationSessionSlotProps = export interface ChatViewInjected { /** Selection write + details panel opening in one gesture (store action + layout orchestration). */ openDetails: (target: SelectionTarget) => void + /** + * Open a tool-arg filesystem path with the host OS default application + * (relative paths resolve against the session cwd). + */ + openFile: (path: string) => void loadOlder: () => void /** Resolve a session-authorized historical image for inline display. */ loadImage: (attachment: ImageAttachmentRef) => Promise } -/** Full chat-view component props: runtime share & the declared toolview hole's render share & store share & injected share. */ +/** Full chat-view component props: runtime share & the declared toolview/commandview holes' render share & store share & injected share. */ export type ChatViewSlotProps = - PropsRuntime<'conversation.view'> & PropsRenderSlots<'conversation.chat.toolview'> + PropsRuntime<'conversation.view'> & PropsRenderSlots<'conversation.chat.toolview' | 'conversation.chat.commandview'> & PropsStore & ChatViewInjected /** diff --git a/packages/client/ui-conversation/src/client/contract/tool-call-model.ts b/packages/client/ui-conversation/src/client/contract/tool-call-model.ts index c7db85b0aa..04a8c66d40 100644 --- a/packages/client/ui-conversation/src/client/contract/tool-call-model.ts +++ b/packages/client/ui-conversation/src/client/contract/tool-call-model.ts @@ -62,6 +62,12 @@ export interface ToolRowModel { variant: ToolRowVariant title: string summary: string + /** + * Filesystem path from args (`path` / `file_path`) when the row is a file + * tool; absent for URL reads and non-file tools. The chat view resolves + * relative values against the session cwd before opening. + */ + filePath: string | undefined /** Expanded-body text (pretty args); null = row not expandable. */ body: string | null state: ToolRowState @@ -121,6 +127,35 @@ function deriveSummary(variant: ToolRowVariant, argsRaw: string): string { return firstLine(argsRaw) } +/** Path keys only — never `url` (web_fetch lands on the read variant). */ +const FILE_PATH_KEYS = ['path', 'file_path'] as const + +/** File-tool variants whose summary may be an openable workspace path. */ +const FILE_PATH_VARIANTS: ReadonlySet = new Set(['read', 'write', 'edit']) + +function deriveFilePath(variant: ToolRowVariant, argsRaw: string): string | undefined { + if (!FILE_PATH_VARIANTS.has(variant)) return undefined + const parsed = parseArgs(argsRaw) + if (typeof parsed !== 'object' || parsed === null) return undefined + const picked = pickString(parsed as Record, FILE_PATH_KEYS) + return picked === undefined ? undefined : firstLine(picked) +} + +/** + * Resolve a tool-arg path against the session cwd for host.openPath. + * Absolute POSIX/Windows paths pass through; relative paths join under cwd. + * @param cwd - session working directory (may be absent for ungrouped sessions). + * @param path - path as carried in tool args. + * @returns a host-facing path string. + */ +export function resolveToolPath(cwd: string | undefined, path: string): string { + if (path.startsWith('/') || /^[A-Za-z]:[/\\]/.test(path) || path.startsWith('\\\\')) return path + if (cwd === undefined || cwd === '') return path + const base = cwd.replace(/[/\\]+$/, '') + const rel = path.replace(/^[/\\]+/, '') + return `${base}/${rel}` +} + function deriveBody(variant: ToolRowVariant, argsRaw: string): string | null { if (argsRaw === '') return null const parsed = parseArgs(argsRaw) @@ -159,6 +194,7 @@ export function toolRowModel(toolName: string, block: ToolCallBlock, cwd?: strin variant, title: toolTitle ?? VARIANT_TITLES[variant], summary, + filePath: deriveFilePath(variant, argsRaw), body: deriveBody(variant, argsRaw), state, } diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 803f163d28..9a4cbce406 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -13,7 +13,8 @@ export type { } from './contract/views.ts' export type { ToolCallBlock } from './contract/tool-call-model.ts' export type { - ChatStore, ChatViewInjected, ChatViewSlotProps, ComposerAttachment, ComposerBarInjected, ComposerChainProps, + ChatStore, ChatViewInjected, ChatViewSlotProps, CommandRowOwnerProps, CommandRowProps, + ComposerAttachment, ComposerBarInjected, ComposerChainProps, ConversationInjected, ConversationSessionInjected, ConversationSlotProps, ConvViewOwnerProps, ConvViewProps, DetailsInjected, DetailsSlotProps, EmptyWorkspaceOwnerProps, ToolRowOwnerProps, ToolRowProps, diff --git a/packages/client/ui-conversation/src/client/skeleton/TodoPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/TodoPanel.tsx index 16edc423c0..b7ef46271a 100644 --- a/packages/client/ui-conversation/src/client/skeleton/TodoPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/TodoPanel.tsx @@ -8,7 +8,11 @@ import { useId, useState } from 'react' import type { Context } from 'cordis' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { TodoItem } from '@deepseek-ai/dsh-client-runtime/client' +// The domain's client-namespace pure-type outlet: one import edge delivers +// the `todos` projection-key merge (single source, no consumer-side restated +// declare) and the payload type. Type-only by construction — the outlet is +// free of host value imports, so no host Context merge enters this program. +import type { TodoItem } from '@deepseek-ai/dsh-tool-todo/client' import { IconChevronDownOutline14, IconChevronUpOutline14 } from '@deepseek-ai/dsh-client-ui-primitives' import css from './TodoPanel.module.css' @@ -115,10 +119,10 @@ export function TodoPanel({ todos }: TodoPanelProps) { /** Full props of a dock entry: InputZone owner share + session standard kit + global seat. */ export type TodoDockProps = PropsRuntime<'conversation.input.dock'> -/** Dock adapter: selects the plan off the session snapshot and hands the strip a plain list. */ -export function TodoDock({ useSession }: TodoDockProps) { - const todos = useSession(s => s.todos) - return +/** Dock adapter: reads the host-computed 'todos' projection (whole list; absent or null renders nothing). */ +export function TodoDock({ useProjection }: TodoDockProps) { + const todos = useProjection('todos') + return } /** diff --git a/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css b/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css index a79faf30f1..2e5d601e62 100644 --- a/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css +++ b/packages/client/ui-conversation/src/client/toolviews/bash-sample.module.css @@ -7,8 +7,6 @@ align-items: center; height: 24px; min-width: 0; - cursor: pointer; - border-radius: 6px; } /* Running sweep glare — same deepsuite ShimmerText pattern as ToolRow. */ diff --git a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx index fbb1104eca..d972a35274 100644 --- a/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/bash-sample.tsx @@ -30,7 +30,7 @@ function stateStatus(state: ToolRowState): string | null { } /** Bash row: icon + Bash · {description}, matching the shared ToolRow chrome. */ -export function BashRow({ toolName, block, openDetails, sessionId, useSessions }: ToolRowProps) { +export function BashRow({ toolName, block, sessionId, useSessions }: ToolRowProps) { const model = toolRowModel(toolName, block) const isChild = useSessions(list => list.byId[sessionId]?.parentId !== undefined) const status = stateStatus(model.state) @@ -40,8 +40,6 @@ export function BashRow({ toolName, block, openDetails, sessionId, useSessions } data-sample={isChild ? 'bash-scoped' : 'bash-global'} data-variant="bash" data-state={model.state} - data-clickable - onClick={openDetails} > {leadingFor(model.state)} {status !== null && {status}} diff --git a/packages/client/ui-conversation/src/client/toolviews/todo-row.module.css b/packages/client/ui-conversation/src/client/toolviews/todo-row.module.css index 1a1b142b3a..8e59b36625 100644 --- a/packages/client/ui-conversation/src/client/toolviews/todo-row.module.css +++ b/packages/client/ui-conversation/src/client/toolviews/todo-row.module.css @@ -6,8 +6,6 @@ align-items: center; height: 24px; min-width: 0; - cursor: pointer; - border-radius: 6px; } .leading { diff --git a/packages/client/ui-conversation/src/client/toolviews/todo-row.tsx b/packages/client/ui-conversation/src/client/toolviews/todo-row.tsx index a47322b614..67732a3650 100644 --- a/packages/client/ui-conversation/src/client/toolviews/todo-row.tsx +++ b/packages/client/ui-conversation/src/client/toolviews/todo-row.tsx @@ -5,7 +5,6 @@ // durable list itself renders in the TodoPanel above the composer, so the // row stays one line. Chrome matches ToolRow (figma 780:53675). -import type { KeyboardEvent } from 'react' import type { Context } from 'cordis' import { IconChecklistOutline16, StateDot } from '@deepseek-ai/dsh-client-ui-primitives' import type { ToolRowProps } from '../contract/slots.ts' @@ -51,29 +50,18 @@ function leadingFor(state: ToolRowState) { } } -/** One-line plan update row (click opens the raw args in details). Non-ok - * execution states keep the generic row's dot semantics — a cancelled call - * wrote no todo/write, so it must not read as a completed update. */ -export function TodoRow({ toolName, block, openDetails }: ToolRowProps) { +/** One-line plan update row. Non-ok execution states keep the generic row's + * dot semantics — a cancelled call wrote no todo/write, so it must not read + * as a completed update. */ +export function TodoRow({ toolName, block }: ToolRowProps) { const model = toolRowModel(toolName, block) const argsRaw = ('kind' in block ? block.call?.argsRaw : block.argsRaw) ?? '' const summary = summarize(argsRaw) ?? model.summary - // Button semantics, not a