Files
deepseek-harness/packages/client/ui-agent-preset/tests/apply.spec.ts
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

559 lines
24 KiB
TypeScript

/**
* Registration: the General row, the settings section, the new-session chip,
* and the header label all come from one apply, and each defers until the slot
* it fills has been declared. A pushed settings change refreshes the surfaces
* that are already showing, so a default set from one converges the other.
*/
import { Context } from '@deepseek-ai/cordis'
import { describe, expect, it, vi } from 'vitest'
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-agent-preset/client'
import { AgentPresetLabel } from '../src/client/AgentPresetLabel.tsx'
import type { AgentPresetLabelInjected } from '../src/client/AgentPresetLabel.tsx'
import { AgentPresetRow } from '../src/client/AgentPresetRow.tsx'
import type { AgentPresetRowInjected } from '../src/client/AgentPresetRow.tsx'
import { AgentPresetSection } from '../src/client/AgentPresetSection.tsx'
import type { AgentPresetSectionInjected } from '../src/client/AgentPresetSection.tsx'
import { AgentPresetSeat } from '../src/client/AgentPresetSeat.tsx'
import type { AgentPresetSeatInjected } from '../src/client/AgentPresetSeat.tsx'
// The service reads its initial locale from the browser; these specs assert
// the shipped Chinese copy, so they state the browser they assume.
usePinnedBrowserLanguages('zh-CN')
const ROSTER_ONE = {
rpcId: 'r',
result: {
ok: true as const,
value: {
presets: [{ id: 'standard', trust: 'system', isDefault: true }],
authorable: true,
hasDocument: true,
},
},
}
/** The roster after this browser copied one preset of its own. */
const ROSTER_AUTHORED = {
rpcId: 'r',
result: {
ok: true as const,
value: {
presets: [
{ id: 'standard', trust: 'system', isDefault: true },
{ id: 'mine', trust: 'user', isDefault: false },
],
authorable: true,
hasDocument: true,
},
},
}
/** The same roster with a second preset carrying the default. */
const ROSTER_MOVED = {
rpcId: 'r',
result: {
ok: true as const,
value: {
presets: [
{ id: 'standard', trust: 'system', isDefault: false },
{ id: 'minimal', trust: 'system', isDefault: true },
],
authorable: true,
hasDocument: true,
},
},
}
async function bench() {
const ctx = new Context()
// The host's answer, mutable so a spec can move the default the way the
// settings surface does and watch who re-reads it.
let ROSTER: typeof ROSTER_ONE | typeof ROSTER_MOVED | typeof ROSTER_AUTHORED = ROSTER_ONE
const moveDefault = (): void => { ROSTER = ROSTER_MOVED }
await ctx.plugin(SlotsService).await()
const locale = new LocaleService(ctx)
ctx.provide('locale', locale)
// The plugins inject `remote`; forwarded events reach them through the
// same `$dispatch` handoff the connection sink makes.
new TestRemote(ctx)
const calls: string[] = []
ctx.provide('connection', {
api: {
agentPresets: {
list: () => { calls.push('list'); return Promise.resolve(ROSTER) },
read: () => Promise.resolve({
rpcId: 'r',
result: { ok: true as const, value: { agentPreset: 'standard', trust: 'system', content: '' } },
}),
copy: (payload: { from: string; agentPreset: string }) => {
calls.push(`copy:${payload.agentPreset}`)
// The host's roster now contains it, which is the whole point of the
// copy and what every surface must converge on.
ROSTER = ROSTER_AUTHORED
return Promise.resolve({ rpcId: 'r', result: { ok: true as const, value: { agentPreset: payload.agentPreset } } })
},
openDocument: (payload: { agentPreset: string }) => {
calls.push(`openDocument:${payload.agentPreset}`)
return Promise.resolve({ rpcId: 'r', result: { ok: true as const, value: { opened: true as const } } })
},
remove: () => Promise.resolve({ rpcId: 'r', result: { ok: true as const, value: {} } }),
select: (payload: { agentPreset: string }) => {
calls.push(`select:${payload.agentPreset}`)
return Promise.resolve({ rpcId: 'r', result: { ok: true as const, value: { agentPreset: payload.agentPreset } } })
},
},
settings: {
// The row reads this to learn whether this browser may write at all.
describe: () => Promise.resolve({
rpcId: 'r',
result: { ok: true as const, value: { writable: true, hasDocument: true, namespaces: [] } },
}),
update: (payload: { patch: unknown }) => { calls.push(`settings:${JSON.stringify(payload.patch)}`); return Promise.resolve({ rpcId: 'r', result: { ok: true as const, value: {} } }) },
},
},
} as never)
return { ctx, slots: ctx.get('slots') as SlotsService, calls, moveDefault }
}
function declareRoot(slots: SlotsService): () => void {
return slots.register({
name: 'root',
children: {
'settings.general.item': { kind: 'list', scope: 'root' },
'settings.section': { kind: 'list', scope: 'root' },
conversation: { kind: 'single', scope: 'root' },
},
} as never, () => null)
}
/** The conversation's own declarations, which the chip and label wait for. */
function declareConversation(slots: SlotsService): () => void {
return slots.register({
name: 'conversation',
children: {
'conversation.hero.agentPreset': { kind: 'single', scope: 'root' },
'conversation.session.header.actions': { kind: 'list', scope: 'session' },
},
} as never, () => null)
}
/** A workspaces double recording new-session starts. */
function workspacesDouble() {
const starts: unknown[] = []
return {
starts,
startSession: (workspaceId?: unknown) => { starts.push(workspaceId ?? null) },
}
}
/** A sessions double whose list can be moved and whose changes are pushed. */
function sessionsDouble(state: {
current?: string
byId: Record<string, { id: string; blank: boolean; agentPreset?: string }>
}) {
const listeners = new Set<() => void>()
return {
list: {
getSnapshot: () => state,
subscribe: (fn: () => void) => {
listeners.add(fn)
return () => listeners.delete(fn)
},
},
/** Push a list change the way the runtime's store does. */
notify: () => { for (const fn of listeners) fn() },
}
}
describe('ui-agent-preset apply', () => {
it('declares the services it uses', () => {
expect(inject).toEqual(['slots', 'locale', 'connection', 'remote'])
})
it('registers the General row and the settings section', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
const row = slots.entries('settings.general.item')[0]!
expect(row.component).toBe(AgentPresetRow)
expect(row.options).toMatchObject({ id: 'agent-preset', order: -25 })
const section = slots.entries('settings.section')[0]!
expect(section.component).toBe(AgentPresetSection)
expect(section.options).toMatchObject({ id: 'agent-presets', order: 20 })
// The nav label is a locale-following thunk; owners resolve it at read time.
expect(resolveSlotLabel(section.options.label)).toBe('Agent 预设')
})
it('registers into a declaration that arrives after apply', async () => {
const { ctx, slots } = await bench()
await ctx.plugin({ inject: [...inject], apply }).await()
declareRoot(slots)
await vi.waitFor(() => { expect(slots.entries('settings.section')).toHaveLength(1) })
})
it('hands each surface its own store and actions', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
const row = (slots.entries('settings.general.item')[0]!.inject as unknown as () => AgentPresetRowInjected)()
const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)()
expect(row.hooks.agentPreset).not.toBe(section.hooks.agentPresetSection)
// Each thunk reaches its own controller: the row's load fills the row's
// store, and the section's default write does not go through the row.
await row.load()
await row.select('standard')
await section.makeDefault('standard')
expect(row.hooks.agentPreset.getSnapshot().options).toEqual([{ id: 'standard', trust: 'system' }])
expect(section.hooks.agentPresetSection.getSnapshot().rows)
.toEqual([{ id: 'standard', trust: 'system', isDefault: true }])
})
it('routes the section actions to one controller', async () => {
const { ctx, slots, calls } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)()
await section.load()
section.beginCopy('standard')
section.cancelCopy()
section.beginCopy('standard')
section.setCopyId('mine')
section.setCopyName('我的模式')
await section.confirmCopy()
await section.view('standard')
section.closeView()
section.confirmDelete('mine')
await Promise.all([section.openLocation('mine'), section.remove()])
// One controller behind every action: the copy the dialog named is the
// one the roster re-read reflects, and the delete the section confirmed
// is the one its remove() sees.
expect(calls).toContain('copy:mine')
expect(calls.filter(call => call === 'openDocument:mine').length).toBeGreaterThan(0)
expect(section.hooks.agentPresetSection.getSnapshot().rows).toHaveLength(2)
})
it('refreshes a showing surface when its namespace changes, and ignores others', async () => {
const { ctx, slots, calls } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)()
await section.load()
const before = calls.length
ctx.remote.$dispatch('settings/document-updated', ['agent-presets', 1])
await vi.waitFor(() => { expect(calls.length).toBe(before + 2) })
const afterRelevant = calls.length
ctx.remote.$dispatch('settings/document-updated', ['llm-deepseek', 1])
await Promise.resolve()
// Both surfaces re-read on their own namespace; an unrelated one moves
// neither, so this rules out a blanket refresh on every settings write.
expect(calls.length).toBe(afterRelevant)
})
it('re-reads both surfaces when the connection comes back', async () => {
const { ctx, slots, calls } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)()
await section.load()
const before = calls.length
ctx.emit('connection/reset')
// A reconnect can land on a host whose roster changed under the browser.
await vi.waitFor(() => { expect(calls.length).toBe(before + 2) })
})
it('leaves the section alone until it has been opened once', async () => {
const { ctx, slots, calls } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
const before = calls.length
ctx.remote.$dispatch('settings/document-updated', ['agent-presets', 1])
await vi.waitFor(() => { expect(calls.length).toBeGreaterThan(before) })
// Only the General row reloads: a section nobody opened has nothing to
// converge, and reading the roster for it would be a wasted round trip.
expect(calls.length - before).toBe(1)
})
it('registers the new-session chip and the header label, and drops both on disposal', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
const conversation = declareConversation(slots)
ctx.provide('conversation', {} as never)
ctx.provide('sessions', sessionsDouble({ byId: {} }) as never)
ctx.provide('workspaces', workspacesDouble() as never)
const fiber = ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply })
await fiber.await()
const chip = slots.entries('conversation.hero.agentPreset')[0]!
expect(chip.component).toBe(AgentPresetSeat)
const label = slots.entries('conversation.session.header.actions')[0]!
expect(label.component).toBe(AgentPresetLabel)
expect(label.options).toMatchObject({ id: 'agent-preset', order: -10 })
await fiber.dispose()
expect(slots.entries('conversation.hero.agentPreset')).toHaveLength(0)
expect(slots.entries('conversation.session.header.actions')).toHaveLength(0)
expect(slots.entries('settings.section')).toHaveLength(0)
conversation()
})
it('moves the chip when the default changes on the settings surface', async () => {
const { ctx, slots, moveDefault } = await bench()
declareRoot(slots)
const conversation = declareConversation(slots)
ctx.provide('conversation', {} as never)
ctx.provide('sessions', sessionsDouble({ byId: {} }) as never)
ctx.provide('workspaces', workspacesDouble() as never)
await ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply }).await()
const chip = slots.entries('conversation.hero.agentPreset')[0]!
const seat = (chip.inject as unknown as () => AgentPresetSeatInjected)()
await seat.load()
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('standard')
// The chip opens on the deployment default, and the setting it comes from
// lives on another screen: without this the next session — the very one
// the setting governs — would be composed from the previous default until
// a reload.
// An unrelated namespace moves nothing: the chip re-reads on its own
// setting, not on every settings write in the process.
moveDefault()
ctx.remote.$dispatch('settings/document-updated', ['llm-deepseek', 1])
await Promise.resolve()
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('standard')
ctx.remote.$dispatch('settings/document-updated', ['agent-presets', 1])
await vi.waitFor(() => {
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('minimal')
})
conversation()
})
it('offers a just-authored preset on the new-session chip', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
const conversation = declareConversation(slots)
ctx.provide('conversation', {} as never)
ctx.provide('sessions', sessionsDouble({ byId: {} }) as never)
ctx.provide('workspaces', workspacesDouble() as never)
await ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply }).await()
const chip = slots.entries('conversation.hero.agentPreset')[0]!
const seat = (chip.inject as unknown as () => AgentPresetSeatInjected)()
await seat.load()
expect(seat.hooks.agentPresetSeat.getSnapshot().options.map(option => option.id)).toEqual(['standard'])
const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)()
await section.load()
section.beginCopy('standard')
section.setCopyId('mine')
section.setCopyName('我的模式')
await section.confirmCopy()
// Authoring copies a directory rather than writing a setting, so nothing
// on the wire announces it: a preset created to be used must appear on
// the one screen that starts sessions, without a reload.
await vi.waitFor(() => {
expect(seat.hooks.agentPresetSeat.getSnapshot().options.map(option => option.id)).toEqual(['standard', 'mine'])
})
conversation()
})
it('applies the staged choice to the blank session the flow lands on', async () => {
const { ctx, slots, calls } = await bench()
declareRoot(slots)
declareConversation(slots)
ctx.provide('conversation', {} as never)
const state: {
current?: string
byId: Record<string, { id: string; blank: boolean; agentPreset?: string }>
} = { byId: {} }
const sessions = sessionsDouble(state)
ctx.provide('sessions', sessions as never)
ctx.provide('workspaces', workspacesDouble() as never)
await ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply }).await()
const chip = (slots.entries('conversation.hero.agentPreset')[0]!
.inject as unknown as () => AgentPresetSeatInjected)()
await chip.load()
// Picked on the hero screen, where there is no session yet.
await chip.select('minimal')
expect(calls).not.toContain('select:minimal')
state.current = 's1'
state.byId['s1'] = { id: 's1', blank: true, agentPreset: 'standard' }
sessions.notify()
// Connecting a workspace produced the session; the stage reaches it there.
await vi.waitFor(() => { expect(calls).toContain('select:minimal') })
})
it('applies the stage to a session that records no preset of its own', async () => {
const { ctx, slots, calls } = await bench()
declareRoot(slots)
declareConversation(slots)
ctx.provide('conversation', {} as never)
const sessions = sessionsDouble({
current: 's1',
byId: { s1: { id: 's1', blank: true } },
})
ctx.provide('sessions', sessions as never)
ctx.provide('workspaces', workspacesDouble() as never)
await ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply }).await()
const chip = (slots.entries('conversation.hero.agentPreset')[0]!
.inject as unknown as () => AgentPresetSeatInjected)()
await chip.load()
await chip.select('minimal')
// A session created before the deployment composed presets records none;
// reading that as "already runs it" would drop the pick on the floor.
expect(calls).toContain('select:minimal')
})
it('forgets the stage once it has been spent', async () => {
const { ctx, slots, calls } = await bench()
declareRoot(slots)
declareConversation(slots)
ctx.provide('conversation', {} as never)
const state = {
current: 's1',
byId: { s1: { id: 's1', blank: true, agentPreset: 'standard' } },
}
const sessions = sessionsDouble(state)
ctx.provide('sessions', sessions as never)
ctx.provide('workspaces', workspacesDouble() as never)
await ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply }).await()
const chip = (slots.entries('conversation.hero.agentPreset')[0]!
.inject as unknown as () => AgentPresetSeatInjected)()
await chip.load()
await chip.select('minimal')
const spent = calls.filter(call => call === 'select:minimal').length
sessions.notify()
sessions.notify()
// Every later list movement would re-apply a stage that was not cleared,
// switching sessions the user never picked for.
await Promise.resolve()
expect(calls.filter(call => call === 'select:minimal')).toHaveLength(spent)
})
it('gives the header label the same roster the General row reads', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
declareConversation(slots)
ctx.provide('conversation', {} as never)
ctx.provide('sessions', sessionsDouble({ byId: {} }) as never)
ctx.provide('workspaces', workspacesDouble() as never)
await ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply }).await()
const label = (slots.entries('conversation.session.header.actions')[0]!
.inject as unknown as () => AgentPresetLabelInjected)()
const row = (slots.entries('settings.general.item')[0]!
.inject as unknown as () => AgentPresetRowInjected)()
await label.load()
// One roster behind both: the label resolves a name the settings row's own
// load already fetched, rather than issuing a second read per session.
expect(label.hooks.agentPresets).toBe(row.hooks.agentPreset)
expect(label.hooks.agentPresets.getSnapshot().options).toEqual([{ id: 'standard', trust: 'system' }])
})
it('stages the creator preset and starts a session from the section', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
const conversation = declareConversation(slots)
ctx.provide('conversation', {} as never)
ctx.provide('sessions', sessionsDouble({ byId: {} }) as never)
const workspaces = workspacesDouble()
ctx.provide('workspaces', workspaces as never)
await ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply }).await()
const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)()
const seat = (slots.entries('conversation.hero.agentPreset')[0]!
.inject as unknown as () => AgentPresetSeatInjected)()
section.startCreatorDraft?.()
// The pick is staged on the chip's own controller — the session the
// workspace start produces is what the stage lands on — and exactly one
// new-session flow began.
expect(section.startCreatorDraft).toBeDefined()
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis')
expect(workspaces.starts).toHaveLength(1)
// A cross-screen stage carries the introduce cue; the chip acknowledges
// it once, and a repeat acknowledgement leaves the snapshot untouched.
expect(seat.hooks.agentPresetSeat.getSnapshot().introduce).toBe(true)
seat.introduced()
const acknowledged = seat.hooks.agentPresetSeat.getSnapshot()
expect(acknowledged.introduce).toBe(false)
seat.introduced()
expect(seat.hooks.agentPresetSeat.getSnapshot()).toBe(acknowledged)
conversation()
})
it('keeps the applied composition when the roster load lands late', async () => {
const { ctx, slots, calls } = await bench()
declareRoot(slots)
const conversation = declareConversation(slots)
ctx.provide('conversation', {} as never)
const state: {
current?: string
byId: Record<string, { id: string; blank: boolean; agentPreset?: string }>
} = { byId: {} }
const sessions = sessionsDouble(state)
ctx.provide('sessions', sessions as never)
ctx.provide('workspaces', workspacesDouble() as never)
await ctx.plugin({ inject: [...inject, 'conversation', 'sessions', 'workspaces'], apply }).await()
const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)()
const seat = (slots.entries('conversation.hero.agentPreset')[0]!
.inject as unknown as () => AgentPresetSeatInjected)()
section.startCreatorDraft?.()
state.current = 's1'
state.byId['s1'] = { id: 's1', blank: true }
sessions.notify()
await vi.waitFor(() => { expect(calls).toContain('select:cordis') })
// The chip mounts with the flow's session, so its roster load can land
// AFTER the stage was consumed; the session's own composition is what
// the display must keep — not the deployment default.
state.byId['s1'] = { id: 's1', blank: true, agentPreset: 'cordis' }
await seat.load()
expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis')
conversation()
})
it('offers no creator draft while the conversation flow is absent', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
// No conversation scope mounted: the face omits the affordance and the
// section hides its button rather than staging into nowhere.
const section = (slots.entries('settings.section')[0]!.inject as unknown as () => AgentPresetSectionInjected)()
expect(section.startCreatorDraft).toBeUndefined()
})
})