Files
deepseek-harness/packages/client/ui-command/tests/service.spec.ts
T
imccyu 01ecb43ebc docs: state the Host-face rule for the browser e2e and settle the follow-ups
apps/web/tests/README.md records why these e2e type-check in the Host aggregate
and why importing a Client package there pulls its project tree into the Host
build graph, with mirroring as the standing answer. The Agent Note drops the
directory-picker face split (assessed and declined) and the grep-level gate in
favour of that README.

docs: regenerate the catalogs and retarget the moved declarations

The forwarded-event change moved three owner packages' cordis `Events`
declarations and their branded types into client-safe `./types` modules, and
the settings-scope split moves the shell spec into ui-settings-general. Point
the type-equivalence manifest and the affected Agent Note at those homes,
register the new `remote/*` event scope and the `ctx.settingsScope` service in
the catalog partition, and re-run the generators.

`$on` joins the documented `TypeRTClientRemote` surface, and the two Agent Note
fences that quote a bare member signature are marked `ignore-check`: they are
declaration fragments, not compilable units.

refactor(client): make ui-settings the settings domain's base layer

The settings-namespace transport lived in client/runtime, where every feature
could value-import it because runtime is a platform module. It belongs to the
settings domain, but moving it into ui-settings as a shared function fails
twice: the client bundle purity gate forbids cross-plugin value imports, and
ui-settings reached ui-sidebar for its shell, so any feature depending on it
closed a cycle through ui-layout and ui-theme.

Both halves move. `ctx.settingsScope` is now a cordis service — the
collaboration shape the purity gate prescribes, and the service proxy binds
`this.ctx` to the caller, so a bound scope's disposer belongs to the calling
fiber. The shell ui-settings used to own (the `sidebar.settings` occupant, its
navigation, and the nav-row projection) moves to ui-settings-general, which
already owns the chrome and the General section. What stays in ui-settings is
what carries no `ui-*` dependency: the scope service and the canonical settings
slot types, `settings.general.item` included. That type was parked in the locale
package precisely because the declarer was unreachable without a cycle; every
registrant now depends on this base layer, so it comes home.

The scope CONTRACT stays in client/runtime: a feature service accepts a scope
through its own signature without depending on the surface that binds it.

The forwarded settings invalidation replaces the deleted client-side
`settings/changed` event, so the transport reads `ctx.remote.$on`. It reaches
`$on` through the gateway's Client half plus the allowlist's type-only subpath
rather than api-remotes' Client face: that face imports a Host-tsdown-generated
artifact, and this package is reachable from the Host build graph through its
callers.

refactor(client): reach the settings transport through ctx.settingsScope

Every feature that owns a preference row switches from value-importing a shared
binder to the settings domain's service, and declares the two injections that
binding needs: `settingsScope` for the transport and `remote` for the forwarded
invalidation it subscribes to on the caller's own context.

The rows stay with the features that own the preferences — Language with locale,
Appearance with ui-theme, Composer Enter with ui-conversation. Only their route
to the transport changes, so no settings surface moves and no feature gains a
dependency on the shell.

The `settings.general.item` slot type now arrives from ui-settings, the base
layer every registrant already depends on, which retires the re-export outlet
ui-theme kept and the parked declaration in the locale package.

client/runtime drops its settings-form and schemastery dependencies with the
transport that used them.

test(client): bind the settings transport in the specs that boot a preference row

Every bench that activates a plugin owning a preference row now supplies the two
services that plugin injects: the forwarded-event port and the scope service.
Specs that exercise no settings path get the minimal doubles; the ones that do
drive their refresh chains through `remote/host-event`, the same signal
client/runtime republishes from a forwarded frame, replacing the deleted
client-side `settings/changed` event.

Also fixes a publication defect the built-invariant gate catches once it runs:
api-remotes' invariant companion shared the allowlist module with the package
index, so rolldown hoisted it into a third chunk beside the two bundled entries
— a file the mechanically derived publication list does not carry, leaving an
installed companion unable to import it. The companion now reads the allowlist
through this package's own published `./types` subpath, which the bundle keeps
external, so each entry stays self-contained.

The dynamic-subscription cast in apiproxy is gone: after the vendored cordis
rescope, `on` accepts the rest-parameter handler directly, and the allowlist's
shape assertion still carries the safety argument.

fix(client): carry the settings-scope move across the release manifests

Rebasing onto the publishable release set replaced every manifest's dependency
block, so the packages this change touches restate their additions in the
workspace-protocol form: the base layer's own transport dependencies, and the
`ui-settings` plus `remote` edges each preference-row owner now needs.

ui-settings-general takes clsx with the shell it received, and client/runtime
drops the settings-form and schemastery dependencies that left with the
transport.

fix(api-gateway): give each $on subscription its own registration and containment

Two defects in the forwarded-event subscription table, both raised in review:

A set keyed on listener identity stored one entry when two callers subscribed the
same function object to the same event, so the first frame reached it once instead
of twice and either disposer silenced the surviving registration. Subscriptions are
now records addressed by registration, which is what "the disposer belongs to the
calling fiber" requires.

A listener declared void may still be `async`, and the synchronous `try/catch`
could not see its rejection: the promise was dropped and surfaced as an unhandled
rejection outside the documented containment. Delivery now attaches a rejection
handler when a listener returns a promise, so both failure modes are logged and
isolated alike.

Delivery also iterates a snapshot, so a listener that subscribes or disposes during
a frame no longer changes who receives that frame, and production matches the
TestRemote double instead of relying on live Set iteration order.

Both fixes are pinned by tests that fail against the previous implementation. The
double gains its own spec for the `$mount` refusal and the unsubscribed-name drop —
per-file coverage reaches it — plus a note that it propagates a throwing listener
where production contains one, so no spec mistakes it for the containment guarantee.

Three prose corrections: `assertJsonArgs` states where its throw actually surfaces
(the emitter's listener containment, not load or emit time), the browser e2e README
names every standing Client import rather than claiming one exception, and two
comments and a test title state the forwarded event instead of the deleted
client-side one.

refactor(remote): deliver forwarded frames through ctx.remote.$dispatch

The carrier used to relay each decoded frame over an internal
`remote/host-event` cordis event so the delivery port could stay off the Remote
contract. The relay was the wrong shape twice over: it put a client-face event
into a scan whose subject is the Host vocabulary, forcing a walk exemption for
something that is not a Host event at all, and it made a direct handoff between
two Client plugins look like a broadcast any plugin participates in.

`TypeRTClientRemote` now carries both roles of one surface — consumers subscribe
with `$on`, and whoever owns the Host frame sink hands frames over with
`$dispatch` — so client/runtime calls the Remote service directly and the event
declaration is gone. A cordis service method is the collaboration shape the
client bundle purity gate prescribes, and it needs no relay to satisfy it.

The trade is that the handoff is now developer-visible: any plugin holding
`ctx.remote` can synthesize a forwarded event. That is the exposure the relay
already had — `ctx.emit` was equally reachable — stated in the contract instead
of hidden behind a private subscriber.

runtime reaches `ctx.remote` through the gateway's Client face rather than
api-remotes': that face imports a Host-tsdown-generated artifact, and this
project sits in the Host build graph.

refactor(api-remotes): keep the allowlist value out of types.ts

`src/types.ts` carries only types by package convention, but it held the
forwarded-event array, so the type-only subpath published runtime code. The
array moves to `src/remote-events.ts` and `types.ts` derives its projection from
it; both compiler faces list both files, so the Host forwarding loop and the
consumer key face still read one declaration and the package's exports are
unchanged.

The invariant companion returns to an empty installer. Its dispatch-shape check
was the only reason the companion imported the allowlist, which made the two
bundled entries share a module: rolldown hoisted it into a third chunk that the
mechanically derived publication list does not carry, so an installed companion
could not import it. Dropping the check retires that coupling along with the
subpath-import and bundle-external workarounds it needed, and the shape the
check enforced at runtime is the part the Host face's `TypeRTForwardableEvent`
assertion already refuses at compile time.

test(ui-task): bind the locale plugin's new injections in its bench

The bench boots the real locale plugin, which now injects the settings-scope
service and the forwarded-event port, so it stayed pending and left `ctx.locale`
undefined. Supplies both doubles like the other benches that boot a plugin
owning a preference row.

docs: close the documentation gates for the forwarded-event surface

Regenerates the two graph catalogs and re-records every bilingual pair this
branch edited. Several pairs needed real work beyond the record:

- The generators write only the English side, so the Chinese sides of
  `event-producer-consumer` and `module-graph` had drifted: the former still
  listed the three deleted client-face events and pointed at declaration sites
  this branch moved into `types.ts` modules, and the latter carried a stale
  dependency graph.
- `TypeRTClientRemote`'s documented declaration gains `$dispatch` on both sides.
- The pairing contract requires both sides to link the same target, so the
  apiproxy README and the design note now link the English note from both
  languages, and the note's code blocks are byte-identical across the pair
  (a translated comment inside a fence counts as divergence).
- `apps/web/tests/README.md` gains its Chinese counterpart; the browser e2e lane
  documents a discipline reviewers apply, so it belongs in the bilingual corpus
  rather than in the pairing exemption list.
- Four fences in the design note are marked `ignore-check`: each quotes a member
  signature, a union arm, or a snippet that names symbols it does not import, so
  none is a compilable unit.

docs(agent-note): transition the forwarded-event note to implemented

The design shipped in this PR, so the pair moves into `implemented/` and takes
that folder's skeleton: `## Proposal` becomes a present-tense `## Decision`,
and `## Acceptance criteria` plus `## Risks` fold into `## Verification` (what
pins the behavior) and `## Consequences` (what the shipped shape costs).

Facts that moved after the proposal are corrected rather than preserved: the
allowlist value now lives in `remote-events.ts` beside a type-only `types.ts`,
the delivery port is `$dispatch` rather than an internal cordis event, and the
invariant companion is an explained empty installer. `Verification` states the
two `$on` defects the review found — independent registration identity and
async-rejection containment — since those are now the properties tests pin.

Supersession is partial, so five active notes stay active and gain a
cross-link each: `web-config-plane`, `web-client-session-scope`,
`config-plane-boundaries`, `versioned-gui-welcome-onboarding`, and
`permission-default-for-new-sessions` each described a frame this change
replaced. Only the mechanism sentence is annotated; every conclusion those
notes own is untouched, and `host/models-changed` remains apiproxy's own
derived frame in all of them.

Also pins the disposer's idempotence: calling one `$on` disposer twice must not
splice a surviving twin registration out from under its owner.

fix: docs

fix: test
2026-08-11 19:25:41 +08:00

667 lines
29 KiB
TypeScript

/**
* CommandService tests on a real cordis Context with fake slash/connection
* faces and real session scopes (createScope): session-keyed candidate
* synthesis (host catalog by sessionId + contributions by availability,
* collision fail-loud), the dispatch decision table cell by cell, matchSpace
* hot-key policy, matchEnter strong-wait / reject, the sessionId execute
* payload, the scoped consume-token dispatch, per-session popupFor
* lifecycle, and the directory invalidation event subscriptions.
*/
import { Context } from '@deepseek-ai/cordis'
import { describe, expect, it, vi } from 'vitest'
import { createScope, scopeOf } from '@deepseek-ai/dsh-client-runtime/client'
import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
import type { ClientSessionContext, ConsumeTokenRequest, SlashPick, SlashSource } from '@deepseek-ai/dsh-client-ui-slash/client'
import type { CommandContribution, CommandDecoration, CommandUiSpec, SelectOption } from '../src/client/contract.ts'
import type { CommandDescriptor } from '../src/client/directory.ts'
import { CommandService } from '../src/client/service.ts'
const sid = (k: string): SessionId => k as SessionId
/** The agent-backed session projection (single state; identity only). */
const proj = (id: string): ClientSessionContext => ({ sessionId: sid(id) })
const S1_CMDS: CommandDescriptor[] = [
{ name: 'plan', description: 'bare kind' },
{ name: 'goal', description: 'leadingInput kind', input: { hint: 'goal text' } },
]
const S2_CMDS: CommandDescriptor[] = [
...S1_CMDS,
{ name: 'attach', description: 'scoped shadow', input: { hint: 'path' } },
]
type ExecuteValue = { matched: boolean }
interface BenchOptions {
/** Scripted catalog per list payload; default serves the fixed catalogs by session. */
commands?: (payload: { sessionId: SessionId }) => Promise<{ commands: CommandDescriptor[] }>
execute?: (payload: { sessionId: SessionId; line: string }) => Promise<ExecuteValue>
addressed?: SessionId
}
async function bench(opts: BenchOptions = {}) {
const ctx = new Context()
const registered = new Map<string, SlashSource>()
const listCalls: Array<{ sessionId: SessionId }> = []
const executeCalls: Array<{ sessionId: SessionId; line: string }> = []
const api = {
commands: {
list: async (payload: { sessionId: SessionId }) => {
listCalls.push(payload)
const value = await (opts.commands ?? (p => Promise.resolve({
commands: p.sessionId === sid('s2') ? S2_CMDS : S1_CMDS,
})))(payload)
return { result: { ok: true as const, value } }
},
execute: async (payload: { sessionId: SessionId; line: string }) => {
executeCalls.push(payload)
const value = await (opts.execute ?? (() => Promise.resolve({ matched: true })))(payload)
return { result: { ok: true as const, value } }
},
},
}
ctx.provide('slash', {
registerSource(src: SlashSource) {
const key = `${src.trigger} ${src.name}`
registered.set(key, src)
return () => { registered.delete(key) }
},
})
// Real scope tags behind a fake sessions face.
const scopes = new Map<SessionId, { ctx: Context; fiber: { dispose(): Promise<void> } }>()
ctx.provide('sessions', {
scope: (id: SessionId) => scopes.get(id)?.ctx,
scopeOf: (c: Context) => scopeOf(c),
subagentAddress: (id: SessionId) => id === opts.addressed
? { parentSessionId: sid('parent'), childSessionId: id, mode: 'continuable' as const }
: undefined,
})
ctx.provide('connection', { api })
// CommandService injects `remote`; the directory invalidation arrives on the
// same `$dispatch` handoff the connection sink makes.
new TestRemote(ctx)
/** Notices the fake conversation face collected (runDetached routing). */
const notices: Array<{ scope: SessionId | undefined; level: 'info' | 'error'; text: string }> = []
ctx.provide('conversation', {
input: {
for: (actx: Context) => ({
notify: (level: 'info' | 'error', text: string) => {
notices.push({ scope: scopeOf(actx), level, text })
},
}),
},
})
const fiber = ctx.plugin(CommandService)
await fiber.await()
const command = ctx.get('command') as CommandService
const source = registered.get('/ command')
if (source === undefined) throw new Error('command source not registered')
const mint = (key: string) => {
const handle = createScope(ctx, sid(key))
scopes.set(sid(key), handle)
return handle
}
/** Warm one session's catalog through the source's own candidate pull. */
const warm = async (session: ClientSessionContext) => {
await source.candidates(session, { query: '', position: 'leading', signal: new AbortController().signal })
}
return { ctx, fiber, command, source, mint, warm, listCalls, executeCalls, registered, notices }
}
function menuPick(source: SlashSource, name: string, session: ClientSessionContext, end?: number) {
const pick: SlashPick = {
candidate: { name },
session,
position: 'leading',
via: 'menu',
span: { start: 0, end: end ?? name.length + 1, draftRev: 3 },
}
return source.onPick(pick)
}
const themeUi = (over: Partial<CommandUiSpec> = {}): CommandUiSpec => ({
kind: 'popupSelect',
options: () => Promise.resolve([{ id: 'dark', label: 'Dark' }]),
onSelect: () => undefined,
...over,
})
const themeContribution = (over: Partial<CommandContribution> = {}): CommandContribution => ({
name: 'theme',
description: 'client popup kind',
available: () => true,
ui: themeUi(),
...over,
})
const req = (query: string, position: 'leading' | 'inline' = 'leading') =>
({ query, position, signal: new AbortController().signal })
describe('registration', () => {
it('registers the "/" source with matchSpace/matchEnter/warm hooks and removes it on fiber disposal', async () => {
const { registered, source, fiber } = await bench()
expect(typeof source.matchSpace).toBe('function')
expect(typeof source.matchEnter).toBe('function')
expect(typeof source.warm).toBe('function')
expect([...registered.keys()]).toEqual(['/ command'])
await fiber.dispose()
expect(registered.size).toBe(0)
})
it('the warm hook prewarms the session key: one pull per session, no duplicate over pending', async () => {
const { source, listCalls } = await bench()
source.warm!(proj('s1'))
expect(listCalls).toEqual([{ sessionId: sid('s1') }])
source.warm!(proj('s2'))
expect(listCalls).toEqual([{ sessionId: sid('s1') }, { sessionId: sid('s2') }])
source.warm!(proj('s1')) // s1 already pending → no duplicate pull
expect(listCalls).toHaveLength(2)
})
})
describe('candidates', () => {
it('does not fetch Agent-bound commands for an addressed child', async () => {
const b = await bench({ addressed: sid('child') })
await expect(b.warm(proj('child'))).resolves.toBeUndefined()
expect(b.listCalls).toEqual([])
})
it('pulls the session catalog; fuzzy filter and hint mapping apply', async () => {
const { source, listCalls } = await bench()
const list = await source.candidates(proj('s1'), req('g'))
expect(listCalls).toEqual([{ sessionId: sid('s1') }])
expect(list).toEqual([{ name: 'goal', description: 'leadingInput kind', hint: 'goal text' }])
})
it('matches case-insensitive subsequences and ranks prefixes, boundaries, adjacency, gaps, then source order', async () => {
const commands: CommandDescriptor[] = [
{ name: 'q-xylophone', description: '' },
{ name: 'qx-long', description: '' },
{ name: 'fabulous', description: '' },
{ name: 'foo-bar', description: '' },
{ name: 'zuv', description: '' },
{ name: 'zu1v', description: '' },
{ name: 'yu1v', description: '' },
{ name: 'zu12v', description: '' },
]
const { source } = await bench({ commands: () => Promise.resolve({ commands }) })
const names = async (query: string) => (await source.candidates(proj('s1'), req(query))).map(c => c.name)
await expect(names('QX')).resolves.toEqual(['qx-long', 'q-xylophone'])
await expect(names('fb')).resolves.toEqual(['foo-bar', 'fabulous'])
await expect(names('uv')).resolves.toEqual(['zuv', 'zu1v', 'yu1v', 'zu12v'])
await expect(names('zzz')).resolves.toEqual([])
await expect(names('query-longer-than-every-name')).resolves.toEqual([])
})
it('catalogs are per session: another session pulls its own key', async () => {
const { source, listCalls } = await bench()
const names = (await source.candidates(proj('s2'), req(''))).map(c => c.name)
expect(listCalls).toEqual([{ sessionId: sid('s2') }])
expect(names).toEqual(['plan', 'goal', 'attach'])
})
it('hides leadingInput commands at inline position', async () => {
const { source } = await bench()
const names = (await source.candidates(proj('s1'), req('', 'inline'))).map(c => c.name)
expect(names).toEqual(['plan'])
})
it('merges available contributions and filters unavailable ones with the per-call projection', async () => {
const { command, source } = await bench()
const available = vi.fn((session: ClientSessionContext) => session.sessionId === sid('s1'))
command.register(themeContribution({ available }))
const s1Names = (await source.candidates(proj('s1'), req(''))).map(c => c.name)
expect(s1Names).toEqual(['plan', 'goal', 'theme'])
expect(available).toHaveBeenLastCalledWith(proj('s1'))
const s2Names = (await source.candidates(proj('s2'), req(''))).map(c => c.name)
expect(s2Names).not.toContain('theme')
})
it('contribution rows ride the same fuzzy query filter', async () => {
const { command, source } = await bench()
command.register(themeContribution())
const names = (await source.candidates(proj('s1'), req('tm'))).map(c => c.name)
expect(names).toEqual(['theme'])
})
it('a contribution/host name collision fails loud', async () => {
const { command, source } = await bench()
command.register(themeContribution({ name: 'plan' }))
await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('collides with a host command')
})
})
describe('decorations (bare-invocation UI on host commands)', () => {
const goalDecoration = (over: Partial<CommandDecoration> = {}): CommandDecoration => ({
name: 'goal',
available: () => true,
ui: themeUi(),
...over,
})
it('adds no catalog row: the host row stands alone', async () => {
const { command, source } = await bench()
command.decorate(goalDecoration())
const names = (await source.candidates(proj('s1'), req(''))).map(c => c.name)
expect(names).toEqual(['plan', 'goal'])
})
it('bare enter opens the popup; an argued line never consults the decoration (host claim)', async () => {
const { command, source, mint, warm } = await bench()
command.decorate(goalDecoration())
const scope = mint('s1')
await warm(proj('s1'))
expect(await source.matchEnter!(proj('s1'), '/goal', new AbortController().signal)).toBe('handled')
expect(command.popupFor(scope.ctx).state.getSnapshot()).toMatchObject({ open: true, command: 'goal' })
const argued = await source.matchEnter!(proj('s1'), '/goal ship it', new AbortController().signal)
if (argued === undefined || argued === 'handled' || !('claim' in argued)) throw new Error('expected the host claim')
expect(argued.claim.token).toBe('/goal ')
})
it('space never consults the decoration (host claim)', async () => {
const { command, source, warm } = await bench()
command.decorate(goalDecoration())
await warm(proj('s1'))
const outcome = source.matchSpace!(proj('s1'), '/goal')
if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected the host claim')
expect(outcome.claim.token).toBe('/goal ')
})
it('a decoration with no host row never fires (bare enter misses; menu pick misses)', async () => {
const { command, source, mint, warm } = await bench()
command.decorate(goalDecoration({ name: 'phantom' }))
const scope = mint('s1')
await warm(proj('s1'))
expect(await source.matchEnter!(proj('s1'), '/phantom', new AbortController().signal)).toBeUndefined()
expect(menuPick(source, 'phantom', proj('s1'))).toBeUndefined()
expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(false)
})
it('an unavailable decoration falls through to the host bare path (detached execute)', async () => {
const { command, source, warm, executeCalls } = await bench()
command.decorate(goalDecoration({ name: 'plan', available: () => false }))
await warm(proj('s1'))
expect(await source.matchEnter!(proj('s1'), '/plan', new AbortController().signal)).toBe('handled')
expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
})
it('duplicate decoration names fail loud', async () => {
const { command } = await bench()
command.decorate(goalDecoration())
expect(() => { command.decorate(goalDecoration()) }).toThrow('duplicate decoration for /goal')
})
})
describe('dispatch (menu column)', () => {
it('contribution → opens the session popup with the open-time projection, no execute', async () => {
const { command, source, mint, warm, executeCalls } = await bench()
const options = vi.fn((_s: ClientSessionContext) => Promise.resolve([{ id: 'dark', label: 'Dark' }]))
command.register(themeContribution({ ui: themeUi({ options }) }))
const scope = mint('s1')
await warm(proj('s1'))
expect(menuPick(source, 'theme', proj('s1'))).toBe('handled')
const popup = command.popupFor(scope.ctx)
expect(popup.state.getSnapshot()).toMatchObject({ open: true, command: 'theme' })
expect(options).toHaveBeenCalledExactlyOnceWith(proj('s1'), expect.any(AbortSignal))
expect(executeCalls).toEqual([])
})
it('an unavailable contribution falls through to the host catalog', async () => {
const { command, source, mint, warm } = await bench()
command.register(themeContribution({ available: () => false }))
const scope = mint('s1')
await warm(proj('s1'))
expect(menuPick(source, 'theme', proj('s1'))).toBeUndefined() // no host 'theme' either
expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(false)
})
it('host leadingInput → {claim} with token "/name " and hint; claiming never executes', async () => {
const { source, warm, executeCalls } = await bench()
await warm(proj('s1'))
const outcome = menuPick(source, 'goal', proj('s1'))
if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
expect(outcome.claim.token).toBe('/goal ')
expect(outcome.claim.hint).toBe('goal text')
expect(executeCalls).toEqual([])
})
it('host bare → consume-token span guard on the session scope + detached execute', async () => {
const { source, mint, warm, executeCalls } = await bench()
const scope = mint('s1')
const consumes: ConsumeTokenRequest[] = []
scope.ctx.on('slash/input-consume-token', (r) => {
consumes.push(r)
return true
})
await warm(proj('s1'))
expect(menuPick(source, 'plan', proj('s1'), 5)).toBe('handled')
expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 5, draftRev: 3 } } }])
await Promise.resolve()
expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
})
it('a name the directory no longer serves → undefined (snapshot swapped between menu and pick)', async () => {
const { source, warm } = await bench()
await warm(proj('s1'))
expect(menuPick(source, 'gone', proj('s1'))).toBeUndefined()
})
})
describe('matchSpace (space column)', () => {
it('answers undefined from a not-ready key (no waiting, no RPC)', async () => {
const { source, listCalls } = await bench()
expect(source.matchSpace!(proj('s1'), '/goal')).toBeUndefined()
expect(listCalls).toEqual([])
})
it('hot leadingInput exact token → {claim}; the key axis is the session', async () => {
const { source, warm } = await bench()
await warm(proj('s2'))
const outcome = source.matchSpace!(proj('s2'), '/attach')
if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
expect(outcome.claim.token).toBe('/attach ')
// s1's key is still cold: the same token answers undefined there.
expect(source.matchSpace!(proj('s1'), '/attach')).toBeUndefined()
})
it('bare kind and contribution names stay plain text', async () => {
const { command, source, warm } = await bench()
command.register(themeContribution())
await warm(proj('s1'))
expect(source.matchSpace!(proj('s1'), '/plan')).toBeUndefined()
expect(source.matchSpace!(proj('s1'), '/theme')).toBeUndefined()
})
it('unknown token / non-slash token → undefined', async () => {
const { source, warm } = await bench()
await warm(proj('s1'))
expect(source.matchSpace!(proj('s1'), '/nope')).toBeUndefined()
expect(source.matchSpace!(proj('s1'), 'plan')).toBeUndefined()
})
})
describe('matchEnter (enter column)', () => {
const signal = () => new AbortController().signal
it('strong-waits a cold key before adjudicating', async () => {
let release!: (value: { commands: CommandDescriptor[] }) => void
const { source } = await bench({
commands: () => new Promise((resolve) => { release = resolve }),
})
const wait = source.matchEnter!(proj('s1'), '/goal args', signal())
release({ commands: S1_CMDS })
const outcome = await wait
if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
expect(outcome.claim.token).toBe('/goal ')
})
it('rejects when warmup fails (never a silent downgrade)', async () => {
const { source } = await bench({
commands: () => Promise.reject(new Error('warmup boom')),
})
await expect(source.matchEnter!(proj('s1'), '/goal', signal())).rejects.toThrow('warmup boom')
})
it('leadingInput claims args-tolerant (bare and with trailing text)', async () => {
const { source, warm } = await bench()
await warm(proj('s1'))
for (const line of ['/goal', '/goal refactor the loop']) {
const outcome = await source.matchEnter!(proj('s1'), line, signal())
if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
expect(outcome.claim.token).toBe('/goal ')
}
})
it('bare host command executes detached with the bare-token consume guard', async () => {
const { source, mint, warm, executeCalls } = await bench()
const scope = mint('s1')
const consumes: ConsumeTokenRequest[] = []
scope.ctx.on('slash/input-consume-token', (r) => {
consumes.push(r)
return true
})
await warm(proj('s1'))
await expect(source.matchEnter!(proj('s1'), '/plan', signal())).resolves.toBe('handled')
expect(consumes).toEqual([{ guard: { kind: 'bare-token', token: '/plan' } }])
await Promise.resolve()
expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan' }])
})
it('bare kind with trailing text → undefined and no RPC (default sink owns the line)', async () => {
const { source, warm, executeCalls } = await bench()
await warm(proj('s1'))
await expect(source.matchEnter!(proj('s1'), '/plan now', signal())).resolves.toBeUndefined()
expect(executeCalls).toEqual([])
})
it('contribution: bare token opens the popup without touching the directory; args → undefined', async () => {
const { command, source, mint, listCalls } = await bench()
command.register(themeContribution())
const scope = mint('s1')
await expect(source.matchEnter!(proj('s1'), '/theme', signal())).resolves.toBe('handled')
expect(command.popupFor(scope.ctx).state.getSnapshot().open).toBe(true)
expect(listCalls).toEqual([]) // contribution short-circuits ahead of ensureReady
await expect(source.matchEnter!(proj('s1'), '/theme dark', signal())).resolves.toBeUndefined()
})
it('unknown name, bare "/", and non-slash lines → undefined', async () => {
const { source, warm } = await bench()
await warm(proj('s1'))
await expect(source.matchEnter!(proj('s1'), '/nope', signal())).resolves.toBeUndefined()
await expect(source.matchEnter!(proj('s1'), '/', signal())).resolves.toBeUndefined()
await expect(source.matchEnter!(proj('s1'), 'plain text', signal())).resolves.toBeUndefined()
})
})
describe('execute payload', () => {
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 }),
})
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' }])
// 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 () => {
const claimOf = async (opts: BenchOptions) => {
const b = await bench(opts)
await b.warm(proj('s1'))
const outcome = b.source.matchSpace!(proj('s1'), '/goal')
if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected claim')
return outcome.claim
}
const first = await claimOf({ execute: () => Promise.resolve({ matched: false }) })
const bad = await first.submit('x', new Context())
expect(bad.kind).toBe('error')
const second = await claimOf({ execute: () => Promise.resolve({ matched: true }) })
await expect(second.submit('', new Context())).resolves.toEqual({ kind: 'success' })
})
})
describe('detached admission notices', () => {
const flush = () => new Promise(resolve => setTimeout(resolve, 0))
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: 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([])
// 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: 'unknown or malformed command: /plan' }])
notices.length = 0
mode = 'reject'
menuPick(source, 'plan', proj('s1'))
await flush()
expect(notices).toEqual([{ scope: sid('s1'), level: 'error', text: 'network down' }])
})
it('a torn-down scope drops the failure notice', async () => {
const { source, warm, notices } = await bench({
execute: () => Promise.reject(new Error('orphan failure')),
})
await warm(proj('ghost')) // never minted: scopeFor misses
menuPick(source, 'plan', proj('ghost'))
await flush()
expect(notices).toEqual([])
})
})
describe('register (contribution face)', () => {
it('duplicate registration throws; the disposer frees the name', async () => {
const { command } = await bench()
const dispose = command.register(themeContribution())
expect(() => command.register(themeContribution())).toThrow('duplicate contribution')
dispose()
command.register(themeContribution())()
})
})
describe('popupFor', () => {
it('resolves lazily per session; a foreign session gets its own controller; unscoped ctx throws', async () => {
const { ctx, command, mint } = await bench()
const a = mint('s1')
const first = command.popupFor(a.ctx)
expect(command.popupFor(a.ctx)).toBe(first)
expect(command.popupFor(mint('s2').ctx)).not.toBe(first)
expect(() => command.popupFor(ctx)).toThrow('requires a session scope')
})
it('a successful select dispatches the scoped consume-token and fires the bound composer focus', async () => {
const { command, source, mint } = await bench()
const onSelect = vi.fn()
command.register(themeContribution({ ui: themeUi({ onSelect }) }))
const scope = mint('s1')
const consumes: ConsumeTokenRequest[] = []
scope.ctx.on('slash/input-consume-token', (r) => {
consumes.push(r)
return true
})
const focus = vi.fn()
command.bindComposerFocus(sid('s1'), focus)
expect(menuPick(source, 'theme', proj('s1'), 6)).toBe('handled')
const popup = command.popupFor(scope.ctx)
await Promise.resolve() // options land
await popup.select(0)
expect(onSelect).toHaveBeenCalledExactlyOnceWith({ id: 'dark', label: 'Dark' } satisfies SelectOption, proj('s1'))
expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 6, draftRev: 3 } } }])
expect(focus).toHaveBeenCalledTimes(1)
})
it('the enter path opens with the bare-token guard', async () => {
const { command, source, mint } = await bench()
command.register(themeContribution())
const scope = mint('s1')
const consumes: ConsumeTokenRequest[] = []
scope.ctx.on('slash/input-consume-token', (r) => {
consumes.push(r)
return true
})
await source.matchEnter!(proj('s1'), '/theme', new AbortController().signal)
const popup = command.popupFor(scope.ctx)
await Promise.resolve()
await popup.select(0)
expect(consumes).toEqual([{ guard: { kind: 'bare-token', token: '/theme' } }])
})
it('the scope disposer disposes the controller and a re-mint resolves fresh', async () => {
const { command, source, mint } = await bench()
command.register(themeContribution())
const scope = mint('s1')
await source.matchEnter!(proj('s1'), '/theme', new AbortController().signal)
const popup = command.popupFor(scope.ctx)
expect(popup.state.getSnapshot().open).toBe(true)
await scope.fiber.dispose()
expect(popup.state.getSnapshot().open).toBe(false)
expect(command.popupFor(mint('s1').ctx)).not.toBe(popup)
})
})
describe('directory invalidation events', () => {
it('commands/change repulls in the background while the old snapshot serves', async () => {
let round = 0
const { ctx, source, warm } = await bench({
commands: () => {
round += 1
return Promise.resolve({
commands: round === 1
? S1_CMDS
: [{ name: 'fresh', description: '', input: { hint: 'h' } }],
})
},
})
await warm(proj('s1'))
ctx.remote.$dispatch('commands/change', [])
await new Promise(resolve => setTimeout(resolve, 0))
expect(source.matchSpace!(proj('s1'), '/fresh')).not.toBeUndefined()
expect(source.matchSpace!(proj('s1'), '/goal')).toBeUndefined()
})
it('session/preset-changed repulls the recomposed session and leaves the others served', async () => {
const rounds = new Map<SessionId, number>()
const { ctx, source, warm } = await bench({
commands: (payload) => {
const round = (rounds.get(payload.sessionId) ?? 0) + 1
rounds.set(payload.sessionId, round)
return Promise.resolve({
commands: round === 1
? S1_CMDS
: [{ name: 'fresh', description: '', input: { hint: 'h' } }],
})
},
})
await warm(proj('s1'))
await warm(proj('s2'))
// A preset switch changes which commands one session's agent resolves;
// every other session keeps the catalog its own composition serves.
ctx.emit('session/preset-changed', sid('s1'), 'minimal')
await new Promise(resolve => setTimeout(resolve, 0))
expect(source.matchSpace!(proj('s1'), '/fresh')).not.toBeUndefined()
expect(source.matchSpace!(proj('s1'), '/goal')).toBeUndefined()
expect(source.matchSpace!(proj('s2'), '/goal')).not.toBeUndefined()
})
it('connection/reset hard-drops every session key until its rewarm lands', async () => {
let block = false
let release!: (value: { commands: CommandDescriptor[] }) => void
const { ctx, source, warm } = await bench({
commands: () => (block
? new Promise((resolve) => { release = resolve })
: Promise.resolve({ commands: S2_CMDS })),
})
await warm(proj('s2'))
expect(source.matchSpace!(proj('s2'), '/attach')).not.toBeUndefined()
block = true
ctx.emit('connection/reset')
// Hard reset: silent until the rewarm lands.
expect(source.matchSpace!(proj('s2'), '/attach')).toBeUndefined()
release({ commands: S2_CMDS })
await new Promise(resolve => setTimeout(resolve, 0))
expect(source.matchSpace!(proj('s2'), '/attach')).not.toBeUndefined()
})
})