@surfishs/dsh-prompt-enhance 0.1.0 → 0.1.2

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@surfishs/dsh-prompt-enhance",
3
3
  "description": "Prompt enhancement for the dsh web GUI: rewrite the composer draft into a well-structured prompt through the harness LLM service, preview the before/after, then fill back, copy, or undo. Original draft is always preserved.",
4
- "version": "0.1.0",
4
+ "version": "0.1.2",
5
5
  "author": "surfishs",
6
6
  "type": "module",
7
7
  "engines": {
@@ -46,3 +46,52 @@ export function FillIcon(): ReactElement {
46
46
  export function UndoIcon(): ReactElement {
47
47
  return icon([<path key="head" d="M9 14 4 9l5-5" />, <path key="curve" d="M4 9h10.5a5.5 5.5 0 0 1 0 11H8" />])
48
48
  }
49
+
50
+ /** A check mark: the applied/undo row's confirmation glyph. */
51
+ export function CheckIcon(): ReactElement {
52
+ return icon([<path key="check" d="m20 6-11 11-5-5" />])
53
+ }
54
+
55
+ /** Two diagonal strokes: close the card. Sized like the chevron so both header
56
+ * controls share one optical weight and their boxes centre the same way. */
57
+ export function XIcon(): ReactElement {
58
+ return (
59
+ <svg
60
+ width={18}
61
+ height={18}
62
+ viewBox="0 0 24 24"
63
+ fill="none"
64
+ stroke="currentColor"
65
+ strokeWidth={2}
66
+ strokeLinecap="round"
67
+ strokeLinejoin="round"
68
+ aria-hidden="true"
69
+ focusable="false"
70
+ style={{ display: 'block', flexShrink: 0 }}
71
+ >
72
+ <path d="M6 6l12 12" />
73
+ <path d="M18 6 6 18" />
74
+ </svg>
75
+ )
76
+ }
77
+
78
+ /** Down chevron: expanded when pointing down, collapsed when rotated to point right. */
79
+ export function ChevronIcon({ open }: { open: boolean }): ReactElement {
80
+ return (
81
+ <svg
82
+ width={20}
83
+ height={20}
84
+ viewBox="0 0 24 24"
85
+ fill="none"
86
+ stroke="currentColor"
87
+ strokeWidth={2}
88
+ strokeLinecap="round"
89
+ strokeLinejoin="round"
90
+ aria-hidden="true"
91
+ focusable="false"
92
+ style={{ display: 'block', flexShrink: 0, transform: open ? 'none' : 'rotate(-90deg)' }}
93
+ >
94
+ <path d="m6 9 6 6 6-6" />
95
+ </svg>
96
+ )
97
+ }
@@ -9,7 +9,7 @@
9
9
  * @module dsh-prompt-enhance/client/EnhanceButton
10
10
  */
11
11
 
12
- import { useCallback, useEffect, useRef, useSyncExternalStore, type ReactNode } from 'react'
12
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'
13
13
  import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
14
14
  import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
15
15
  import type { InputState } from '@deepseek-ai/dsh-client-ui-conversation/client'
@@ -19,10 +19,23 @@ import { EnhanceClientError, requestEnhance, requestEnhanceStream } from './enha
19
19
  import { SparkleFishIcon } from './SparkleFishIcon'
20
20
  import * as ui from './ui-state'
21
21
  import { getClientSettings, subscribeClientSettings } from './settings'
22
+ import { getSettingsWriter, subscribeSettingsWriter } from './settings-writer'
23
+ import { QuickSettingsMenu, type QuickMenuAnchor } from './QuickSettingsMenu'
24
+ import { directoryFaceOf, INHERIT_EFFORT, modelDirectoryOf, resolveQuickSettings, writeQuickContext, writeQuickEffort, type QuickContext, type QuickSettingsData } from './quick-settings'
22
25
  import { useSessionKey, serverSessionId } from './session-key'
23
26
 
24
27
  /** Props of the input.right entry: the InputZone owner share + session kit + locale seat. */
25
- export type EnhanceButtonProps = PropsRuntime<'conversation.input.right'> & PropsLocale<'dsh-prompt-enhance'>
28
+ export type EnhanceButtonProps = PropsRuntime<'conversation.input.right'> &
29
+ PropsLocale<'dsh-prompt-enhance'> & {
30
+ /** Client context handed in by the slot registration (the quick menu reads model directories through it). */
31
+ __ctx?: QuickContext
32
+ }
33
+
34
+ /** How long a press on the button must last to open the quick menu. */
35
+ const LONG_PRESS_MS = 600
36
+
37
+ /** Movement past this many pixels turns a long press back into a drag/click. */
38
+ const LONG_PRESS_SLOP_PX = 6
26
39
 
27
40
  /** Sentinel of {@link occurrenceCountOf} for a host that exposes no chip view. */
28
41
  const OCCURRENCES_UNKNOWN = -1
@@ -90,6 +103,218 @@ export function EnhanceButton(props: EnhanceButtonProps): ReactNode {
90
103
  /** No draft text at all (whitespace and attachment-only drafts count as empty): the icon dims and clicks are no-ops. */
91
104
  const empty = draft.trim() === ''
92
105
 
106
+ // ── quick settings ──────────────────────────────────────────────────────
107
+ // The writer arrives asynchronously (the settings source binds it after
108
+ // apply). Until it exists the entry does not exist either: a menu that
109
+ // cannot save is worse than no menu.
110
+ const writer = useSyncExternalStore(subscribeSettingsWriter, getSettingsWriter)
111
+ const [menu, setMenu] = useState<{ anchor: QuickMenuAnchor; data: QuickSettingsData } | null>(null)
112
+ const [menuError, setMenuError] = useState<string | undefined>(undefined)
113
+ const longPressTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
114
+ const longPressOrigin = useRef<{ x: number; y: number } | null>(null)
115
+ const longPressFired = useRef(false)
116
+
117
+ // Context writes are coalesced: one write is in flight at a time and only the
118
+ // newest requested state is written once it settles, so a fast double flip
119
+ // lands on the last click. The intent is kept in refs so the close path can
120
+ // start it at once instead of waiting behind the write already running.
121
+ const contextWrites = useRef<{
122
+ /** The state the user last asked for; null when nothing is waiting. */
123
+ desired: boolean | null
124
+ /** The last state the host accepted, and the baseline a failed write rolls back to. */
125
+ accepted: boolean | null
126
+ /** The state of the write currently in flight, if any. */
127
+ inFlight: boolean | null
128
+ running: boolean
129
+ /** Bumped per write so a superseded resolve can tell it lost the race. */
130
+ seq: number
131
+ closing: boolean
132
+ }>({ desired: null, accepted: null, inFlight: null, running: false, seq: 0, closing: false })
133
+ const flushContextRef = useRef<() => void>(() => {})
134
+
135
+ const applyContext = (value: boolean): void => {
136
+ setMenu((current) => (current === null ? current : { ...current, data: { ...current.data, contextAware: value } }))
137
+ }
138
+
139
+ /**
140
+ * Start the newest requested state once no write is in flight. "force" re-asserts
141
+ * the intent even when it matches the last accepted value, which is what a stale
142
+ * write that landed late requires.
143
+ */
144
+ const kickContextWrite = (force = false): void => {
145
+ const state = contextWrites.current
146
+ if (writer === undefined || state.running) return
147
+ const target = state.desired
148
+ if (target === null) return
149
+ const accepted = state.accepted ?? settings.contextAware
150
+ state.accepted = accepted
151
+ if (!force && target === accepted) {
152
+ state.desired = null
153
+ return
154
+ }
155
+ state.running = true
156
+ state.inFlight = target
157
+ const ticket = ++state.seq
158
+ void writeQuickContext(writer, target).then((ok) => {
159
+ state.running = false
160
+ state.inFlight = null
161
+ if (ticket !== state.seq) {
162
+ // The close flush already started a newer write; if this older one still
163
+ // reached the host, the host now holds it, so re-assert the newest intent.
164
+ if (ok && state.accepted !== null) {
165
+ state.desired = state.accepted
166
+ kickContextWrite(true)
167
+ }
168
+ return
169
+ }
170
+ if (!ok) {
171
+ state.desired = null
172
+ applyContext(state.accepted ?? settings.contextAware)
173
+ setMenuError(t('menu.writeFailed'))
174
+ return
175
+ }
176
+ state.accepted = target
177
+ if (state.desired === target) state.desired = null
178
+ kickContextWrite()
179
+ })
180
+ }
181
+
182
+ /**
183
+ * The card is leaving: start the pending intent now rather than queueing behind
184
+ * the write in flight. A refusal has no surface left to report on, so it is
185
+ * logged instead of shown.
186
+ */
187
+ const flushContextWrite = (): void => {
188
+ const state = contextWrites.current
189
+ if (writer === undefined || state.closing) return
190
+ const target = state.desired
191
+ if (target === null || target === state.inFlight) return
192
+ const accepted = state.accepted ?? settings.contextAware
193
+ // The in-flight write will overwrite the host, so an intent that merely equals
194
+ // the last accepted value still has to be written when something is in flight.
195
+ const supersededValue = state.inFlight !== null
196
+ state.accepted = accepted
197
+ state.desired = null
198
+ if (!supersededValue && target === accepted) return
199
+ state.closing = true
200
+ const ticket = ++state.seq
201
+ void writeQuickContext(writer, target).then((ok) => {
202
+ state.closing = false
203
+ if (!ok) {
204
+ console.warn('[dsh-prompt-enhance] the contextAware write was refused while closing the quick settings card')
205
+ return
206
+ }
207
+ if (ticket === state.seq) state.accepted = target
208
+ })
209
+ }
210
+ flushContextRef.current = flushContextWrite
211
+
212
+ /** Close the card, flushing a pending context flip first. */
213
+ const dismissMenu = useCallback((): void => {
214
+ flushContextRef.current()
215
+ setMenu(null)
216
+ }, [])
217
+
218
+ const toggleContext = (next: boolean): void => {
219
+ if (writer === undefined) return
220
+ const state = contextWrites.current
221
+ setMenuError(undefined)
222
+ applyContext(next)
223
+ state.desired = next
224
+ if (state.accepted === null) state.accepted = settings.contextAware
225
+ kickContextWrite()
226
+ }
227
+
228
+ // The stored settings feed the accepted baseline until the first write.
229
+ const reconcileEffort = useCallback(
230
+ async (data: QuickSettingsData): Promise<QuickSettingsData> => {
231
+ if (writer === undefined) return data
232
+ if (data.effort === '' || data.effort === INHERIT_EFFORT) return data
233
+ if (data.efforts.some((effort) => effort.id === data.effort)) return data
234
+ const cleared = await writeQuickEffort(writer, INHERIT_EFFORT)
235
+ if (!cleared) {
236
+ console.warn('[dsh-prompt-enhance] could not clear the stored reasoning effort for the current model')
237
+ return data
238
+ }
239
+ return { ...data, effort: INHERIT_EFFORT }
240
+ },
241
+ [writer],
242
+ )
243
+
244
+ // The stored settings feed the accepted baseline until the first write.
245
+ useEffect(() => {
246
+ const state = contextWrites.current
247
+ if (state.seq === 0 && state.desired === null) state.accepted = settings.contextAware
248
+ }, [settings.contextAware])
249
+
250
+ // Unmounting must not park a pending flip: start it and let it settle.
251
+ useEffect(() => () => flushContextRef.current(), [])
252
+
253
+ // While the card is open, follow the session's model directory (and a pinned
254
+ // route change): the tier list belongs to the model actually in use, so a
255
+ // switch made outside the card must swap the list instead of showing the
256
+ // previous model's tiers until the next open.
257
+ const menuOpen = menu !== null
258
+ useEffect(() => {
259
+ if (!menuOpen) return
260
+ const directory = directoryFaceOf(modelDirectoryOf(props.__ctx, sessionId))
261
+ const store = directory?.store
262
+ let cancelled = false
263
+ let timer: ReturnType<typeof setTimeout> | undefined
264
+ const refresh = (): void => {
265
+ if (cancelled) return
266
+ if (timer !== undefined) clearTimeout(timer)
267
+ timer = setTimeout(() => {
268
+ timer = undefined
269
+ void resolveQuickSettings({ ctx: props.__ctx, sessionId, settings }).then(async (resolved) => {
270
+ const data = await reconcileEffort(resolved)
271
+ if (cancelled) return
272
+ const local = contextWrites.current.desired ?? contextWrites.current.accepted
273
+ setMenu((current) => (current === null ? current : { ...current, data: local === null ? data : { ...data, contextAware: local } }))
274
+ })
275
+ }, 80)
276
+ }
277
+ const stop = store?.subscribe?.(refresh)
278
+ // Nudge the host directory so a model switched after the last load answers
279
+ // with the current catalog rather than the previous snapshot.
280
+ try {
281
+ void Promise.resolve(directory?.load?.()).catch(() => {})
282
+ } catch {
283
+ // A directory that refuses to load simply keeps the current snapshot.
284
+ }
285
+ return () => {
286
+ cancelled = true
287
+ if (timer !== undefined) clearTimeout(timer)
288
+ stop?.()
289
+ }
290
+ }, [menuOpen, props.__ctx, sessionId, settings, reconcileEffort])
291
+
292
+ const openMenu = useCallback(
293
+ async (rect: DOMRect): Promise<void> => {
294
+ const anchor = { right: rect.right, top: rect.top }
295
+ setMenuError(undefined)
296
+ const resolved = await resolveQuickSettings({ ctx: props.__ctx, sessionId, settings })
297
+ const data = await reconcileEffort(resolved)
298
+ // A flip that the mirror has not reflected yet still wins on reopen.
299
+ const local = contextWrites.current.desired ?? contextWrites.current.accepted
300
+ setMenu({ anchor, data: local === null ? data : { ...data, contextAware: local } })
301
+ },
302
+ [props.__ctx, sessionId, settings, reconcileEffort],
303
+ )
304
+
305
+ const pickEffort = (id: string): void => {
306
+ if (writer === undefined) return
307
+ // The choice applies on the click itself: close the card first and let the
308
+ // write land in the background, so the host round trip never reads as lag.
309
+ // With the card gone there is no surface left to report a refusal on.
310
+ const unchanged = menu !== null && menu.data.effort === id
311
+ dismissMenu()
312
+ if (unchanged) return
313
+ void writeQuickEffort(writer, id).then((ok) => {
314
+ if (!ok) console.warn('[dsh-prompt-enhance] the reasoningEffort write was refused')
315
+ })
316
+ }
317
+
93
318
  /** Guard chain + fetch + panel transition for this session. */
94
319
  const start = useCallback(
95
320
  (overrideText?: string): void => {
@@ -174,8 +399,78 @@ export function EnhanceButton(props: EnhanceButtonProps): ReactNode {
174
399
  }
175
400
  }, [draft, panel, uiKey])
176
401
 
402
+ // Right-click, a 600 ms press, or Shift+F10 / the context-menu key open the
403
+ // same menu. Registered only when the host can persist settings, so an
404
+ // unsupported host keeps exactly the old button behaviour.
405
+ useEffect(() => {
406
+ if (writer === undefined || !settings.enabled) return
407
+ const button = rootRef.current
408
+ if (button === null) return
409
+ const clearTimer = (): void => {
410
+ if (longPressTimer.current !== undefined) {
411
+ clearTimeout(longPressTimer.current)
412
+ longPressTimer.current = undefined
413
+ }
414
+ }
415
+ const onPointerDown = (event: PointerEvent): void => {
416
+ const target = event.target
417
+ if (!(target instanceof Node) || !button.contains(target)) return
418
+ clearTimer()
419
+ longPressFired.current = false
420
+ longPressOrigin.current = { x: event.clientX, y: event.clientY }
421
+ longPressTimer.current = setTimeout(() => {
422
+ longPressTimer.current = undefined
423
+ // The press itself must not also fire the enhance click on release.
424
+ longPressFired.current = true
425
+ void openMenu(button.getBoundingClientRect())
426
+ }, LONG_PRESS_MS)
427
+ }
428
+ const onPointerMove = (event: PointerEvent): void => {
429
+ const origin = longPressOrigin.current
430
+ if (origin === null) return
431
+ if (Math.abs(event.clientX - origin.x) > LONG_PRESS_SLOP_PX || Math.abs(event.clientY - origin.y) > LONG_PRESS_SLOP_PX) {
432
+ longPressOrigin.current = null
433
+ clearTimer()
434
+ }
435
+ }
436
+ const onPointerUp = (): void => {
437
+ longPressOrigin.current = null
438
+ clearTimer()
439
+ }
440
+ const onKeyDown = (event: KeyboardEvent): void => {
441
+ const menuKey = (event.shiftKey && event.key === 'F10') || event.key === 'ContextMenu'
442
+ if (!menuKey) return
443
+ if (document.activeElement !== button) return
444
+ event.preventDefault()
445
+ void openMenu(button.getBoundingClientRect())
446
+ }
447
+ document.addEventListener('pointerdown', onPointerDown, true)
448
+ document.addEventListener('pointermove', onPointerMove, true)
449
+ document.addEventListener('pointerup', onPointerUp, true)
450
+ document.addEventListener('pointercancel', onPointerUp, true)
451
+ document.addEventListener('keydown', onKeyDown, true)
452
+ return () => {
453
+ clearTimer()
454
+ document.removeEventListener('pointerdown', onPointerDown, true)
455
+ document.removeEventListener('pointermove', onPointerMove, true)
456
+ document.removeEventListener('pointerup', onPointerUp, true)
457
+ document.removeEventListener('pointercancel', onPointerUp, true)
458
+ document.removeEventListener('keydown', onKeyDown, true)
459
+ }
460
+ }, [writer, settings.enabled, openMenu])
461
+
177
462
  if (!settings.enabled) return null
178
463
 
464
+ // The tooltip carries the discoverability the entry cannot get from chrome. It
465
+ // rides along in every state: the card is reachable by right-click (and by
466
+ // long-press / Shift+F10) even while a plain click is inert, so an empty or
467
+ // busy button must not hide the way in.
468
+ const statusTitle = busy ? t('button.busy') : otherBusy ? t('button.otherBusy') : empty ? t('button.emptyTitle') : t('button.title')
469
+ // The hint names the way in while the card is actually reachable on hover; the
470
+ // busy states are short-lived and keep their own single message.
471
+ const quickHint = writer === undefined || busy || otherBusy ? '' : t('button.quickHint')
472
+ const buttonLabel = statusTitle + quickHint
473
+
179
474
  return (
180
475
  <>
181
476
  <button
@@ -186,20 +481,34 @@ export function EnhanceButton(props: EnhanceButtonProps): ReactNode {
186
481
  // Read by useDockAlignment (same attribute constant).
187
482
  data-dsh-pe-key={uiKey}
188
483
  className={`dsh-pe-btn${busy ? ' is-busy' : ''}${otherBusy && !empty ? ' is-blocked' : ''}${empty && !busy ? ' is-empty' : ''}`}
189
- title={busy ? t('button.busy') : otherBusy ? t('button.otherBusy') : empty ? t('button.emptyTitle') : t('button.title')}
190
- aria-label={busy ? t('button.busy') : otherBusy ? t('button.otherBusy') : empty ? t('button.emptyTitle') : t('button.title')}
484
+ title={buttonLabel}
485
+ aria-label={statusTitle}
486
+ aria-haspopup={writer === undefined ? undefined : 'menu'}
487
+ onContextMenu={(event) => {
488
+ if (writer === undefined) return
489
+ event.preventDefault()
490
+ void openMenu(event.currentTarget.getBoundingClientRect())
491
+ }}
191
492
  // `aria-disabled` instead of `disabled`: a disabled button is skipped by
192
493
  // the keyboard and by screen readers, so the reason this composer is
193
494
  // inert (empty draft, or another session's enhancement occupies the
194
495
  // single preview panel) would be unreachable exactly for the users who
195
496
  // need it. The click is a no-op either way.
196
497
  aria-disabled={empty || otherBusy || undefined}
197
- onClick={() => start()}
498
+ onClick={() => {
499
+ // A long press opened the menu; its trailing click must not enhance.
500
+ if (longPressFired.current) {
501
+ longPressFired.current = false
502
+ return
503
+ }
504
+ start()
505
+ }}
198
506
  >
199
507
  <span className="dsh-pe-btn-icon" aria-hidden>
200
508
  <SparkleFishIcon size={15} spinning={busy} />
201
509
  </span>
202
510
  </button>
511
+ {menu === null ? null : <QuickSettingsMenu t={t} data={menu.data} anchor={menu.anchor} error={menuError} onPick={pickEffort} onToggleContext={toggleContext} onClose={dismissMenu} />}
203
512
  </>
204
513
  )
205
514
  }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The quick-settings menu the composer button opens.
3
+ *
4
+ * Deliberately small: the reasoning tier (a radio list including "follow the
5
+ * provider default") and the context switch, nothing numeric. It renders as a
6
+ * fixed-position sibling of the button — no portal, because the client bundle
7
+ * has never depended on `react-dom` and a menu is not worth introducing that
8
+ * dependency. Escape and an outside click close it; Tab walks the items.
9
+ *
10
+ * The selected row is marked by a check at the right edge only: no bold, no
11
+ * accent colour — the same way the shell's own menus show a choice.
12
+ *
13
+ * The tier list is drilled, not expanded: the card opens showing one cell
14
+ * (推理等级 <current> ›) and activating it replaces the card content with
15
+ * the radio list, exactly like the shell's model menu switches panes. Escape
16
+ * backs out of the pane first and only then closes the menu.
17
+ * @module dsh-prompt-enhance/client/QuickSettingsMenu
18
+ */
19
+
20
+ import { useEffect, useRef, useState, type ReactElement } from 'react'
21
+ import { Switch } from '@deepseek-ai/dsh-client-ui-primitives'
22
+ import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
23
+ import { NS } from './locales'
24
+ import { INHERIT_EFFORT, menuOptionsOf, type QuickSettingsData } from './quick-settings'
25
+
26
+ /** Where the menu hangs, in viewport coordinates. */
27
+ export interface QuickMenuAnchor {
28
+ readonly right: number
29
+ readonly top: number
30
+ }
31
+
32
+ /** Props of one open menu. */
33
+ export interface QuickSettingsMenuProps {
34
+ t: TranslateNS<typeof NS>
35
+ data: QuickSettingsData
36
+ anchor: QuickMenuAnchor
37
+ /** Write failure shown in place; the menu stays open. */
38
+ error?: string
39
+ onPick(effort: string): void
40
+ onToggleContext(next: boolean): void
41
+ onClose(): void
42
+ }
43
+
44
+ /** One radio row: the label on the left, the check at the right. */
45
+ function MenuRow(props: { label: string; checked: boolean; role: 'menuitemradio'; onSelect(): void }): ReactElement {
46
+ const { label, checked, role, onSelect } = props
47
+ return (
48
+ <button type="button" role={role} aria-checked={checked} className="dsh-pe-menu-item" onClick={onSelect}>
49
+ <span className="dsh-pe-menu-label">{label}</span>
50
+ <span className="dsh-pe-menu-mark" aria-hidden>
51
+ {checked ? '✓' : ''}
52
+ </span>
53
+ </button>
54
+ )
55
+ }
56
+
57
+ /**
58
+ * Render the menu above its trigger, clamped to the viewport.
59
+ * @param props - the data, the anchor, and the actions.
60
+ * @returns the menu element.
61
+ */
62
+ export function QuickSettingsMenu(props: QuickSettingsMenuProps): ReactElement {
63
+ const { t, data, anchor, error, onPick, onToggleContext, onClose } = props
64
+ const ref = useRef<HTMLDivElement | null>(null)
65
+
66
+ const [pane, setPane] = useState<'root' | 'effort'>('root')
67
+ const paneRef = useRef<HTMLDivElement | null>(null)
68
+
69
+ useEffect(() => {
70
+ const onKeyDown = (event: KeyboardEvent): void => {
71
+ if (event.key !== 'Escape') return
72
+ event.preventDefault()
73
+ // Escape backs out of the drilled pane first, then closes — the shell's
74
+ // model menu behaves the same way.
75
+ setPane((current) => {
76
+ if (current === 'effort') return 'root'
77
+ onClose()
78
+ return current
79
+ })
80
+ }
81
+ const onPointerDown = (event: MouseEvent): void => {
82
+ const node = ref.current
83
+ if (node === null) return
84
+ const target = event.target
85
+ if (target instanceof Node && node.contains(target)) return
86
+ onClose()
87
+ }
88
+ document.addEventListener('keydown', onKeyDown, true)
89
+ document.addEventListener('mousedown', onPointerDown, true)
90
+ return () => {
91
+ document.removeEventListener('keydown', onKeyDown, true)
92
+ document.removeEventListener('mousedown', onPointerDown, true)
93
+ }
94
+ }, [onClose])
95
+
96
+ useEffect(() => {
97
+ if (pane !== 'effort') return
98
+ const checked = paneRef.current?.querySelector<HTMLElement>('[aria-checked="true"]')
99
+ checked?.focus()
100
+ }, [pane])
101
+
102
+ const viewportWidth = typeof window === 'undefined' ? 0 : window.innerWidth
103
+ const viewportHeight = typeof window === 'undefined' ? 0 : window.innerHeight
104
+ const right = Math.max(8, viewportWidth - anchor.right)
105
+ const bottom = Math.max(8, viewportHeight - anchor.top + 8)
106
+ const options = menuOptionsOf(data)
107
+ // The stored value is an id (off); the cell shows the tier's display name
108
+ // (Off) the same way the shell's trigger prints the model's effort name.
109
+ const currentEffort = options.find((option) => option.id === data.effort)
110
+ // A route that declares no tiers gets no radio rows at all: the appended
111
+ // stored-value row is only for naming the folded cell, not for offering a
112
+ // tier the model never declared.
113
+ const radioOptions = data.efforts.length === 0 ? [] : options
114
+ const effortValue = data.effort === INHERIT_EFFORT ? t('menu.effortDefault') : (currentEffort?.name ?? data.effort)
115
+ // Read-only mirror of the routing override: the card must never imply that
116
+ // the plugin's provider/model can be changed here (that lives on its page).
117
+ // Names come from the host catalogs; an id the registry stopped advertising
118
+ // still shows as its id.
119
+ const providerPart = data.providerLabel === '' ? data.provider : data.providerLabel
120
+ const modelPart = data.modelLabel === '' ? data.model : data.modelLabel
121
+ const pinnedRoute = [providerPart, modelPart].filter((part) => part !== '').join(' / ')
122
+ const modelValue = pinnedRoute === '' ? t('menu.modelFollow') : pinnedRoute
123
+
124
+ return (
125
+ <div ref={ref} className="dsh-pe-menu" role="menu" aria-label={t('menu.title')} style={{ position: 'fixed', right, bottom }}>
126
+ {pane === 'root' ? (
127
+ <>
128
+ <div className="dsh-pe-menu-info" title={t('menu.modelHint')}>
129
+ <span className="dsh-pe-menu-label">{t('menu.model')}</span>
130
+ <span className="dsh-pe-menu-state">{modelValue}</span>
131
+ </div>
132
+ <button type="button" role="menuitem" className="dsh-pe-menu-item dsh-pe-menu-cell" onClick={() => setPane('effort')}>
133
+ <span className="dsh-pe-menu-label">{t('menu.effort')}</span>
134
+ <span className="dsh-pe-menu-state">{effortValue}</span>
135
+ <span className="dsh-pe-menu-chevron" aria-hidden />
136
+ </button>
137
+ <div className="dsh-pe-menu-sep" role="separator" />
138
+ <div className="dsh-pe-menu-switch">
139
+ <span className="dsh-pe-menu-switch-label">{t('menu.context')}</span>
140
+ <Switch className="dsh-pe-menu-switch-input" checked={data.contextAware} label={t('menu.context')} onChange={(next: boolean) => onToggleContext(next)} />
141
+ </div>
142
+ </>
143
+ ) : (
144
+ <div ref={paneRef} className="dsh-pe-menu-group" role="group" aria-label={t('menu.effort')}>
145
+ <MenuRow role="menuitemradio" label={t('menu.effortDefault')} checked={data.effort === INHERIT_EFFORT} onSelect={() => onPick(INHERIT_EFFORT)} />
146
+ {radioOptions.map((option) => (
147
+ <MenuRow key={option.id} role="menuitemradio" label={option.name} checked={data.effort === option.id} onSelect={() => onPick(option.id)} />
148
+ ))}
149
+ {radioOptions.length > 0 ? null : (
150
+ <div className="dsh-pe-menu-note" role="status">
151
+ {data.effortReason === 'no-efforts' ? t('menu.effortsNone') : t('menu.effortsFailed')}
152
+ </div>
153
+ )}
154
+ </div>
155
+ )}
156
+ {error === undefined ? null : (
157
+ <div className="dsh-pe-menu-error" role="alert">
158
+ {error}
159
+ </div>
160
+ )}
161
+ </div>
162
+ )
163
+ }