Merge remote-tracking branch 'origin/master' into worktree/context-source-cards

# Conflicts:
#	packages/client/runtime/README.i18n.yaml
#	packages/client/ui-conversation/README.i18n.yaml
This commit is contained in:
creatixchu
2026-08-06 11:57:17 +08:00
100 changed files with 1065 additions and 837 deletions

View File

@@ -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/runtime/README.md
README.md: 45ca8d41bb6d3557cd1e476d51f4470ce73484e8
README.zh.md: 27fd9c8bfb168e85762c2d03ce7fc13d39977a33
README.md: 8ac29a4258bbd7456b20c61e547d48c570e84d27
README.zh.md: 0e065e43ecc571e68d3976d2100eb43959cb2e3d

View File

@@ -4,6 +4,12 @@ English | [中文](README.zh.md)
Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects and the Chat-facing list, scope, and event-window state; SessionHistoryService lazily owns independent raw-history ledgers for inspection consumers, loading the current tail first and prepending one older page only when its consumer requests it. Each history snapshot exposes the raw window's absolute base sequence so a consumer detects a prepend even when the page adds no surface-visible node. WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, default-target derivation, and the New Session blank-reuse entry (`connectWorkspace`). The runtime fans the shared Host stream into the Session, Workspace, and activated history owners without routing inspection state through Session or SessionManager, and bridges the registry-invalidation frames to typed ctx events (`commands/changed`, `settings/changed`, `credentials/changed`, `models/changed`) so surface caches refetch without touching the stream. Client sessions are always Host-born (Session+Agent+cwd in one `session.create`); the client holds no pre-entity session state — a session's Agent scope (the client mirror of host dsh-scope, keyed by the shared agent/session id) is born when its row enters the list mirror and dies with the prune. Contract: api-contracts v3 §4. Each `Session` holds a generic `ProjectionValueStore` seeded from the history-tail `projections` block and updated by `session/projection` frames under higher-seq-wins; domain keys (including `todos`) are read via `projections.faceOf` / `useProjection`, not via `ConversationSnapshot`. The store also publishes one reference-stable whole-value map through `SessionSummary.projectionValues`, allowing global list consumers to reuse the same projections without creating per-session subscriptions.
## Slot declaration injection
`ctx.slots.inject(name, callback)` makes a full `SlotMap` key the dependency for a contribution whose plugin can activate independently from the declaring entry. It runs `callback` synchronously when the declaration exists, otherwise waits; declaration collapse disposes the callback effect, and redeclaration reruns it. The controller belongs to the caller's plugin fiber, so unloading the contributor cancels either the wait or its active registrations. A direct `slots.register()` into an undeclared slot still throws.
The callback returns one synchronous disposer or an iterable of disposers. A generator can therefore yield several `slots.register()` calls as one transaction: setup failure rolls earlier yields back and teardown runs them in reverse order. Declaration lifetimes use a dedicated monotonic epoch, so a collapse and redeclaration batched into one renderer notification still restarts the callback, while ordinary entry changes do not. Declaration-bound teardown runs synchronously with the ledger mutation, releasing runtime resources before subsequent same-tick registrations. See the [declaration-injection decision](../../../.agents/notes/implemented/architecture/2026-08-05-slot-declaration-injection.md).
## Workspace and Session lists
Workspace and Session lists have independent monotone `pending``ready` baseline phases and separate refresh activity/error state. Incremental upsert/removal frames and unary mutation echoes arriving during a list request replay over its response. The first successful baseline establishes Host order; later refreshes update rows and membership without changing the relative order of identities already shown. Removed Workspace ids retain process-local tombstones so late changed frames cannot resurrect them; reconnect still takes `workspace.list` as the baseline. Workspace recency is derived only after both baselines are ready and never changes Workspace list order.

View File

@@ -4,6 +4,12 @@
客户端 cordis 启动与不依赖 React 的对象服务SlotsService 包装 SlotCore 并提供 renderer 数据源SessionsService 拥有 Session 对象以及 Chat 所需的列表、scope 和事件窗口状态SessionHistoryService 为检查类消费方惰性拥有彼此独立的原始历史账本,先加载当前尾部,并仅在消费方请求时向前补入一页更早历史。每份历史快照都会公开原始窗口的绝对基准序号,因此即使该页没有新增任何 surface 可见节点消费方仍能检测到向前补页。WorkspacesService 依赖 SessionsService拥有 Workspace 对象、列表/操作、默认目标派生,以及 New Session 空会话复用入口(`connectWorkspace`)。运行时把共享 Host 流分发给 Session、Workspace 和已激活的历史数据所有者,不让检查状态经过 Session 或 SessionManager并把注册表失效帧桥接为类型化 ctx 事件(`commands/changed``settings/changed``credentials/changed``models/changed`),使各表面缓存无需触碰流即可重拉。客户端会话一律由 Host 创建(一次 `session.create` 同时产生 Session、agent智能体和 cwd客户端不持有任何实体化之前的会话状态——agent scopehost dsh-scope 的客户端镜像,以 agent/session 共用 id 为键)在会话行进入列表镜像时创建,并随 prune 销毁。契约api-contracts v3 §4。每个 `Session` 持有一个通用的 `ProjectionValueStore`,由历史记录尾部的 `projections` 块播种,并经 `session/projection` 帧按 seq 高者胜更新;领域键(含 `todos`)经 `projections.faceOf``useProjection` 读取,不经 `ConversationSnapshot`。该 store 还会通过 `SessionSummary.projectionValues` 发布一份引用稳定的完整值映射,使全局列表消费方无需为每个会话创建订阅,即可复用同一组投影。
## Slot 声明注入
`ctx.slots.inject(name, callback)` 将完整的 `SlotMap` key 作为贡献项的依赖,适用于贡献方插件可独立于声明条目激活的情形。声明存在时,它会同步运行 `callback`,否则等待;声明折叠会 dispose资源释放回调 effect重新声明则会再次运行回调。控制器归调用方的插件 fiber 所有,因此卸载贡献方会取消等待或移除其活跃注册项。直接调用 `slots.register()` 向未声明 slot 注册仍会抛出异常。
回调返回一个同步 disposer 或由多个 disposer 构成的 iterable。因此generator 可以 yield 多个 `slots.register()` 调用并将它们组成一项事务setup 失败会回滚先前 yield 的 effectteardown 则按逆序运行它们。声明生命周期使用专用的单调 declaration epoch声明代次因此即使折叠与重新声明合并在同一次 renderer 通知中,回调仍会重启,而普通条目变更不会重启它。声明绑定的 teardown 与账本变更同步运行,在同一 tick 内的后续注册之前释放运行时资源。详见 [slot 声明注入决策](../../../.agents/notes/implemented/architecture/2026-08-05-slot-declaration-injection.md)。
## Workspace 与 Session 列表
Workspace 和 Session 列表各自具有单调的 `pending``ready` 基线阶段,也有各自的刷新活动/错误状态。列表请求期间到达的增量插入或更新/移除帧与一元变更回显会在其响应之上回放。第一次成功的基线建立 Host 顺序;后续刷新更新行和成员关系,但不改变已经显示的标识之间的相对顺序。已移除的 Workspace id 会保留进程本地删除标记,避免延迟到达的 changed 帧将其复活;重连仍以 `workspace.list` 作为基线。Workspace 新近程度只在两条基线都 ready 后派生,且绝不改变 Workspace 列表顺序。
@@ -46,7 +52,7 @@ SlotsService 分别为 renderer 提供 `useSessions` 与 `useWorkspaces` 的裸
## 模型重试投影
Session 对象会在事件 wire 边界依据生产方的完整字段契约,验证由插件负责、按提供方路由的 `llm/retry` 载荷,包括计时器、整数、状态、提供方延迟和非空诊断字段的边界。有效事件会移除对应失败步骤的流式输出片段,并在该事件的序列位置插入一条持久的重试提示。该提示在后续重试轮次开始前为 `scheduled`;源轮次中止或被 dispose(资源释放)时,会将该提示标记为 `cancelled`,重试轮次则会将其标记为 `started`。normal mode 提示携带其有限上限always mode 提示则保持显式无界。没有重试的终态 `turn/end` 错误会从持久消息与可选错误码投影出一个 `turn-error` 节点AUTH 投影会把可能回显凭据片段的提供方文案替换为 `API key is invalid`,原始诊断仍保留在会话日志中。进入重试的失败则只保留该次尝试的重试提示。窗口重建与历史回放应用相同的投影,因此刷新既不会让已丢弃的分片重新出现,也不会丢失终态失败反馈。可见但尚未定稿的输出会在终态错误旁冻结为中断的 assistant 节点。
Session 对象会在事件 wire 边界依据生产方的完整字段契约,验证由插件负责、按提供方路由的 `llm/retry` 载荷,包括计时器、整数、状态、提供方延迟和非空诊断字段的边界。有效事件会移除对应失败步骤的流式输出片段,并在该事件的序列位置插入一条持久的重试提示。该提示在后续重试轮次开始前为 `scheduled`;源轮次中止或被 dispose 时,会将该提示标记为 `cancelled`,重试轮次则会将其标记为 `started`。normal mode 提示携带其有限上限always mode 提示则保持显式无界。没有重试的终态 `turn/end` 错误会从持久消息与可选错误码投影出一个 `turn-error` 节点AUTH 投影会把可能回显凭据片段的提供方文案替换为 `API key is invalid`,原始诊断仍保留在会话日志中。进入重试的失败则只保留该次尝试的重试提示。窗口重建与历史回放应用相同的投影,因此刷新既不会让已丢弃的分片重新出现,也不会丢失终态失败反馈。可见但尚未定稿的输出会在终态错误旁冻结为中断的 assistant 节点。
## 会话 fork

View File

@@ -2,12 +2,12 @@
* SlotsService: the cordis Service layer of the slot system over the pure
* SlotCore (ui-slots owns registration semantics, the declaration ledger,
* the load-time validations, and the unload cascade). This layer owns what
* needs the runtime: the 'slots/changed' event bridge, register through the
* caller's ctx.effect (fiber unload collects registrations), the renderer
* install seam (install()/renderSlot('root') + the SlotRendererHost face),
* and the store INSTANCE axis — handle x scope key -> create/cache, dropped
* with the last holding entry, session instances cleared (with persisted
* state) on scope death.
* needs the runtime: the 'slots/changed' event bridge, register and
* declaration injection through the caller's ctx.effect (fiber unload
* collects both), the renderer install seam (install()/renderSlot('root') +
* the SlotRendererHost face), and the store INSTANCE axis — handle x scope
* key -> create/cache, dropped with the last holding entry, session instances
* cleared (with persisted state) on scope death.
*/
/* oxlint-disable typescript/no-redundant-type-constituents --
* `keyof SlotMap & string` is the declare-merge key pattern: SlotMap only
@@ -78,6 +78,9 @@ interface ErasedRegisterOptions {
/** Erased core call face (the service re-erases at its own boundary; the core's typed face targets end callers). */
interface ErasedCore { register(options: object, component: unknown): () => void }
/** One synchronous effect installed while an injected slot declaration is live. */
type SlotInjectionEffect = (() => void) | Iterable<() => void, void, void>
/** cordis Service layer of the slot system; see the module doc for the split with SlotCore. */
export class SlotsService extends Service {
private readonly _core = new SlotCore()
@@ -114,6 +117,85 @@ export class SlotsService extends Service {
*/
declare readonly register: SlotCore['register']
/**
* Install an effect for each declaration lifetime of a slot. The callback
* runs synchronously when the declaration already exists; otherwise it runs
* inside the declaring `register()` call after the declaration is committed.
* Collapse disposes the effect and a later declaration runs it again.
* Callback effects are synchronous disposers; iterable effects install
* transactionally and dispose in reverse order. The controller belongs to
* the caller's fiber, so plugin unload cancels a pending wait and removes any
* active contribution.
*
* @param key - declared SlotMap key to depend on.
* @param callback - creates one disposer or an iterable of disposers.
* @returns idempotent disposer for the wait and active effect.
* @throws callback setup failures synchronously when the slot is already declared.
*/
inject(key: keyof SlotMap & string, callback: () => SlotInjectionEffect): () => void {
const ctx = this.ctx
const disposeController = ctx.effect(() => {
let active: (() => void) | undefined
let activeEpoch: number | undefined
let stopped = false
let unsubscribe = (): void => {}
const stop = (): void => {
if (stopped) return
// Failure callers retire the injection permanently: a delayed setup
// failure never retries on a later declaration.
stopped = true
unsubscribe()
const dispose = active
active = undefined
activeEpoch = undefined
dispose?.()
}
const reconcile = (): void => {
if (stopped) return
const spec = this._core.specDynamic(key)
const epoch = this._core.declarationEpoch(key)
if (active !== undefined && activeEpoch === epoch) return
const dispose = active
active = undefined
activeEpoch = undefined
dispose?.()
if (spec === undefined) return
// A declaration lifetime is a nested Cordis effect. This gives
// generator callbacks the same transactional setup, reverse teardown,
// diagnostics tree, and idempotence as every other plugin effect.
const disposeEffect = ctx.effect(callback, `slots.inject(${JSON.stringify(key)}): declaration`)
active = () => { void disposeEffect() }
activeEpoch = epoch
}
const changed = (): void => {
try {
reconcile()
} catch (error) {
if ((error as { code?: unknown } | null)?.code === 'INACTIVE_EFFECT') {
stop()
return
}
stop()
const failure = error instanceof Error ? error : new Error(String(error))
queueMicrotask(() => { throw failure })
}
}
unsubscribe = this._core.subscribeDeclaration(key, changed)
try {
reconcile()
} catch (error) {
stop()
throw error
}
return stop
}, `slots.inject(${JSON.stringify(key)})`)
return () => { void disposeController() }
}
/**
* Install the shell's renderer (web-react's createSlotRenderer product).
* Boot-once: a second install throws. Runs through the caller's ctx.effect,

View File

@@ -29,6 +29,7 @@ const C: FC<object> = () => null
*/
interface ErasedService {
register(options: object, component: unknown): () => void
inject(name: string, callback: () => (() => void) | Iterable<() => void>): () => void
install(renderer: object): void
renderSlot(key: string, owner: object): unknown
}
@@ -166,6 +167,266 @@ describe('load-time validation', () => {
})
})
describe('declaration injection', () => {
it('activates immediately and ignores ordinary entry mutations', async () => {
const bench = await boot()
bench.erased.register({
name: 'root', children: { 't.rows': { kind: 'list', scope: 'root' } },
}, C)
const setup = vi.fn(() => bench.erased.register({ name: 't.rows', id: 'injected' }, C))
const dispose = bench.erased.inject('t.rows', setup)
expect(setup).toHaveBeenCalledOnce()
bench.erased.register({ name: 't.rows', id: 'ordinary' }, C)
await Promise.resolve()
expect(setup).toHaveBeenCalledOnce()
dispose()
expect(bench.svc.entries('t.rows').map(entry => entry.options.id)).toEqual(['ordinary'])
})
it('waits for declaration, cleans up on collapse, and reruns after redeclaration', async () => {
const bench = await boot()
const cleanup = vi.fn()
const setup = vi.fn(() => {
const unregister = bench.erased.register({ name: 't.host' }, C)
return () => { unregister(); cleanup() }
})
bench.erased.inject('t.host', setup)
expect(setup).not.toHaveBeenCalled()
const disposeFrame = bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
await Promise.resolve()
expect(setup).toHaveBeenCalledOnce()
expect(bench.svc.entries('t.host')).toHaveLength(1)
disposeFrame()
await Promise.resolve()
expect(cleanup).toHaveBeenCalledOnce()
expect(bench.svc.entries('t.host')).toHaveLength(0)
bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
await Promise.resolve()
expect(setup).toHaveBeenCalledTimes(2)
expect(bench.svc.entries('t.host')).toHaveLength(1)
})
it('observes a same-tick collapse and redeclaration through the declaration epoch', async () => {
const bench = await boot()
const firstFrame = bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
const cleanup = vi.fn()
const setup = vi.fn(() => {
const unregister = bench.erased.register({ name: 't.host' }, C)
return () => { unregister(); cleanup() }
})
bench.erased.inject('t.host', setup)
firstFrame()
bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
await Promise.resolve()
expect(cleanup).toHaveBeenCalledOnce()
expect(setup).toHaveBeenCalledTimes(2)
expect(bench.svc.entries('t.host')).toHaveLength(1)
})
it('plugin disposal removes an active injection and prevents a waiting one from resurrecting', async () => {
const active = await boot()
active.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
const activeFiber = active.ctx.plugin({
name: 'active-injection',
inject: ['slots'],
apply: (ctx: Context) => { ctx.slots.inject('t.host', () => ctx.slots.register({ name: 't.host' }, C)) },
})
await activeFiber.await()
expect(active.svc.entries('t.host')).toHaveLength(1)
await activeFiber.dispose()
expect(active.svc.entries('t.host')).toHaveLength(0)
const waiting = await boot()
const setup = vi.fn(() => waiting.erased.register({ name: 't.host' }, C))
const waitingFiber = waiting.ctx.plugin({
name: 'waiting-injection',
inject: ['slots'],
apply: (ctx: Context) => { ctx.slots.inject('t.host', setup) },
})
await waitingFiber.await()
await waitingFiber.dispose()
waiting.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
await Promise.resolve()
expect(setup).not.toHaveBeenCalled()
})
it('rolls back earlier yielded registrations when generator setup fails', async () => {
const bench = await boot()
bench.erased.register({
name: 'root',
children: {
't.host': { kind: 'single', scope: 'root' },
't.rows': { kind: 'list', scope: 'root' },
},
}, C)
bench.erased.register({ name: 't.host' }, C)
expect(() => bench.erased.inject('t.rows', function* () {
yield bench.erased.register({ name: 't.rows', id: 'rolled-back' }, C)
yield bench.erased.register({ name: 't.host' }, C)
})).toThrow(/already has a registration/)
expect(bench.svc.entries('t.rows')).toHaveLength(0)
})
it('contains and wraps a delayed setup failure so later slot listeners still run', async () => {
const bench = await boot()
const failures: unknown[] = []
const onLoud = (error: unknown): void => { failures.push(error) }
process.on('uncaughtException', onLoud)
try {
const setup = vi.fn(function* () {
yield bench.erased.register({ name: 't.host' }, C)
throw null
})
bench.erased.inject('t.host', setup)
const later = vi.fn(() => () => undefined)
bench.erased.inject('t.host', later)
const disposeFrame = bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
await new Promise(resolve => setTimeout(resolve, 20))
expect(failures).toHaveLength(1)
expect(failures[0]).toBeInstanceOf(Error)
expect(String(failures[0])).toContain('null')
expect(later).toHaveBeenCalledOnce()
disposeFrame()
bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
expect(setup).toHaveBeenCalledOnce()
} finally {
process.off('uncaughtException', onLoud)
}
})
it('skips a stopped controller retained by the current declaration snapshot', async () => {
const bench = await boot()
let stopLater = (): void => {}
const first = vi.fn(() => {
stopLater()
return () => undefined
})
const later = vi.fn(() => () => undefined)
bench.erased.inject('t.host', first)
stopLater = bench.erased.inject('t.host', later)
bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
expect(first).toHaveBeenCalledOnce()
expect(later).not.toHaveBeenCalled()
})
it('keeps a nested redeclaration activation when the outer collapse resumes', async () => {
const bench = await boot()
const disposeFrame = bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
let disposeReplacement = (): void => {}
let replaced = false
const first = vi.fn(() => () => {
if (replaced) return
replaced = true
disposeReplacement = bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
})
const later = vi.fn(() => () => undefined)
bench.erased.inject('t.host', first)
bench.erased.inject('t.host', later)
disposeFrame()
expect(first).toHaveBeenCalledTimes(2)
expect(later).toHaveBeenCalledTimes(2)
expect(bench.svc.spec('t.host')).toBeDefined()
disposeReplacement()
})
it('cancels a waiting injection when its contributor is already unloading', async () => {
const bench = await boot()
const setup = vi.fn(() => bench.erased.register({ name: 't.host' }, C))
let release = (): void => {}
const blocked = new Promise<void>((resolve) => { release = resolve })
const pauseUnload = vi.fn(async () => { await blocked })
const contributor = bench.ctx.plugin({
name: 'unloading-injection',
inject: ['slots'],
apply: (ctx: Context) => {
ctx.slots.inject('t.host', setup)
ctx.effect(() => pauseUnload, 'pause contributor unload')
},
})
await contributor.await()
const disposing = contributor.dispose()
expect(() => bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)).not.toThrow()
expect(setup).not.toHaveBeenCalled()
await vi.waitFor(() => { expect(pauseUnload).toHaveBeenCalledOnce() })
release()
await disposing
})
it('supports dynamic plugin replacement without retaining the old rendered entry', async () => {
const bench = await boot()
bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
const componentA = (): null => null
const componentB = (): null => null
const mount = (name: string, component: FC<object>) => bench.ctx.plugin({
name,
inject: ['slots'],
apply: (ctx: Context) => { ctx.slots.inject('t.host', () => ctx.slots.register({ name: 't.host' }, component)) },
})
const first = mount('replacement-a', componentA)
await first.await()
expect(bench.svc.entries('t.host')[0]?.component).toBe(componentA)
await first.dispose()
expect(bench.svc.entries('t.host')).toHaveLength(0)
const second = mount('replacement-b', componentB)
await second.await()
expect(bench.svc.entries('t.host')[0]?.component).toBe(componentB)
})
it('releases service-layer store state when the declaration collapses', async () => {
const bench = await boot()
let host: SlotRendererHost | undefined
bench.erased.install({ renderRoot: (value: SlotRendererHost) => { host = value; return null } })
bench.ctx.reflect.provide('sessions', fakeSessions())
bench.ctx.reflect.provide('workspaces', fakeWorkspaces())
const disposeFrame = bench.erased.register({
name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
}, C)
bench.erased.renderSlot('root', {})
if (host === undefined) throw new Error('renderer never received the host')
const { handle } = fakeHandle()
bench.erased.inject('t.host', () => bench.erased.register({ name: 't.host', store: handle }, C))
const oldEntry = host.entriesOf('t.host')[0]
expect(host.storeOf(oldEntry as never, undefined)).toBeDefined()
disposeFrame()
expect(() => host?.storeOf(oldEntry as never, undefined)).toThrow(/not registered/)
bench.erased.register({
name: 'root', children: { 't.panel': { kind: 'single', scope: 'session' } },
}, C)
bench.erased.register({ name: 't.panel', store: handle }, C)
const panelEntry = host.entriesOf('t.panel')[0]
expect(host.storeOf(panelEntry as never, 's1')).toBeDefined()
expect(handle.create).toHaveBeenLastCalledWith('s1')
})
})
describe('renderer install seam', () => {
it('throws on renderSlot before install (boot-order guidance)', async () => {
const bench = await boot()