@linxin666/dsh-liangshen 0.3.23 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +55 -41
  3. package/README.zh.md +54 -40
  4. package/cordis.patch.yml +3 -2
  5. package/icon.svg +3 -0
  6. package/lib/client.js +1380 -29
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +616 -367
  9. package/lib/types/announce.test.d.ts +10 -0
  10. package/lib/types/client/LiangShenSettingsCard.d.ts +78 -0
  11. package/lib/types/client/PluginSettingsCard.d.ts +137 -0
  12. package/lib/types/client/index.d.ts +57 -4
  13. package/lib/types/client/lever-controller.d.ts +16 -2
  14. package/lib/types/client/locales.d.ts +40 -1
  15. package/lib/types/client/main-session.d.ts +32 -0
  16. package/lib/types/client/plugin-card-seat.d.ts +103 -0
  17. package/lib/types/client/settings-form.d.ts +197 -0
  18. package/lib/types/composition.d.ts +116 -0
  19. package/lib/types/composition.test.d.ts +7 -0
  20. package/lib/types/core/lever.d.ts +6 -3
  21. package/lib/types/index.d.ts +160 -33
  22. package/lib/types/index.test.d.ts +5 -0
  23. package/package.json +27 -18
  24. package/presets/liangshen/NOTICE +4 -4
  25. package/presets/liangshen/agent.cordis.yml +168 -123
  26. package/presets/liangshen/fact-ledger.mjs +141 -0
  27. package/presets/liangshen/guard.mjs +426 -0
  28. package/presets/liangshen/minimal-prompt.mjs +73 -38
  29. package/presets/liangshen/paging.mjs +232 -0
  30. package/presets/liangshen/tool-activate.mjs +176 -0
  31. package/presets/liangshen/tool-catalog.mjs +615 -219
  32. package/presets/liangshen/working-context.mjs +222 -0
  33. package/src/announce.test.ts +248 -55
  34. package/src/client/LiangShenLever.module.css +2 -0
  35. package/src/client/LiangShenLever.tsx +41 -10
  36. package/src/client/LiangShenSettingsCard.tsx +233 -0
  37. package/src/client/PluginSettingsCard.tsx +555 -0
  38. package/src/client/index.ts +102 -5
  39. package/src/client/lever-controller.ts +76 -9
  40. package/src/client/locales.ts +79 -1
  41. package/src/client/main-session.ts +43 -0
  42. package/src/client/plugin-card-seat.ts +192 -0
  43. package/src/client/settings-card.module.css +418 -0
  44. package/src/client/settings-form.ts +442 -0
  45. package/src/composition.test.ts +294 -0
  46. package/src/composition.ts +554 -0
  47. package/src/core/lever.ts +7 -4
  48. package/src/index.test.ts +68 -1
  49. package/src/index.ts +293 -101
  50. package/tools/benchmark-live-run.mjs +193 -63
  51. package/lib/types/schema.d.ts +0 -18
  52. package/lib/types/schema.test.d.ts +0 -1
  53. package/lib/types/sync.d.ts +0 -47
  54. package/lib/types/sync.test.d.ts +0 -1
  55. package/presets/liangshen/custom-bash.mjs +0 -213
  56. package/src/schema.test.ts +0 -64
  57. package/src/schema.ts +0 -110
  58. package/src/sync.test.ts +0 -224
  59. package/src/sync.ts +0 -222
@@ -0,0 +1,222 @@
1
+ /**
2
+ * working-context — the LiangShen preset's minimal recency projection: one
3
+ * durable user message carrying a single `[Working Context: ...]` line of the
4
+ * session's objective, machine-readable state, refreshed only when it changes.
5
+ *
6
+ * Every field is folded from the durable session event stream, so the line
7
+ * survives resume, reload, and compaction without any process-memory state,
8
+ * and every field is omitted when the log has nothing objective to say:
9
+ *
10
+ * - `plan mode: on|off` — from the session's `plan/mode` events (the last one
11
+ * wins, as the host's own plan projection folds them). Omitted when the log
12
+ * holds no `plan/mode` event at all: the ambient default is off, and the
13
+ * planMode service itself sits behind an isolate realm this preset row must
14
+ * not depend on.
15
+ * - `active namespaces: ...` — the paged tool namespaces currently on the
16
+ * wire, replayed from `tool_activate` calls exactly the way the wire
17
+ * partition in tool-catalog replays them.
18
+ * - `in progress: ...` — the in-progress todo titles from the latest
19
+ * `todo/write` event, cleared by the next `turn/start`, mirroring the host's
20
+ * todos projection.
21
+ *
22
+ * When no field has anything to say the step is left untouched. The injection
23
+ * and dedup discipline mirrors tool-catalog's pre-step: the message is
24
+ * persistent, carries the plugin source shape, and a replacement is published
25
+ * only when the rendered line changed or the published copy left the visible
26
+ * surface.
27
+ */
28
+
29
+ import {
30
+ DEFAULT_MAX_ACTIVE_NAMESPACES,
31
+ DEFAULT_PAGED_TOOL_PATTERNS,
32
+ integerAtLeast,
33
+ replayActivations,
34
+ validatePagedToolPatterns,
35
+ } from './paging.mjs'
36
+
37
+ import { foldFactLedger, renderLedgerField } from './fact-ledger.mjs'
38
+
39
+ /** Cordis plugin name used by loader diagnostics. */
40
+ export const name = 'liangshen-working-context'
41
+
42
+ /** Cap one rendered todo title so the line stays a single glance. */
43
+ const MAX_TITLE_CHARS = 80
44
+
45
+ /** At most this many in-progress titles render; the rest collapse to a count. */
46
+ const MAX_TITLES = 3
47
+
48
+ /** Session events, tolerating both snapshotEvents() and events array. */
49
+ function sessionEvents(session) {
50
+ if (Array.isArray(session?.events)) return session.events
51
+ if (typeof session?.snapshotEvents === 'function') return session.snapshotEvents()
52
+ return []
53
+ }
54
+
55
+ /** The latest plan/mode state in the log: seen flag plus active value. */
56
+ export function planModeState(events) {
57
+ let seen = false
58
+ let active = false
59
+ for (const event of Array.isArray(events) ? events : []) {
60
+ if (event?.type !== 'plan/mode' || typeof event.data?.active !== 'boolean') continue
61
+ seen = true
62
+ active = event.data.active
63
+ }
64
+ return { seen, active }
65
+ }
66
+
67
+ /**
68
+ * The in-progress todo titles as the host's todos projection folds them: the
69
+ * latest todo/write list, cleared by the next turn/start.
70
+ */
71
+ export function inProgressTodos(events) {
72
+ let todos
73
+ for (const event of Array.isArray(events) ? events : []) {
74
+ if (event?.type === 'turn/start') {
75
+ todos = undefined
76
+ continue
77
+ }
78
+ if (event?.type === 'todo/write' && Array.isArray(event.data?.todos)) {
79
+ todos = event.data.todos
80
+ }
81
+ }
82
+ return (todos ?? [])
83
+ .filter(item => item?.status === 'in_progress' && typeof item?.content === 'string' && item.content.trim() !== '')
84
+ .map(item => item.content.trim())
85
+ }
86
+
87
+ /** Clip one title to the per-title budget at a word-ish boundary. */
88
+ function clipTitle(title) {
89
+ if (title.length <= MAX_TITLE_CHARS) return title
90
+ return `${title.slice(0, MAX_TITLE_CHARS - 3)}...`
91
+ }
92
+
93
+ /**
94
+ * Render the working-context line for one session's events, or undefined when
95
+ * no field has anything objective to say.
96
+ */
97
+ export function renderWorkingContext(events, options) {
98
+ const patterns = options?.pagedToolPatterns ?? DEFAULT_PAGED_TOOL_PATTERNS
99
+ const maxActive = options?.maxActiveNamespaces ?? DEFAULT_MAX_ACTIVE_NAMESPACES
100
+ const fields = []
101
+
102
+ const plan = planModeState(events)
103
+ if (plan.seen) fields.push(`plan mode: ${plan.active ? 'on' : 'off'}`)
104
+
105
+ const { active } = replayActivations(events, maxActive, patterns)
106
+ if (active.length > 0) fields.push(`active namespaces: ${[...active].sort().join(', ')}`)
107
+
108
+ const titles = inProgressTodos(events)
109
+ if (titles.length > 0) {
110
+ const shown = titles.slice(0, MAX_TITLES).map(clipTitle)
111
+ const rest = titles.length - shown.length
112
+ fields.push(`in progress: ${shown.join('; ')}${rest > 0 ? `; +${rest} more` : ''}`)
113
+ }
114
+
115
+ // The key-fact register: facts the model pinned with fact_register, folded
116
+ // from the same event stream, ride this line so they land inside the local
117
+ // attention window every step.
118
+ const ledgerField = renderLedgerField(foldFactLedger(events))
119
+ if (ledgerField !== undefined) fields.push(ledgerField)
120
+
121
+ return fields.length === 0 ? undefined : `[Working Context: ${fields.join(' | ')}]`
122
+ }
123
+
124
+ /** The text one message contributes, joined across its text blocks. */
125
+ function textOf(message) {
126
+ const blocks = Array.isArray(message?.content) ? message.content : []
127
+ return blocks
128
+ .filter(block => block?.type === 'text' && typeof block.text === 'string')
129
+ .map(block => block.text)
130
+ .join('\n')
131
+ }
132
+
133
+ /** Whether one message is this plugin's working-context line. */
134
+ function isContextMessage(message) {
135
+ const source = message?.source
136
+ return source?.kind === name || (source?.kind === 'plugin' && source?.plugin === name)
137
+ }
138
+
139
+ /** Visible surface positions, or undefined when the session exposes none. */
140
+ function visibleSeqSet(session) {
141
+ const nodes = session?.surface?.nodes
142
+ return Array.isArray(nodes) ? new Set(nodes) : undefined
143
+ }
144
+
145
+ /**
146
+ * Published working-context state read back from the durable log: the latest
147
+ * visible line's text, or just the published flag when every copy was shadowed.
148
+ */
149
+ function contextHistory(agent) {
150
+ const session = agent?.session
151
+ const events = sessionEvents(session)
152
+ const visible = visibleSeqSet(session)
153
+ let published = false
154
+ for (let index = events.length - 1; index >= 0; index -= 1) {
155
+ const event = events[index]
156
+ if (event?.type !== 'user/message' || !isContextMessage(event.data)) continue
157
+ published = true
158
+ if (visible === undefined || typeof event.seq !== 'number' || visible.has(event.seq)) {
159
+ return { published, text: textOf(event.data) }
160
+ }
161
+ }
162
+ return { published }
163
+ }
164
+
165
+ /** Build the durable working-context message for one rendered line. */
166
+ export function createContextMessage(line) {
167
+ return {
168
+ id: globalThis.crypto.randomUUID(),
169
+ role: 'user',
170
+ content: [{ type: 'text', text: line }],
171
+ source: { kind: name },
172
+ }
173
+ }
174
+
175
+ /** Register the per-step working-context injection. */
176
+ export function apply(ctx, config) {
177
+ const pagedToolPatterns = validatePagedToolPatterns(name, config?.pagedToolPatterns)
178
+ const maxActiveNamespaces = integerAtLeast(
179
+ name,
180
+ config?.maxActiveNamespaces,
181
+ 'maxActiveNamespaces',
182
+ 1,
183
+ DEFAULT_MAX_ACTIVE_NAMESPACES,
184
+ )
185
+
186
+ ctx.on('agent/pre-step', async (payload, next) => {
187
+ const decision = await next()
188
+ if (decision.kind !== 'enter') return decision
189
+ const agent = payload?.agent
190
+ if (agent?.session === undefined) return decision
191
+
192
+ const line = renderWorkingContext(sessionEvents(agent.session), {
193
+ pagedToolPatterns,
194
+ maxActiveNamespaces,
195
+ })
196
+
197
+ const history = contextHistory(agent)
198
+ const existing = decision.messages.find(message => isContextMessage(message))
199
+
200
+ // Nothing objective to say: inject nothing. A stale published line is left
201
+ // for compaction to age out rather than replaced with an empty marker.
202
+ if (line === undefined) {
203
+ if (existing === undefined) return decision
204
+ return { ...decision, messages: decision.messages.filter(message => message.id !== existing.id) }
205
+ }
206
+
207
+ if (history.text === line) {
208
+ if (existing === undefined) return decision
209
+ return { ...decision, messages: decision.messages.filter(message => message.id !== existing.id) }
210
+ }
211
+ if (existing !== undefined && textOf(existing) === line) return decision
212
+
213
+ const message = createContextMessage(line)
214
+ if (existing === undefined) {
215
+ return { ...decision, messages: [...decision.messages, message] }
216
+ }
217
+ return {
218
+ ...decision,
219
+ messages: decision.messages.map(item => (item.id === existing.id ? message : item)),
220
+ }
221
+ }, { prepend: true })
222
+ }
@@ -1,76 +1,269 @@
1
1
  /**
2
- * Announcement behavior (issue #839): the system-prompt announcement ships
3
- * OFF by default and only registers when announceToAgent is on. The apply
4
- * path is exercised against a minimal fake context; each test re-imports the
5
- * module so the mount-once guard cannot swallow a second apply call.
2
+ * The host half against a fake cordis context: announcing (issue #839) and the
3
+ * preset DECLARATION that replaces the pre-0.1.7 preset-file sync.
4
+ *
5
+ * Declare = enabled: activation registers the bundled preset with
6
+ * `ctx.agentPresets` and keeps the returned disposer, a committed settings write
7
+ * re-declares through `loader/volatile-update`, and unloading releases the
8
+ * registration. Each test re-imports the module so the mount-once guard cannot
9
+ * swallow a second apply call.
6
10
  */
7
- import { mkdtempSync } from 'node:fs'
8
- import { tmpdir } from 'node:os'
9
- import { join } from 'node:path'
10
- import process from 'node:process'
11
- import { describe, expect, it, vi } from 'vitest'
12
-
13
- interface FakePrompt {
14
- section: (spec: { name: string; order: number; text: string }) => () => void
11
+
12
+ import { afterEach, describe, expect, it, vi } from 'vitest'
13
+
14
+ import type { PresetDefinition } from '@deepseek-ai/dsh-agent-preset-registry'
15
+ import { bundledPresetDir, resolveConfig } from '../src/index.ts'
16
+
17
+ /** Disposer the fake registry hands back for one declaration. */
18
+ interface FakeRegistration {
19
+ /** The definition the plugin declared. */
20
+ definition: PresetDefinition
21
+ /** Whether the plugin released this registration. */
22
+ released: boolean
15
23
  }
16
24
 
17
- function makeCtx(sections: ReturnType<typeof vi.fn>[] = []) {
18
- const registered: Array<{ name: string; order: number; text: string }> = []
19
- const systemPrompt: FakePrompt = {
20
- section(spec) {
21
- registered.push(spec)
22
- return () => {}
25
+ /** The host surface `apply` touches, with everything the tests observe. */
26
+ interface FakeHost {
27
+ ctx: never
28
+ /** The sections the announcement registered, in order. */
29
+ sections: { name: string, order: number, text: string }[]
30
+ /** The declarations the plugin submitted, in order. */
31
+ declarations: FakeRegistration[]
32
+ /** Logger lines the plugin emitted. */
33
+ warnings: string[]
34
+ /** Run every disposer the plugin registered through `ctx.effect`. */
35
+ unload(): Promise<void>
36
+ /** Dispatch `loader/volatile-update` to this fiber's listeners. */
37
+ commit(): void
38
+ }
39
+
40
+ /** Build a fake host context; `withRegistry: false` models a deployment without one. */
41
+ function makeHost(options: { withRegistry?: boolean } = {}): FakeHost {
42
+ const sections: FakeHost['sections'] = []
43
+ const declarations: FakeRegistration[] = []
44
+ const warnings: string[] = []
45
+ const effects: unknown[] = []
46
+ const listeners = new Map<string, ((...args: unknown[]) => void)[]>()
47
+ const registry = options.withRegistry === false ? undefined : {
48
+ register: async (definition: PresetDefinition) => {
49
+ const record: FakeRegistration = { definition, released: false }
50
+ declarations.push(record)
51
+ return async () => { record.released = true }
52
+ },
53
+ }
54
+ const ctx = {
55
+ systemPrompt: {
56
+ section: (spec: { name: string, order: number, text: string }) => {
57
+ sections.push(spec)
58
+ return () => {}
59
+ },
60
+ },
61
+ effect: (fn: () => unknown) => {
62
+ const disposer = fn()
63
+ effects.push(disposer)
64
+ return disposer
65
+ },
66
+ on: (event: string, listener: (...args: unknown[]) => void) => {
67
+ const list = listeners.get(event) ?? []
68
+ list.push(listener)
69
+ listeners.set(event, list)
70
+ return () => { listeners.set(event, (listeners.get(event) ?? []).filter(entry => entry !== listener)) }
23
71
  },
72
+ get: (name: string) => (name === 'agentPresets' ? registry : undefined),
73
+ logger: { warn: (message: string) => { warnings.push(message) }, info: () => {} },
24
74
  }
25
75
  return {
26
- ctx: {
27
- systemPrompt,
28
- effect: (fn: () => () => void) => fn(),
29
- inject: vi.fn(),
30
- logger: { warn: vi.fn(), info: vi.fn() },
31
- } as never,
32
- registered,
76
+ ctx: ctx as never,
77
+ sections,
78
+ declarations,
79
+ warnings,
80
+ async unload() {
81
+ for (const disposer of effects.splice(0)) {
82
+ if (typeof disposer === 'function') await (disposer as () => unknown)()
83
+ }
84
+ },
85
+ commit() {
86
+ for (const listener of listeners.get('loader/volatile-update') ?? []) listener([])
87
+ },
33
88
  }
34
89
  }
35
90
 
91
+ /**
92
+ * Flush the declaration queue. It is pure promise chaining, so a bounded run of
93
+ * microtask turns settles it without a timer (and without depending on wall
94
+ * clock time).
95
+ */
96
+ async function settle(): Promise<void> {
97
+ for (let turn = 0; turn < 64; turn += 1) await Promise.resolve()
98
+ }
99
+
100
+ /**
101
+ * Hosts mounted by this file, released after each test: the plugin's mount-once
102
+ * guard is process-wide, so a host left mounted would silence the next apply.
103
+ */
104
+ const mounted: FakeHost[] = []
105
+
106
+ afterEach(async () => {
107
+ for (const host of mounted.splice(0)) await host.unload()
108
+ })
109
+
110
+ /** One loaded module plus the host it was applied to. */
111
+ async function mount(
112
+ config?: Record<string, unknown>,
113
+ options: { withRegistry?: boolean } = {},
114
+ ): Promise<{ mod: typeof import('../src/index.ts'), host: FakeHost }> {
115
+ vi.resetModules()
116
+ const mod = await import('../src/index.ts')
117
+ const host = makeHost(options)
118
+ mounted.push(host)
119
+ mod.apply(host.ctx, config as never)
120
+ await settle()
121
+ return { mod, host }
122
+ }
123
+
36
124
  describe('dsh-liangshen announcement (issue #839)', () => {
37
- it('resolves announceToAgent to false by default in the schema', async () => {
125
+ it('operator keeps the announcement off until the schema default is changed', async () => {
126
+ // Given the shipped Config schema, When the operator reads its defaults,
127
+ // Then the announcement stays off while the plugin itself stays enabled.
38
128
  vi.resetModules()
39
129
  const mod = await import('../src/index.ts')
40
- const value = mod.Config({})
41
- expect(value.announceToAgent).toBe(false)
42
- expect(value.enabled).toBe(true)
130
+ expect(resolveConfig(mod.Config({}))).toMatchObject({ announceToAgent: false, enabled: true })
43
131
  })
44
132
 
45
- it('registers the announcement section when announceToAgent is on', async () => {
46
- vi.resetModules()
47
- const home = mkdtempSync(join(tmpdir(), 'liangshen-announce-'))
48
- const previous = process.env.DSH_HOME
49
- process.env.DSH_HOME = home
50
- try {
51
- const mod = await import('../src/index.ts')
52
- const { ctx, registered } = makeCtx()
53
- mod.apply(ctx, { announceToAgent: true })
54
- expect(registered.length).toBe(1)
55
- expect(registered[0]?.name).toBe('plugin:dsh-liangshen')
56
- expect(registered[0]?.text).toBe(mod.LIANGSHEN_GUIDANCE)
57
- } finally {
58
- process.env.DSH_HOME = previous
133
+ it('operator turns the announcement on and the section carries the guidance', async () => {
134
+ // Given a config that announces the plugin, When the operator activates
135
+ // it, Then one system-prompt section carries the guidance text.
136
+ const { mod, host } = await mount({ announceToAgent: true })
137
+ expect(host.sections.length).toBe(1)
138
+ expect(host.sections[0]?.name).toBe('plugin:dsh-liangshen')
139
+ expect(host.sections[0]?.text).toBe(mod.LIANGSHEN_GUIDANCE)
140
+ })
141
+
142
+ it('operator keeps every prompt clean under the default config', async () => {
143
+ // Given an activation with no config at all, When the operator mounts the
144
+ // plugin, Then no announcement section registers.
145
+ const { host } = await mount(undefined)
146
+ expect(host.sections.length).toBe(0)
147
+ })
148
+ })
149
+
150
+ describe('dsh-liangshen preset declaration', () => {
151
+ it('operator gets the bundled preset declared at activation and released on unload', async () => {
152
+ // Given a host whose registry is mounted, When the operator activates the
153
+ // plugin, Then the shipped preset is declared and unload releases it.
154
+ const { host } = await mount(undefined)
155
+ expect(host.declarations.length).toBe(1)
156
+ const { definition } = host.declarations[0]!
157
+ expect(definition.id).toBe('liangshen')
158
+ // Display text comes from the preset's own preset.yml, so the roster shows
159
+ // the same name an installed copy would.
160
+ expect(definition.name).toBe('梁神模式')
161
+ expect(definition.order).toBe(4)
162
+ expect(definition.plugins.length).toBeGreaterThan(20)
163
+ // Relative module names point inside the bundled preset directory: the
164
+ // registry mounts the declaration under its own loader base.
165
+ for (const plugin of definition.plugins) {
166
+ if ((plugin.name ?? '').startsWith('file:')) expect(plugin.name).toContain('presets')
59
167
  }
168
+ await host.unload()
169
+ expect(host.declarations[0]?.released).toBe(true)
60
170
  })
61
171
 
62
- it('keeps silent with the default config (announceToAgent off)', async () => {
172
+ it('operator gets the committed settings applied to the rows they shape', async () => {
173
+ // Given committed presentation and guard settings, When the operator
174
+ // activates the plugin, Then the declared rows carry those values.
175
+ const { host } = await mount({ presentation: 'ptc', guardEnabled: false, guardEchoFailures: 5 })
176
+ const rows = host.declarations[0]!.definition.plugins as readonly { id?: string, config?: Record<string, unknown> }[]
177
+ expect(rows.find(row => row.id === 'tool-catalog')?.config?.['presentation']).toBe('ptc')
178
+ expect(rows.find(row => row.id === 'guard')?.config).toEqual({
179
+ enabled: false,
180
+ sensitivity: 'balanced',
181
+ stallReasoningChars: 8000,
182
+ globalStallCap: 4,
183
+ echoFailures: 5,
184
+ })
185
+ })
186
+
187
+ it('operator keeps the roster and the prompt untouched while the master switch is off', async () => {
188
+ // Given a disabled row that still asks for the announcement, When the
189
+ // operator activates it, Then nothing is declared and nothing is announced.
190
+ const { host } = await mount({ enabled: false, announceToAgent: true })
191
+ expect(host.declarations.length).toBe(0)
192
+ expect(host.sections.length).toBe(0)
193
+ })
194
+
195
+ it('operator sees a committed settings write re-declare the preset', async () => {
196
+ // Given a running row whose volatile references the Host commits into,
197
+ // When the operator writes a new presentation and the Loader announces it,
198
+ // Then the preset is declared again and the previous declaration released.
63
199
  vi.resetModules()
64
- const home = mkdtempSync(join(tmpdir(), 'liangshen-announce-'))
65
- const previous = process.env.DSH_HOME
66
- process.env.DSH_HOME = home
67
- try {
68
- const mod = await import('../src/index.ts')
69
- const { ctx, registered } = makeCtx()
70
- mod.apply(ctx, undefined)
71
- expect(registered.length).toBe(0)
72
- } finally {
73
- process.env.DSH_HOME = previous
74
- }
200
+ const mod = await import('../src/index.ts')
201
+ let presentation = 'both'
202
+ let announceToAgent = false
203
+ const host = makeHost()
204
+ mounted.push(host)
205
+ mod.apply(host.ctx, {
206
+ presentation: { get: () => presentation } as never,
207
+ announceToAgent: { get: () => announceToAgent } as never,
208
+ })
209
+ await settle()
210
+ expect(host.declarations.length).toBe(1)
211
+
212
+ presentation = 'native'
213
+ announceToAgent = true
214
+ host.commit()
215
+ await settle()
216
+ expect(host.declarations.length).toBe(2)
217
+ expect(host.declarations[0]?.released).toBe(true)
218
+ const rows = host.declarations[1]!.definition.plugins as readonly { id?: string, config?: Record<string, unknown> }[]
219
+ expect(rows.find(row => row.id === 'tool-catalog')?.config?.['presentation']).toBe('native')
220
+ expect(host.sections.length).toBe(1)
221
+ })
222
+
223
+ it('operator gets a burst of settings writes settled on the last one', async () => {
224
+ // Given a running row and two committed writes in a row, When the operator
225
+ // lets the declaration queue drain, Then one live declaration holds the
226
+ // last value and every predecessor is released.
227
+ vi.resetModules()
228
+ const mod = await import('../src/index.ts')
229
+ let presentation = 'both'
230
+ const host = makeHost()
231
+ mounted.push(host)
232
+ mod.apply(host.ctx, { presentation: { get: () => presentation } as never })
233
+ await settle()
234
+ presentation = 'native'
235
+ host.commit()
236
+ presentation = 'ptc'
237
+ host.commit()
238
+ await settle()
239
+ const live = host.declarations.filter(record => !record.released)
240
+ expect(live.length).toBe(1)
241
+ const rows = live[0]!.definition.plugins as readonly { id?: string, config?: Record<string, unknown> }[]
242
+ expect(rows.find(row => row.id === 'tool-catalog')?.config?.['presentation']).toBe('ptc')
243
+ })
244
+
245
+ it('operator keeps a registry-less deployment running with a warning', async () => {
246
+ // Given a deployment that composes no agent-preset registry, When the
247
+ // operator activates the plugin, Then it warns instead of failing.
248
+ const { host } = await mount(undefined, { withRegistry: false })
249
+ expect(host.declarations.length).toBe(0)
250
+ expect(host.warnings.join('\n')).toContain('agent-preset registry is unavailable')
251
+ })
252
+
253
+ it('operator gets no declaration when a write lands while the row unloads', async () => {
254
+ // Given an unloaded row, When a settings write still reaches its
255
+ // listener, Then no preset is declared for it.
256
+ const { host } = await mount(undefined)
257
+ await host.unload()
258
+ host.commit()
259
+ await settle()
260
+ // The committed write must not re-declare a preset for an unloaded row.
261
+ expect(host.declarations.filter(record => !record.released).length).toBe(0)
262
+ })
263
+
264
+ it('operator has the bundled preset directory holding the composition', () => {
265
+ // Given the installed package, When the operator reads the bundled preset
266
+ // directory, Then it names the presets tree.
267
+ expect(bundledPresetDir()).toContain('presets')
75
268
  })
76
269
  })
@@ -29,6 +29,8 @@
29
29
  font: inherit;
30
30
  cursor: pointer;
31
31
  touch-action: none;
32
+ user-select: none;
33
+ -webkit-user-select: none;
32
34
  transition: background-color 0.16s ease, color 0.16s ease;
33
35
  }
34
36
 
@@ -29,13 +29,27 @@ const MORSE = '-.. . . .--. ... . . -.- / .... .- .-. -. . ... ...'
29
29
  /** One spark per spoke of the burst. */
30
30
  const SPARKS = Array.from({ length: 14 }, (_, index) => index)
31
31
 
32
+ /** Sync the hero preset chip above the composer so both controls always agree. */
33
+ function syncHeroChip(label: string): void {
34
+ try {
35
+ if (typeof document === 'undefined') return
36
+ const chip = document.querySelector<HTMLElement>('button[aria-haspopup="menu"] span[class*="seatLabel"]')
37
+ ?? Array.from(document.querySelectorAll<HTMLElement>('button[aria-haspopup="menu"] span')).find(s => s.className.includes('seatLabel'))
38
+ if (chip && chip.textContent !== label) {
39
+ chip.textContent = label
40
+ }
41
+ } catch {
42
+ // Non-browser or detached element
43
+ }
44
+ }
45
+
32
46
  /** Slot entry for `conversation.input.right` (left of the model selector). */
33
47
  export function LiangShenLever(face: LeverFace): ReactElement | null {
34
48
  const snapshot = useSyncExternalStore(face.store.subscribe, face.store.getSnapshot)
35
49
  const { state, restoreLabel, busy, error, burst } = snapshot
36
50
  const [burstKey, setBurstKey] = useState(0)
37
51
  const seen = useRef(burst)
38
- const drag = useRef<{ y: number, fired: boolean } | undefined>(undefined)
52
+ const drag = useRef<{ x: number, y: number, fired: boolean } | undefined>(undefined)
39
53
  const actionable = !busy && (state === 'on' || state === 'off')
40
54
  const on = state === 'on'
41
55
  const errorText = error === undefined
@@ -61,11 +75,25 @@ export function LiangShenLever(face: LeverFace): ReactElement | null {
61
75
  return () => { clearTimeout(timer) }
62
76
  }, [burstKey])
63
77
 
78
+ // Keep the hero preset chip above the composer in sync with the lever's selection
79
+ const prevState = useRef(state)
80
+ useEffect(() => {
81
+ if (state === 'on') {
82
+ syncHeroChip(face.t('lever.name'))
83
+ } else if (prevState.current === 'on' && state === 'off' && restoreLabel !== '') {
84
+ syncHeroChip(restoreLabel)
85
+ }
86
+ prevState.current = state
87
+ }, [state, restoreLabel, face])
88
+
64
89
  // The lever exists only while the preset can still change, which is the
65
90
  // blank-session window: a started session reports `locked`, a deployment
66
91
  // without the preset reports `missing`, and both mean the row renders
67
92
  // nothing instead of a dead control in the composer of a running session.
68
- if (state === 'locked' || state === 'missing') return null
93
+ // An `on` lever with an empty restore label has nothing to return to either
94
+ // (the roster supplies no other usable preset), so a push there would be the
95
+ // same dead control: render nothing rather than a switch that eats gestures.
96
+ if (state === 'locked' || state === 'missing' || (state === 'on' && restoreLabel === '')) return null
69
97
 
70
98
  const toggle = (): void => {
71
99
  if (!actionable) return
@@ -75,20 +103,23 @@ export function LiangShenLever(face: LeverFace): ReactElement | null {
75
103
 
76
104
  const onPointerDown = (event: ReactPointerEvent<HTMLButtonElement>): void => {
77
105
  if (!actionable) return
78
- drag.current = { y: event.clientY, fired: false }
79
- event.currentTarget.setPointerCapture?.(event.pointerId)
106
+ drag.current = { x: event.clientX, y: event.clientY, fired: false }
107
+ try {
108
+ event.currentTarget.setPointerCapture?.(event.pointerId)
109
+ } catch {
110
+ // Defensive: some environments throw on pointer capture
111
+ }
80
112
  }
81
113
 
82
114
  const onPointerMove = (event: ReactPointerEvent<HTMLButtonElement>): void => {
83
115
  const pending = drag.current
84
116
  if (pending === undefined || pending.fired) return
85
- const travel = event.clientY - pending.y
86
- if (travel >= DRAG_THRESHOLD_PX) {
87
- pending.fired = true
88
- face.pull()
89
- } else if (travel <= -DRAG_THRESHOLD_PX) {
117
+ const travelY = event.clientY - pending.y
118
+ const travelX = event.clientX - pending.x
119
+ if (Math.hypot(travelX, travelY) >= DRAG_THRESHOLD_PX) {
90
120
  pending.fired = true
91
- face.push()
121
+ if (on) face.push()
122
+ else face.pull()
92
123
  }
93
124
  }
94
125