* ✨ feat(session): persist and synchronize read state * 🌐 fix(client): complete Japanese labels after base update * 📝 docs: refresh session read-state dependency graph * 🧪 test(web): align session menu and read-state snapshots * 🌐 fix(session): complete Japanese plugin metadata * 🧪 test(web): distinguish unread from pending user input * 🐛 修复会话阅读状态的故障隔离与生命周期 * 🐛 修复阅读状态依赖检查并补齐自动已读覆盖 * 🐛 恢复会话绿点并移除未读标题加粗 * ♻️ Keep shared session reading state in Host memory * 🌐 Complete reading-state metadata for supported locales * 📝 Refresh module graph after removing storage dependency * 🧹 Move storage dependency policy out of memory-only reading * 🐛 Wait for sidebar catalog before replay navigation * 🔧 Give Host TypeScript checks 8 GiB of heap * ✅ Align Host heap checks and Windows diagnostics * ♻️ Keep CI repairs outside the session reading PR * 🐛 Show failed unread turns with an error indicator * 🔧 Adjust npm layout budget for the reading package * 🧪 Scope projection stream assertions to observed units * 🧪 Scope permission and title assertions to their projections * ♻️ Simplify session reading updates to explicit positions * 🐛 Align session reading package with release version * 🧪 Load reading state in LiveShare viewer fixtures * 🧹 Remove persistence-only type link from memory PR * 🧪 Align context menu expectations with reading actions * 🐛 Sync reading package with the release version * 🧪 Include turn boundaries in session summary expectations * ♻️ Derive reading failure facts from Host events instead of a projection The reading service took each completion from the Agent turn-boundary projection, which forced a stateVersion bump and put that projection's whole internal state on the wire for every Session list row. The service now records `turn/end` itself, so `core/agent` and the persisted projection schema are untouched. History that ended before the service started raises no reminder, which keeps "existing history reads as read" without a startup scan. The failure flag therefore describes only turns this Host observed: marking a Session whose last turn failed before a restart shows the ordinary unread reminder. * 🐛 Preserve manual unread until explicit Session interaction * 🧪 Align cold Session reading snapshot with unloaded title * 🔖 chore(session): align session-read-state with 0.2.2-rc.2 Master moved the root and every released manifest to 0.2.2-rc.2, but the new dsh-session-read-state package still declared 0.2.2-rc.1, failing constraints, verify-version-sync, verify-npm-install-layout, and release:verify after the master merge. * ♻️ refactor(gateway): recognize Remote stream carrier loss by error code RemoteStream now decides whether a generation end or failure is a retryable carrier loss by the stable code 'gateway/carrier-lost' instead of `instanceof RemoteStreamCarrierError`. RemoteStreamCarrierError keeps working and carries that code, so existing callers are unchanged, while a Client feature package can return a coded Error from `ended` without importing the class. The new RemoteStreamCarrierFailure type describes such errors; terminal-controller classifies disconnects the same way. * ♻️ refactor(session): move Session reading into ui-session-status Fold the reading feature into the single package packages/client/ui-session-status and delete session-read-state. - Host face: SessionStatusService keeps in-memory reading records and serves the sessionStatus Remote namespace (mark, follow) with session-status/* error codes; its service key is registered only for Gateway discovery and is not declared on Context. - Client face: a package-internal reading model follows the Host stream through RemoteSnapshotStream; ctx.uiSession.sessionStatus folds the records into completionUnread and completionFailed and exposes mark and readingReady; main-view acknowledgement and the session-status/read-intent event live here. No reading service or type is exported. - verify-client-packages lets a packages/client feature package request packages/api rows through dsh.client.external; feature-to-feature requests stay rejected. - ui-workspace, ui-conversation, bundles, remotes, LiveShare, the client test runtime, docs, Agent Notes, and the upgrade guide follow. * ♻️ refactor(session): clear manual unread only when the main view switches to the Session Remove the session-status/read-intent event. ui-session-status now clears an existing manual unread mark when the main view switches to a different Session, including the first selection after a page load, once the reading baseline is ready and the body arrives. Window focus, visibility changes, a replaced binding for the same Session, and activity in the open Session preserve manual unread. ui-conversation returns to master (only the ui-session-status client tsconfig reference remains), and ui-workspace navigation no longer emits the event. Tests, the session-reading Web e2e case, READMEs, and the reading Agent Note follow the new rule. * 🐛 fix(session): address the Session status review findings - Open the reading stream only while ctx.remoteAccess allows sessionStatus/follow, so a LiveShare viewer opens no owner-only stream, keeps readingReady false, and logs no synchronization failure; access changes start or stop the stream. - Hide the unacknowledged completion of the Session the visible, focused main view retains; manual marks stay visible, completionFailed follows completionUnread, and the reminder returns on blur, hiding, or a switch. - Declare ctx.sessionStatus on Context and restore its SERVICE_PAGE and SERVICE_ROLES entries; the service and SessionRead* types document on docs/subsystems/web-client.md, which now owns the reading section with the failed field. - Document that a Host plugin reload can leave the Client with a terminal error until a page reload; drop the redundant types import and the unused publish() result. - Archived Sessions read as read and offer no reading mark in the row menu or the toggle-read shortcut. - session.toggleRead names the open dialog, open panel, or archived Session that blocks it instead of asking to select a Session. - isRemoteStreamCarrierFailure rejects a RemoteError from the Host even when it carries gateway/carrier-lost; the code is Client-local. - ./types is types-only like ui-trajectory, and files no longer ship lib/types JavaScript. * 🐛 fix(session): close the remaining Session status review gaps - The Gateway Client exports isRemoteStreamCarrierFailure, and the terminal view uses it, so a Host RemoteError carrying the carrier code shows as failed rather than disconnected. - Each access grant's reading stream carries a token: frames a revoked or superseded stream still delivers are discarded, and cleanup waits for disposal before leaving reading unavailable unless a newer grant is active. - The status table hides the viewed Session's natural reminder only while that Session is open; the panel case is a documented limitation. - The README limitation and the upgrade guide state that only the main-view switch rule, including a reload restore, clears manual unread automatically. - Add the missing blank line before the next heading in the web-client reading section. * ♻️ refactor(session): install reading under the Session status table - apply returns to master's form plus one line: UiSessionStatus is the root, published as the useSessionStatus source, and installReading() from the new src/client/read.ts follows Host reading records into it. UiSessionStatus takes master's three constructor parameters and creates its own SessionReadModel as the package-internal `reading` member; installSessionStatus is removed and acknowledge.ts stays a separate file. - The viewed Session's snapshot subscription republishes the table only when its openState changes, so streamed events do not rebuild it. - Remove the obsolete Dev Note sentence about failure outcomes. - session.toggleRead passes when the Peer may not mark reading, matching the row menu, and reports readingUnavailable only while unsynchronized. --------- Co-authored-by: imccyu <[email protected]> Co-authored-by: imccyu <[email protected]>
18 KiB
Web Client architecture
English | 中文
The Web Client is a browser-side Cordis application assembled from independently loaded plugins. Its architecture has four reusable foundations: Client Modules loads the plugin graph, the API Gateway provides typed Host communication, Slots composes React UI, and Conversation turns a Session history window into target-owned views. This page connects those systems and defines where Client models and feature packages belong.
Keyboard shortcuts owns window-local command registration and physical-key dispatch; the shortcut reference presents available commands and local input actions. Command owners declare each runtime/platform default and share their existing actions with mouse controls. The shared modal primitive arbitrates top-layer Escape and restores focus.
Layers and ownership
| Layer | Main owners | Responsibility |
|---|---|---|
| Host application | business services and packages/api/*-controller Host entries |
Own authoritative state, persistence, mutation ordering, access policy, and stream production. |
| Transport and API assembly | client/connection, api/gateway, api/remotes |
Establish a Client generation, expose generated ctx.remote methods and streams, forward selected Cordis events, and carry cancellation and results. |
| Client models | api/session-controller/client, api/workspace-controller/client |
Maintain React-free mirrors of Host state, resolve stream/unary races, own object identities and subscriptions, and expose narrow command services. |
| UI adapters | client/ui-session, client/ui-workspace |
Convert model observables into root or Provider-bound Session Slot sources and own view-level navigation and status policy. |
| Conversation data | client/ui-conversation, target packages such as ui-chat and ui-trajectory |
Assemble standard events and compact historical Assistant runs into independent target snapshots and own the shared conversation shell and input flow. |
| Composition and rendering | client/ui-slots, client/ui-renderer, client/ui-layout, feature UI packages |
Declare extension locations, derive component props, bind observables to React hooks, and mount the final tree. |
The dependency direction is Host state → Remote transport → Client model → UI adapter → Conversation or presentation → Slots → React. User actions travel back through callbacks that close over an injected Client service or generated Remote namespace. A presentation component never receives Cordis ctx, a transport object, or another feature plugin's implementation.
Browser boot
The Host writes the composed WebBootGraph to window.__DSH_BOOT__ and installs the browser module-loader facade before parser-preloaded scripts execute. The module system is a lazy CommonJS table: loading a bundle registers its factory, while materializing an entry runs the factory with synchronous require over platform modules and declared dynamic dependencies.
The Web boot kernel creates the module system, prefetches immediately entries, mounts the vendored Cordis Loader, and creates every graph entry. Cordis service injection determines activation; module graph order determines only whether synchronous imports can be materialized. After the complete roster reaches a settled state and the boot audit accepts it (an inactive entry on the browser required list rejects startup; other inactive entries produce one console warning), ui-renderer hydrates the framework-free boot DOM and calls the sole context-level renderSlot('root') operation. Client Modules owns the graph, bundle route, cache revision, and loader details.
Remote communication
Host business services annotate callable methods with Typert Remote decorators. Host generation emits strict descriptors, runtime codecs, declaration merges, and source maps. The Client-side api-remotes assembly selects those generated contributions and mounts concrete methods under ctx.remote.<namespace> and Session-scoped agentCtx.remote.<namespace>. Feature packages depend on the generated service face, not the Gateway implementation or a Host package's runtime entry.
The Connection owns request URL resolution, correlation, the /api carrier, trust checks, exact Fetch routes, and connection generations. API Gateway owns Remote dispatch, cancellation, logical streams, and selected Host event forwarding. Controller operations belong on generated Remote methods or explicit Remote streams; feature-owned downloads register exact Fetch routes. The API Gateway reference defines generation and invocation, while the Connection README defines the physical carrier and trust policy.
The internal $events logical stream is the Connection generation source. Its opening ready frame carries the Host home used for path display and establishes the generation after Host listeners are attached, before any controller begins a baseline read. ctx.remote.$on() delivers allowlisted ordinary events to the root Client Context and scoped waterfall events to the resolved Session Context; a waterfall listener returns a result, calls next(), or rejects.
Client models
Each API controller package owns a paired Host and Client face. The Host side owns authoritative mutation and stream production. The Client side owns an identity-stable, React-free model over the same generated wire types and exposes observable snapshots plus commands. UI packages consume these Client services and do not reproduce transport state in component stores.
Sessions
api/session-controller exposes Host commands for list, search, creation, prompt, queue, cancellation, pagination, and follow/control streams. Its Client side is organized as ClientSessions → SessionManager → Session:
ClientSessionsprovidesctx.sessions, owns references, source counts, Session scopes, and stableSessionBindingobjects, and projects catalog state without selecting a global current Session.SessionManagerowns the list baseline, live list/control updates, lazy Session instances, projection stores, subagent catalogs, and conflict ordering between pulls and later updates.- Each
Sessionowns one contiguous logical-event window represented bySessionEventLikeEntryvalues, paging, follow, prompt/control state, and the observable snapshot consumed by adapters.
The durable event path opens follow(), whose first frame contains the current header, tail page, cursor, and complete projection baseline. History records have an explicit event or chunks discriminator and an aligned inner event; the journal validates each inclusive logical sequence range before the Client retains the records as SessionEventLikeEntry values without per-record conversion. Each physical generation atomically replaces the retained window from that snapshot; standard live events then append by sequence. page() is reserved for older history and gap repair. The transient control stream starts every generation with a complete baseline and then applies projection updates.
Workspaces
api/workspace-controller keeps Workspace mutation policy and the authoritative follow feed on the Host. ClientWorkspaceModel owns browser rows, Workspace order, archived and pinned Session id arrays, command echoes, and stream/unary race resolution. Every stream generation starts with a complete baseline followed by upsert, remove, order, archived, and pinned increments; reconnect replaces the model from the new baseline. WorkspaceController exposes that model as ctx.workspaces, while ui-workspace contributes useWorkspaces and navigation callbacks. The sidebar's ArchivedFilter controls default-hidden, shown, or archived-only rows in lists and search. Archived rows retain their ordering slots, render grayed, and cannot open until restored through the row or search-result Unarchive action. Restoration calls workspace.unarchiveSession, and its complete archive set reaches Clients through the unary response and archived increment. Session display order stays browser-local and includes hidden archives; pinning moves a Session within that full order, while unpinning does not restore its earlier position.
This pairing is not a second source of business truth. Host controllers decide durable state and mutation outcomes; Client models maintain the latest usable local projection, preserve object identity where useful to rendering, and encode how delayed responses and replacement baselines merge.
Conversation and presentation
Web and desktop share the Coding Tools preference. It controls diagnostic Views, available preset choices, changed-file cards, and the builtin HTML preview policy without changing Session records.
ui-session installs the Session scope adapter and publishes useSessions, useSessionRetainInfo, useSessionAccess, useSession, sessionId, useProjection, and the Session-scope useAccess over the remote-access Client service. SessionProvider inherits an outer binding or binds an explicit SessionReference, so concurrent subtrees can target different Sessions. ui-session-status publishes useSessionStatus from the ctx.uiSession.sessionStatus table of running state, the effective pending interaction, and reading reminders that its Host face keeps for every Client of one Host. Domain adapters add further standard sources without putting React hooks on the model objects.
ui-conversation binds once to each SessionBinding.eventSource. Its event registry correlates durable Session events and Client-only assistant/live-chunk updates into stable business Contexts, and its view registry materializes target snapshots. Chat Assistant, Trajectory Assistant, and Turn Tail interpret both live chunks and the compact streams embedded in durable settlements, so reconnect and paged history reproduce the same Assistant state without durable token rows. ui-chat and ui-trajectory register separate Definitions and builders: they may interpret the same event family, but they do not import or share each other's final display model. The shell selects a registered view and passes its snapshot through standard hooks and Slots. Conversation defines Context identity, replay, Location data, target builders, and keyed renderers.
ui-slots provides the typed registry and lifecycle ledger; ui-renderer is the only package that binds bare observables through useSyncExternalStore, owns React contexts, and renders the root tree. Feature components receive framework hooks, owner props, store actions, and explicit injection through their derived props. Web Client Slots lists those inputs, extension APIs, and the current Slot hierarchy.
Data paths
| Path | Sequence |
|---|---|
| durable Session display | Host Session log → packed Remote follow/page history → Client SessionEventLikeEntry window → Conversation Contexts → target snapshot (chat, trajectory, or another registered target) → Slot view → React |
| transient Session control | Host control baseline → Remote snapshot stream → SessionManager projection stores → Session and list snapshots → standard hooks → components |
| Background jobs | Host job registry → job.list / job.follow → ClientJobs roster and output views → job list and panels |
| Workspace state | Host Workspace baseline and increments → ClientWorkspaceModel → ctx.workspaces.list → useWorkspaces → sidebar, hero, and navigation entries |
| scoped interaction | Host Cordis waterfall → API Remotes $events → ctx.remote.$on() on the Session Context → owning UI package → result or next() |
| user command | component callback → registration inject face or Slot owner → ctx.sessions, ctx.workspaces, or generated scoped Remote → Host Controller → authoritative update → stream or event projection back to the Client |
Reconnection
Physical and logical recovery are separate. Gateway mux restores the physical WebSocket; each RemoteStream reopens its own logical source when the Connection publishes a usable generation. A carrier failure is retryable, while a business error, malformed opening item, or protocol violation is terminal for the owning logical stream.
Recovery follows the data's semantics:
- A durable Session journal validates logical sequence ranges and replaces its window from every generation's opening snapshot;
page()supplies older history and repairs any later range gap. - Session control and Workspace streams retain the last published value while disconnected, then atomically replace it from a fresh opening baseline.
- Ordinary forwarded notifications are not replayed. Stateful domains need a baseline, cursor, or explicit query; scoped waterfalls retain their own request lifetime.
There is no monolithic Client Runtime, HostFrame, events.mux, events.host, or universal resync() API. The Connection exposes generation state, Gateway owns logical stream supervision, and each Client model defines replacement or resume semantics appropriate to its data.
Reading reminders
Session status holds read acknowledgements and explicit unread marks in Host memory, outside the conversation log. Its Host Remote service sends complete reconnect baselines and committed changes; its Client plugin folds them into the ctx.uiSession.sessionStatus status table and acknowledges loaded completions in the visible, focused main view. Reading state does not change model history.
SessionReadState
A whole reading record names its sessionId, latest completedTurn, whether that turn failed with an execution error this Host observed, acknowledged readTurn, and manualUnread flag. A Session is unread when the flag is set or its latest ended turn exceeds the acknowledged turn.
mark(sessionId, action) updates one Session in Host processing order. Only the ordered subscription updates Client records. The service records turn/end events itself, including whether that turn failed.
SessionReadAction
An unread action sets the manual flag. A read action clears it and advances the read position through its throughTurn; an acknowledge action advances that position without changing the flag. Positions never move backwards or beyond the Host's latest completed turn. Mutation replies report success or failure without echoing a record.
SessionReadFrame
A follow generation starts with type: 'baseline' and every accessible record in items. Each later type: 'changed' carries one complete committed state. Reconnection replaces the previous generation's records.
Package boundaries
Feature plugin packages may share declarations through import type; they do not runtime-import or re-export another feature plugin's values. Cross-package behavior uses injected Cordis services, and cross-package UI uses Slots. Target-specific Conversation Definitions, projection helpers, and final view data stay with their target package even when Chat and Trajectory intentionally implement parallel logic.
Shared runtime values need a narrow static owner with no feature lifecycle, such as client/store, ui-primitives, or a browser-safe utility package. Transport and generated API assembly may import runtime contributions because assembling one protocol is their explicit responsibility. A feature package may request the runtime values of a row under packages/api/ through dsh.client.external, but never another feature plugin's row.
Use the four detailed references according to the extension being added:
- Client Modules for package discovery, loading, shared module identities, and boot order.
- API Gateway for Host methods, generated Remote contributions, streams, and forwarded events.
- Web Client Slots for components, hooks, stores, injection, and placement.
- Conversation for durable event correlation, target snapshots, and Chat or Trajectory view contributions.
Cordis API
Generated from source by scripts/gen-cordis-catalog.ts (verified fresh by pnpm run verify-cordis-catalog in doc-sync; regenerate with pnpm run gen-cordis-catalog) — the language sides differ only in locale-specific paired document paths. Signature blocks use a ts cordis-catalog fence and keep the original source JSDoc; dispatch modes are defined in the primer, and the framework-inherited ctx API lives in cordis-api/inherited.md.
ctx.sessionStatus — SessionStatusService
Shared owner reading records; no reading operation changes model history.
/**
* Update one Session; read positions advance only through Client-observed completions.
* @param sessionId - Session identity.
* @param action - Explicit reminder change or automatic read-position acknowledgement.
* @throws RemoteError when closing, the Session is missing, or its metadata cannot be read.
*/
@Remote async mark(sessionId: SessionId, action: SessionReadAction): Promise<void>
/**
* Follow accessible reading records; every connection starts with a complete baseline.
* @param signal - generation cancellation.
* @returns the baseline and whole-record changes, filtered by Session access.
* @throws RemoteError when the service is closing.
*/
@Remote({ mode: 'stream' }) async *follow(signal: AbortSignal): AsyncIterable<SessionReadFrame>
Types: SessionId