@yx333221c/dsh-question-pacing 0.0.0-stage → 0.1.1

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/client.js ADDED
@@ -0,0 +1,845 @@
1
+ /**
2
+ * Question pacing — browser half.
3
+ *
4
+ * Three surfaces over one model:
5
+ *
6
+ * - the asking-level control in the composer tool row, editing this Session's
7
+ * override;
8
+ * - a settings section holding the global defaults both knobs fall back to;
9
+ * - a dock row above the composer that counts questions still waiting for an
10
+ * answer and reopens one.
11
+ *
12
+ * The countdown itself stays the shipped one. This plugin only decides how long
13
+ * it runs, which is why the control shows a duration rather than counting
14
+ * anything down: the Host owns the deadline and the native question card owns
15
+ * the countdown in its own header (with its own pause).
16
+ *
17
+ * Everything reads the shared store below, so a global change made in Settings
18
+ * is visible in a mounted composer control without reopening it.
19
+ */
20
+
21
+ window.__ModuleLoader__.load({
22
+ id: '@yx333221c/dsh-question-pacing',
23
+ factory(require) {
24
+ const React = require('react')
25
+ const { createPortal } = require('react-dom')
26
+ const h = React.createElement
27
+ const { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } = React
28
+
29
+ const ROUTE = '/question-pacing/api/state'
30
+ const ROOT = 'question-pacing'
31
+
32
+ /** Level ids, in ascending order of how readily the agent asks. */
33
+ const TIERS = ['minimal', 'rarely', 'balanced', 'often', 'mandatory']
34
+
35
+ /** Countdown choices offered by the control, in seconds. */
36
+ const WAITS = [30, 60, 120, 300, 600]
37
+
38
+ /**
39
+ * Bilingual copy, in the module rather than the slot locale seat so all
40
+ * surfaces share one table. The package's `locale/*.json` holds the
41
+ * plugin-page metadata a locale switch reads.
42
+ *
43
+ * Level labels state exactly what `core.js#tierPolicy` instructs: `minimal`
44
+ * keeps two exceptions, and `mandatory` keeps its "unless told otherwise",
45
+ * because a label that promises more than the prompt delivers is a lie the
46
+ * user cannot see.
47
+ */
48
+ const COPY = {
49
+ en: {
50
+ control: 'Asking',
51
+ triggerAria: label => `How often the agent asks: ${label}`,
52
+ popoverAria: 'Asking level and question countdown',
53
+ levelHeader: 'How freely the agent asks',
54
+ waitHeader: 'Question countdown',
55
+ followGlobal: 'Follow the defaults',
56
+ followGlobalHint: 'Clear both overrides for this session',
57
+ sessionScope: 'Changes apply to this session only.',
58
+ failed: 'Could not save',
59
+ retry: 'Retry',
60
+ routeMissing: 'The Host half is not loaded yet. Enable Question pacing under Settings → Plugins, then reload the page.',
61
+ loading: 'Loading…',
62
+ pendingNote: 'When it ends the agent continues on its own; the question stays answerable.',
63
+ overridden: 'overridden',
64
+ noChoiceSelected: 'Current value',
65
+ tiers: {
66
+ minimal: ['Only when asked', 'When you explicitly ask to be consulted, or before something irreversible.'],
67
+ rarely: ['Ask rarely', 'Only when a missing fact blocks the work and no tool can find it.'],
68
+ balanced: ['Ask sometimes', 'When the answer changes what gets built and the workspace cannot settle it.'],
69
+ often: ['Ask often', 'Before large or hard-to-undo work, and on ambiguous requests.'],
70
+ mandatory: ['Ask at every step', 'Before each step that changes the result, unless you said not to ask.'],
71
+ },
72
+ settingsTitle: 'Question pacing',
73
+ settingsLead: 'How freely the agent asks, and how long a question card counts down before the agent continues on its own. A session can override both from the composer.',
74
+ settingsLevel: 'Default asking level',
75
+ settingsWait: 'Default countdown',
76
+ settingsReset: 'Clear the defaults',
77
+ minute: 'min',
78
+ second: 's',
79
+ unanswered: count => (count === 1 ? '1 unanswered question' : `${String(count)} unanswered questions`),
80
+ unansweredHint: 'The agent has moved on. Choose one to reopen its card.',
81
+ reopened: 'Reopened this question.',
82
+ reopenUnavailable: 'This page holds no card for that question; open the session it belongs to.',
83
+ },
84
+ zh: {
85
+ control: '提问',
86
+ triggerAria: label => `agent 提问的主动程度:${label}`,
87
+ popoverAria: '提问等级与提问倒计时',
88
+ levelHeader: 'agent 提问的主动程度',
89
+ waitHeader: '提问倒计时',
90
+ followGlobal: '跟随默认设置',
91
+ followGlobalHint: '清除本会话的两项单独设置',
92
+ sessionScope: '修改只作用于本会话。',
93
+ failed: '保存失败',
94
+ retry: '重试',
95
+ routeMissing: '宿主半边尚未加载:请在「设置 → 插件」中启用提问节奏,然后刷新页面。',
96
+ loading: '加载中…',
97
+ pendingNote: '倒计时结束后 agent 会先继续工作,问题仍然可以回答。',
98
+ overridden: '已单独设置',
99
+ noChoiceSelected: '当前值',
100
+ tiers: {
101
+ minimal: ['只在被要求时问', '仅在你明确要求被征询时,或动手前会造成不可逆后果时。'],
102
+ rarely: ['尽量少问', '只有缺少某个事实、且工具查不到时才问。'],
103
+ balanced: ['适中', '答案会改变产出、且工作区里找不到依据时才问。'],
104
+ often: ['多问', '大改动、难回退的工作前,以及需求有歧义时。'],
105
+ mandatory: ['每一步都问', '每个会改变结果的步骤前都问,除非你说过不要问。'],
106
+ },
107
+ settingsTitle: '提问节奏',
108
+ settingsLead: '控制 agent 提问的主动程度,以及提问卡片倒计时的长度(倒计时结束 agent 会先继续工作)。本会话可在输入框工具行单独覆盖。',
109
+ settingsLevel: '默认提问等级',
110
+ settingsWait: '默认倒计时',
111
+ settingsReset: '清除默认设置',
112
+ minute: '分钟',
113
+ second: '秒',
114
+ unanswered: count => `${String(count)} 组未回复的问题`,
115
+ unansweredHint: 'agent 已经先继续工作了。选一条可以重新打开它的卡片。',
116
+ reopened: '已重新打开这个问题。',
117
+ reopenUnavailable: '本页没有这张卡片;请打开它所属的会话。',
118
+ },
119
+ }
120
+
121
+ /** Read the active locale id defensively. */
122
+ function safeLocale(locale) {
123
+ try {
124
+ return String(locale?.getLocale?.()?.active ?? '')
125
+ } catch {
126
+ return ''
127
+ }
128
+ }
129
+
130
+ /** Subscribe to the locale snapshot so a language switch is reflected live. */
131
+ function useLocaleId(locale) {
132
+ const subscribe = useCallback(listener => {
133
+ if (locale === undefined || typeof locale.subscribe !== 'function') return () => {}
134
+ return locale.subscribe(listener)
135
+ }, [locale])
136
+ const getSnapshot = useCallback(() => safeLocale(locale), [locale])
137
+ return useSyncExternalStore(subscribe, getSnapshot, () => '')
138
+ }
139
+
140
+ /** Copy for an active locale id. */
141
+ function copyFor(activeId) {
142
+ return String(activeId ?? '').toLowerCase().startsWith('zh') ? COPY.zh : COPY.en
143
+ }
144
+
145
+ /** Whether a value is a known level id. */
146
+ function isTier(value) {
147
+ return typeof value === 'string' && TIERS.includes(value)
148
+ }
149
+
150
+ /** A countdown as `45s` / `45 秒`, or `2 min` / `2 分钟`. */
151
+ function waitLabel(seconds, copy) {
152
+ const value = Number(seconds)
153
+ if (!Number.isFinite(value) || value <= 0) return ''
154
+ if (value < 60) return `${String(Math.round(value))}${copy.second}`
155
+ const minutes = value / 60
156
+ const text = Number.isInteger(minutes) ? String(minutes) : minutes.toFixed(1)
157
+ return `${text} ${copy.minute}`
158
+ }
159
+
160
+ /* ------------------------------------------------------------------ *
161
+ * Shared store
162
+ *
163
+ * Both composer and settings surfaces read this one cache, so a global
164
+ * write is reflected in a mounted trigger. Entries are keyed by the
165
+ * session the Host computed `effective` for ('' = global view), and every
166
+ * write refetches the keys that are loaded: a global change moves the
167
+ * effective value of every session that does not override that knob.
168
+ * ------------------------------------------------------------------ */
169
+
170
+ const ABSENT = Object.freeze({ status: 'loading' })
171
+ const store = new Map()
172
+ const listeners = new Set()
173
+
174
+ /** Notify every mounted surface. */
175
+ function emit() {
176
+ for (const listener of [...listeners]) listener()
177
+ }
178
+
179
+ /** Subscribe one surface. */
180
+ function subscribe(listener) {
181
+ listeners.add(listener)
182
+ return () => { listeners.delete(listener) }
183
+ }
184
+
185
+ /** The cached entry for one key, never undefined. */
186
+ function entryOf(key) {
187
+ return store.get(key) ?? ABSENT
188
+ }
189
+
190
+ /** Session query string for one key. */
191
+ function queryOf(key) {
192
+ return key === '' ? '' : `?session=${encodeURIComponent(key)}`
193
+ }
194
+
195
+ /** Fetch one key and cache it. */
196
+ async function fetchKey(key) {
197
+ try {
198
+ const response = await fetch(`${ROUTE}${queryOf(key)}`, {
199
+ method: 'GET',
200
+ credentials: 'same-origin',
201
+ headers: { accept: 'application/json' },
202
+ })
203
+ if (response.status === 404) {
204
+ store.set(key, { status: 'missing' })
205
+ emit()
206
+ return
207
+ }
208
+ if (!response.ok) throw new Error(`the Host answered ${response.status}`)
209
+ const data = await response.json()
210
+ store.set(key, { status: 'ready', data })
211
+ } catch (cause) {
212
+ store.set(key, {
213
+ status: 'error',
214
+ detail: cause?.message ?? String(cause),
215
+ })
216
+ }
217
+ emit()
218
+ }
219
+
220
+ /** Fetch every key currently cached, plus one more if it is new. */
221
+ async function refreshAll(extra) {
222
+ const keys = new Set(store.keys())
223
+ keys.add('')
224
+ if (extra !== undefined) keys.add(extra)
225
+ await Promise.all([...keys].map(key => fetchKey(key)))
226
+ }
227
+
228
+ /** Write one patch, then refresh what the change could have moved. */
229
+ async function writePatch(patch, key) {
230
+ const response = await fetch(`${ROUTE}${queryOf(key)}`, {
231
+ method: 'PUT',
232
+ credentials: 'same-origin',
233
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
234
+ body: JSON.stringify({ patch, sessionId: key === '' ? undefined : key }),
235
+ })
236
+ const payload = await response.json().catch(() => ({}))
237
+ if (!response.ok) throw new Error(payload.detail ?? payload.error ?? `the Host answered ${response.status}`)
238
+ if (payload?.effective !== undefined) store.set(key, { status: 'ready', data: payload })
239
+ emit()
240
+ await refreshAll(key)
241
+ }
242
+
243
+ /**
244
+ * Subscribe one surface to its key, loading it on first use.
245
+ * @param sessionId - session identity, or undefined for the global view.
246
+ * @returns the cached entry plus a writer that reports failure to the caller.
247
+ */
248
+ function usePacing(sessionId) {
249
+ const key = sessionId === undefined ? '' : String(sessionId)
250
+ const entry = useSyncExternalStore(subscribe, () => entryOf(key), () => ABSENT)
251
+ const [busy, setBusy] = useState(false)
252
+ const [failure, setFailure] = useState('')
253
+ const alive = useRef(true)
254
+
255
+ useEffect(() => {
256
+ alive.current = true
257
+ return () => { alive.current = false }
258
+ }, [])
259
+
260
+ useEffect(() => {
261
+ if (entry.status !== 'loading') return
262
+ void fetchKey(key)
263
+ }, [entry.status, key])
264
+
265
+ const apply = useCallback(async patch => {
266
+ setBusy(true)
267
+ setFailure('')
268
+ try {
269
+ await writePatch(patch, key)
270
+ return true
271
+ } catch (cause) {
272
+ if (alive.current) setFailure(cause?.message ?? String(cause))
273
+ return false
274
+ } finally {
275
+ if (alive.current) setBusy(false)
276
+ }
277
+ }, [key])
278
+
279
+ const reload = useCallback(() => { void fetchKey(key) }, [key])
280
+
281
+ return { entry, busy, failure, apply, reload }
282
+ }
283
+
284
+ /** Style vocabulary; theme tokens only, so light and dark both hold. */
285
+ const S = {
286
+ // Matches the sibling composer chips (model / permission): borderless,
287
+ // 28px high, 13/20 label in the secondary tone.
288
+ trigger: {
289
+ display: 'inline-flex', alignItems: 'center', gap: 4,
290
+ minWidth: 0, maxWidth: 190, height: 28, padding: '0 4px 0 8px',
291
+ border: 'none', borderRadius: 'var(--dsw-radius-sm)', outline: 'none',
292
+ background: 'transparent', color: 'var(--dsw-alias-label-secondary)',
293
+ font: 'inherit', fontSize: 13, lineHeight: '20px', cursor: 'pointer',
294
+ whiteSpace: 'nowrap',
295
+ },
296
+ triggerText: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
297
+ triggerValue: { flex: '0 0 auto', opacity: 0.75 },
298
+ // The override marker: a state, not an error, so it uses the warn tone
299
+ // already reserved for "something to notice" in this product.
300
+ dot: {
301
+ width: 5, height: 5, borderRadius: '50%', flex: '0 0 auto',
302
+ background: 'var(--dsw-alias-state-warn-primary)',
303
+ },
304
+ // Elevated surface: same material as the shipped dropdowns (no border,
305
+ // the prominent elevation shadow and the l1 elevation stroke).
306
+ popover: {
307
+ position: 'fixed', zIndex: 1100, boxSizing: 'border-box',
308
+ padding: 4, borderRadius: 'var(--dsw-radius-md)',
309
+ border: 0,
310
+ '--dsw-elevation-stroke-color': 'var(--dsw-alias-border-l1)',
311
+ background: 'var(--dsw-alias-bg-overlay)',
312
+ boxShadow: 'var(--dsw-elevation-prominent)',
313
+ color: 'var(--dsw-alias-label-primary)', fontSize: 12,
314
+ // Tall enough that the wrapped zh hints do not force scrolling; the
315
+ // scroll below is the fallback on a short viewport, not the norm.
316
+ maxHeight: 'min(78vh, 580px)', overflowY: 'auto',
317
+ },
318
+ header: {
319
+ padding: '6px 8px 3px', fontSize: 10.5, letterSpacing: '0.04em',
320
+ textTransform: 'uppercase', color: 'var(--dsw-alias-label-secondary)',
321
+ },
322
+ row: {
323
+ display: 'flex', alignItems: 'flex-start', gap: 8, width: '100%',
324
+ padding: '6px 8px', borderRadius: 6, border: 'none', background: 'transparent',
325
+ color: 'inherit', font: 'inherit', textAlign: 'left', cursor: 'pointer',
326
+ },
327
+ rowCopy: { display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0, flex: '1 1 auto' },
328
+ rowLabel: { fontSize: 12.5, lineHeight: 1.4 },
329
+ rowHint: { fontSize: 11, lineHeight: 1.4, color: 'var(--dsw-alias-label-secondary)' },
330
+ check: { flex: '0 0 auto', width: 12, color: 'var(--dsw-alias-label-primary)' },
331
+ divider: { height: 1, margin: '4px 2px', background: 'var(--dsw-alias-border-l1)' },
332
+ error: { padding: '4px 8px 6px', fontSize: 11, color: 'var(--dsw-alias-state-error-primary)' },
333
+ note: { padding: '4px 8px 6px', fontSize: 10.5, lineHeight: 1.45, color: 'var(--dsw-alias-label-secondary)' },
334
+ section: { display: 'flex', flexDirection: 'column', gap: 10, color: 'var(--dsw-alias-label-primary)' },
335
+ card: {
336
+ border: '1px solid var(--dsw-alias-border-l1)', borderRadius: 'var(--dsw-radius-md)',
337
+ background: 'var(--dsw-alias-bg-layer-1)', padding: 12,
338
+ display: 'flex', flexDirection: 'column', gap: 14,
339
+ },
340
+ groupTitle: { margin: 0, fontSize: 12.5, fontWeight: 600 },
341
+ chipRow: { display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 },
342
+ chip: selected => ({
343
+ padding: '4px 10px', borderRadius: 999, font: 'inherit', fontSize: 12, cursor: 'pointer',
344
+ border: `0.5px solid ${selected ? 'var(--dsw-alias-border-l2)' : 'var(--dsw-alias-border-l1)'}`,
345
+ background: selected ? 'var(--dsw-alias-interactive-bg-hover)' : 'transparent',
346
+ color: 'var(--dsw-alias-label-primary)',
347
+ fontWeight: selected ? 600 : 400,
348
+ }),
349
+ hint: { margin: '8px 0 0', fontSize: 11, lineHeight: 1.5, color: 'var(--dsw-alias-label-secondary)' },
350
+ link: {
351
+ alignSelf: 'flex-start', padding: 0, border: 'none', background: 'transparent',
352
+ color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: 11.5, cursor: 'pointer',
353
+ textDecoration: 'underline',
354
+ },
355
+ dock: { display: 'flex', flexDirection: 'column', gap: 2, padding: '2px 2px 4px' },
356
+ // A bordered chip, not bare text: it has to read as a control, and it
357
+ // has to hold that shape over the chat body it floats above.
358
+ dockButton: {
359
+ display: 'inline-flex', alignSelf: 'flex-start', alignItems: 'center', gap: 6,
360
+ padding: '2px 10px', borderRadius: 999,
361
+ border: '0.5px solid var(--dsw-alias-border-l2)',
362
+ background: 'var(--dsw-alias-bg-layer-1)',
363
+ color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: 11.5,
364
+ lineHeight: '18px', cursor: 'pointer',
365
+ },
366
+ dockDot: {
367
+ width: 6, height: 6, borderRadius: '50%', flex: '0 0 auto',
368
+ background: 'var(--dsw-alias-state-warn-primary)',
369
+ },
370
+ dockList: {
371
+ display: 'flex', flexDirection: 'column', gap: 1, alignItems: 'flex-start',
372
+ paddingLeft: 10,
373
+ borderLeft: '0.5px solid var(--dsw-alias-border-l1)', marginLeft: 10,
374
+ },
375
+ dockItem: {
376
+ display: 'inline-flex', alignItems: 'center', gap: 6, maxWidth: '100%',
377
+ padding: '2px 8px', borderRadius: 6, border: 'none', background: 'transparent',
378
+ color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: 11.5, cursor: 'pointer',
379
+ textAlign: 'left',
380
+ },
381
+ dockIndex: {
382
+ flex: '0 0 auto', minWidth: 14, fontSize: 10.5, textAlign: 'right',
383
+ color: 'var(--dsw-alias-label-secondary)',
384
+ },
385
+ dockItemText: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
386
+ dockNote: { paddingLeft: 10, fontSize: 10.5, color: 'var(--dsw-alias-label-secondary)' },
387
+ }
388
+
389
+ /** Hover and focus treatment inline styles cannot express. */
390
+ const STYLE_TEXT = `
391
+ .${ROOT}-trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
392
+ .${ROOT}-trigger:focus-visible { box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }
393
+ .${ROOT}-trigger:disabled { cursor: default; opacity: 0.6; }
394
+ .${ROOT}-row:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
395
+ .${ROOT}-row:focus-visible { box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }
396
+ .${ROOT}-chip:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
397
+ .${ROOT}-chip:focus-visible { box-shadow: 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); }
398
+ `
399
+
400
+ const POPOVER_WIDTH = 296
401
+
402
+ /**
403
+ * Where the portalled popover goes.
404
+ *
405
+ * Measured height rather than a guess: the copy wraps differently per
406
+ * language, so a fixed estimate either overlaps the trigger or floats a
407
+ * large gap above it.
408
+ * @param rect - trigger rect.
409
+ * @param height - measured popover height, or 0 before the first paint.
410
+ * @returns fixed coordinates that keep the popover inside the viewport.
411
+ */
412
+ function placePopover(rect, height) {
413
+ const margin = 8
414
+ const width = Math.min(POPOVER_WIDTH, window.innerWidth - margin * 2)
415
+ const below = rect.bottom + 6
416
+ const flipUp = height > 0 && below + height > window.innerHeight - margin
417
+ const top = flipUp
418
+ ? Math.max(margin, rect.top - height - 6)
419
+ : Math.min(below, Math.max(margin, window.innerHeight - height - margin))
420
+ const left = Math.max(margin, Math.min(rect.left, window.innerWidth - width - margin))
421
+ return { top, left, width }
422
+ }
423
+
424
+ /** Stable empty projection value, so the hook never re-subscribes on absence. */
425
+ const EMPTY_ACTIVE = Object.freeze([])
426
+
427
+ /** One pickable row. */
428
+ function Row({ selected, label, hint: rowHint, onClick, disabled }) {
429
+ return h('button', {
430
+ type: 'button',
431
+ role: 'menuitemradio',
432
+ 'aria-checked': selected === true,
433
+ className: `${ROOT}-row`,
434
+ 'aria-disabled': disabled === true ? true : undefined,
435
+ onClick: () => { if (disabled !== true) onClick() },
436
+ style: { ...S.row, opacity: disabled === true ? 0.55 : 1 },
437
+ },
438
+ h('span', { style: S.rowCopy },
439
+ h('span', { style: S.rowLabel }, label),
440
+ rowHint === undefined ? null : h('span', { style: S.rowHint }, rowHint)),
441
+ h('span', { style: S.check, 'aria-hidden': true }, selected === true ? '✓' : ''))
442
+ }
443
+
444
+ /** The composer control: asking level and countdown, per session. */
445
+ function makeTrigger(locale) {
446
+ return function PacingTrigger(props) {
447
+ const activeLocale = useLocaleId(locale)
448
+ const copy = useMemo(() => copyFor(activeLocale), [activeLocale])
449
+ const sessionId = props.sessionId === undefined ? undefined : String(props.sessionId)
450
+ const pacing = usePacing(sessionId)
451
+ const [open, setOpen] = useState(false)
452
+ const [placement, setPlacement] = useState({ top: 0, left: 0, width: POPOVER_WIDTH })
453
+ const triggerRef = useRef(null)
454
+ const popoverRef = useRef(null)
455
+
456
+ const data = pacing.entry.status === 'ready' ? pacing.entry.data : undefined
457
+ const tier = isTier(data?.effective?.tier) ? data.effective.tier : 'balanced'
458
+ const wait = Number(data?.effective?.waitSeconds ?? 120)
459
+ const overridden = data?.effective?.sessionTier === true || data?.effective?.sessionWait === true
460
+ const tierCopy = copy.tiers[tier]
461
+
462
+ // A default is only a guess until the Host answers, so the trigger says
463
+ // so instead of presenting an unverified value as the current one.
464
+ const unavailable = pacing.entry.status === 'missing'
465
+ const failed = pacing.entry.status === 'error' || pacing.failure !== ''
466
+ const detail = pacing.failure !== '' ? pacing.failure : pacing.entry.detail
467
+ const label = data === undefined ? copy.control : `${copy.control} · ${tierCopy[0]}`
468
+ const stateText = unavailable ? copy.routeMissing
469
+ : failed ? `${copy.failed}${detail === undefined ? '' : `: ${detail}`}`
470
+ : undefined
471
+
472
+ const openMenu = () => {
473
+ const rect = triggerRef.current?.getBoundingClientRect()
474
+ if (rect !== undefined) setPlacement(placePopover(rect, 0))
475
+ setOpen(true)
476
+ }
477
+
478
+ // Measure after the first paint, then place from the real height.
479
+ useEffect(() => {
480
+ if (!open) return
481
+ const rect = triggerRef.current?.getBoundingClientRect()
482
+ const height = popoverRef.current?.offsetHeight ?? 0
483
+ if (rect !== undefined) setPlacement(placePopover(rect, height))
484
+ }, [open, copy])
485
+
486
+ useEffect(() => {
487
+ if (!open) return
488
+ popoverRef.current?.focus()
489
+ const closeOutside = event => {
490
+ if (triggerRef.current?.contains(event.target) === true) return
491
+ if (popoverRef.current?.contains(event.target) === true) return
492
+ setOpen(false)
493
+ }
494
+ const onKey = event => {
495
+ if (event.key === 'Escape') {
496
+ event.stopPropagation()
497
+ setOpen(false)
498
+ triggerRef.current?.focus()
499
+ return
500
+ }
501
+ // Roving focus over the rows, so the popover is keyboard-operable.
502
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return
503
+ const rows = [...(popoverRef.current?.querySelectorAll(`.${ROOT}-row:not([aria-disabled="true"])`) ?? [])]
504
+ if (rows.length === 0) return
505
+ event.preventDefault()
506
+ const at = rows.indexOf(document.activeElement)
507
+ const next = at === -1
508
+ ? (event.key === 'ArrowDown' ? 0 : rows.length - 1)
509
+ : (at + (event.key === 'ArrowDown' ? 1 : -1) + rows.length) % rows.length
510
+ rows[next]?.focus()
511
+ }
512
+ const onViewportChange = event => {
513
+ // A scroll INSIDE the popover must not close it: the list is
514
+ // taller than the popover, so drag-scrolling the thumb or the
515
+ // wheel is the normal way to reach the lower rows. Only a scroll
516
+ // of an outer box would leave a fixed popover behind its trigger.
517
+ if (event?.target instanceof Node && popoverRef.current?.contains(event.target) === true) return
518
+ setOpen(false)
519
+ }
520
+ document.addEventListener('mousedown', closeOutside)
521
+ document.addEventListener('keydown', onKey, true)
522
+ window.addEventListener('resize', onViewportChange)
523
+ window.addEventListener('scroll', onViewportChange, true)
524
+ return () => {
525
+ document.removeEventListener('mousedown', closeOutside)
526
+ document.removeEventListener('keydown', onKey, true)
527
+ window.removeEventListener('resize', onViewportChange)
528
+ window.removeEventListener('scroll', onViewportChange, true)
529
+ }
530
+ }, [open])
531
+
532
+ // A pick keeps the popover open: the two knobs are one decision, and a
533
+ // save failure has to stay visible where it happened.
534
+ const chooseTier = async next => {
535
+ if (next === tier && data?.effective?.sessionTier === true) return
536
+ // Picking the inherited value must not create a no-op override.
537
+ const inherited = next === (isTier(data?.global?.tier) ? data.global.tier : 'balanced')
538
+ await pacing.apply({ scope: 'session', sessionId, tier: inherited ? null : next })
539
+ }
540
+
541
+ const chooseWait = async next => {
542
+ const inherited = next === Number(data?.global?.waitSeconds ?? 120)
543
+ await pacing.apply({ scope: 'session', sessionId, waitSeconds: inherited ? null : next })
544
+ }
545
+
546
+ const followGlobal = async () => {
547
+ await pacing.apply({ scope: 'session', sessionId, tier: null, waitSeconds: null })
548
+ }
549
+
550
+ // Without a session there is nothing to scope an override to, so the
551
+ // control hides rather than editing a value that would apply to nobody.
552
+ const hidden = sessionId === undefined
553
+ const title = stateText ?? `${copy.triggerAria(tierCopy[0])} · ${waitLabel(wait, copy)}`
554
+ // A stored duration outside the offered choices still has to be visible.
555
+ const waitChoices = WAITS.includes(wait) ? WAITS : [...WAITS, wait].sort((a, b) => a - b)
556
+
557
+ return h(React.Fragment, null,
558
+ h('button', {
559
+ ref: triggerRef,
560
+ type: 'button',
561
+ className: `${ROOT}-trigger`,
562
+ 'aria-haspopup': 'dialog',
563
+ 'aria-expanded': open,
564
+ 'aria-label': copy.triggerAria(tierCopy[0]),
565
+ 'aria-invalid': failed ? true : undefined,
566
+ title,
567
+ style: {
568
+ ...S.trigger,
569
+ display: hidden ? 'none' : 'inline-flex',
570
+ color: failed ? 'var(--dsw-alias-state-error-primary)' : S.trigger.color,
571
+ },
572
+ onClick: () => { if (open) setOpen(false); else openMenu() },
573
+ },
574
+ h('span', { style: S.triggerText }, label),
575
+ h('span', { style: S.triggerValue }, waitLabel(wait, copy)),
576
+ overridden
577
+ ? h('span', { style: S.dot, 'aria-hidden': true, title: copy.overridden })
578
+ : null),
579
+
580
+ open ? createPortal(h('div', {
581
+ ref: popoverRef,
582
+ role: 'dialog',
583
+ tabIndex: -1,
584
+ 'aria-label': copy.popoverAria,
585
+ className: ROOT,
586
+ style: {
587
+ ...S.popover,
588
+ top: placement.top,
589
+ left: placement.left,
590
+ width: placement.width,
591
+ outline: 'none',
592
+ },
593
+ },
594
+ pacing.entry.status === 'loading'
595
+ ? h('div', { style: S.note }, copy.loading)
596
+ : null,
597
+ unavailable ? h('div', { style: S.error }, copy.routeMissing) : null,
598
+
599
+ pacing.entry.status === 'ready'
600
+ ? h(React.Fragment, null,
601
+ h('div', { style: S.header, id: `${ROOT}-level-header` }, copy.levelHeader),
602
+ h('div', { role: 'group', 'aria-labelledby': `${ROOT}-level-header` },
603
+ TIERS.map(id => h(Row, {
604
+ key: `tier-${id}`,
605
+ selected: tier === id,
606
+ label: copy.tiers[id][0],
607
+ hint: copy.tiers[id][1],
608
+ disabled: pacing.busy,
609
+ onClick: () => { void chooseTier(id) },
610
+ }))),
611
+ h('div', { style: S.divider }),
612
+ h('div', { style: S.header, id: `${ROOT}-wait-header` }, copy.waitHeader),
613
+ h('div', { role: 'group', 'aria-labelledby': `${ROOT}-wait-header` },
614
+ waitChoices.map(seconds => h(Row, {
615
+ key: `wait-${String(seconds)}`,
616
+ selected: wait === seconds,
617
+ label: waitLabel(seconds, copy),
618
+ disabled: pacing.busy,
619
+ onClick: () => { void chooseWait(seconds) },
620
+ }))),
621
+ overridden
622
+ ? h(React.Fragment, null,
623
+ h('div', { style: S.divider }),
624
+ h(Row, {
625
+ selected: false,
626
+ label: copy.followGlobal,
627
+ hint: copy.followGlobalHint,
628
+ disabled: pacing.busy,
629
+ onClick: () => { void followGlobal() },
630
+ }))
631
+ : null,
632
+ h('div', { style: S.note }, `${copy.pendingNote} ${copy.sessionScope}`))
633
+ : null,
634
+
635
+ failed
636
+ ? h('div', null,
637
+ h('div', { style: S.error }, `${copy.failed}${detail === undefined ? '' : `: ${detail}`}`),
638
+ h('button', {
639
+ type: 'button',
640
+ className: `${ROOT}-row`,
641
+ style: { ...S.row, fontSize: 11.5 },
642
+ onClick: () => { pacing.reload() },
643
+ }, copy.retry))
644
+ : null), document.body) : null)
645
+ }
646
+ }
647
+
648
+ /** The settings section: the global defaults an override falls back to. */
649
+ function makeSettings(locale) {
650
+ return function PacingSettings() {
651
+ const activeLocale = useLocaleId(locale)
652
+ const copy = useMemo(() => copyFor(activeLocale), [activeLocale])
653
+ const pacing = usePacing(undefined)
654
+ const data = pacing.entry.status === 'ready' ? pacing.entry.data : undefined
655
+ const tier = isTier(data?.effective?.tier) ? data.effective.tier : 'balanced'
656
+ const wait = Number(data?.effective?.waitSeconds ?? 120)
657
+ const stored = data?.global ?? {}
658
+ const hasStored = stored.tier !== undefined || stored.waitSeconds !== undefined
659
+ const failed = pacing.entry.status === 'error' || pacing.failure !== ''
660
+ const detail = pacing.failure !== '' ? pacing.failure : pacing.entry.detail
661
+ const unavailable = pacing.entry.status === 'missing'
662
+
663
+ const choose = patch => { void pacing.apply({ scope: 'global', ...patch }) }
664
+
665
+ if (unavailable) {
666
+ return h('div', { className: ROOT, style: S.section },
667
+ h('p', { style: { ...S.hint, margin: 0 } }, copy.routeMissing))
668
+ }
669
+
670
+ // The controls stay mounted while an error is shown: replacing them
671
+ // would leave the section dead with no way to retry.
672
+ return h('div', { className: ROOT, style: S.section },
673
+ h('p', { style: { ...S.hint, margin: 0 } }, copy.settingsLead),
674
+
675
+ failed
676
+ ? h('div', { style: { display: 'flex', gap: 10, alignItems: 'baseline' } },
677
+ h('span', { style: { ...S.hint, margin: 0, color: 'var(--dsw-alias-state-error-primary)' } },
678
+ `${copy.failed}${detail === undefined ? '' : `: ${detail}`}`),
679
+ h('button', {
680
+ type: 'button',
681
+ style: { ...S.link, color: 'var(--dsw-alias-label-secondary)' },
682
+ onClick: () => { pacing.reload() },
683
+ }, copy.retry))
684
+ : null,
685
+
686
+ data === undefined
687
+ ? h('p', { style: { ...S.hint, margin: 0 } }, copy.loading)
688
+ : h('div', { style: S.card },
689
+ h('div', null,
690
+ h('h3', { style: S.groupTitle }, copy.settingsLevel),
691
+ h('div', { role: 'group', 'aria-label': copy.settingsLevel, style: S.chipRow },
692
+ TIERS.map(id => h('button', {
693
+ key: id,
694
+ type: 'button',
695
+ className: `${ROOT}-chip`,
696
+ 'aria-pressed': tier === id,
697
+ disabled: pacing.busy,
698
+ style: S.chip(tier === id),
699
+ title: copy.tiers[id][1],
700
+ onClick: () => { choose({ tier: id }) },
701
+ }, copy.tiers[id][0]))),
702
+ h('p', { style: S.hint }, copy.tiers[tier][1])),
703
+ h('div', null,
704
+ h('h3', { style: S.groupTitle }, copy.settingsWait),
705
+ h('div', { role: 'group', 'aria-label': copy.settingsWait, style: S.chipRow },
706
+ (WAITS.includes(wait) ? WAITS : [...WAITS, wait].sort((a, b) => a - b)).map(seconds => h('button', {
707
+ key: String(seconds),
708
+ type: 'button',
709
+ className: `${ROOT}-chip`,
710
+ 'aria-pressed': wait === seconds,
711
+ disabled: pacing.busy,
712
+ style: S.chip(wait === seconds),
713
+ onClick: () => { choose({ waitSeconds: seconds }) },
714
+ }, waitLabel(seconds, copy)))),
715
+ h('p', { style: S.hint }, copy.pendingNote)),
716
+ hasStored
717
+ ? h('button', {
718
+ type: 'button',
719
+ style: S.link,
720
+ disabled: pacing.busy,
721
+ onClick: () => { choose({ tier: null, waitSeconds: null }) },
722
+ }, copy.settingsReset)
723
+ : null))
724
+ }
725
+ }
726
+
727
+ /**
728
+ * The dock entry that keeps unanswered questions visible.
729
+ *
730
+ * The composer seat holds ONE request at a time, so a second question — or
731
+ * the same one after its countdown ended — never gets a card of its own; it
732
+ * is reachable only through the `userQuestions` projection. This row makes
733
+ * that state visible and reversible.
734
+ *
735
+ * Only `continued` rows count: an `open` row is the card currently on
736
+ * screen, and counting it would claim the agent had moved on while the user
737
+ * is looking at the question.
738
+ */
739
+ function makeDock(locale, resolvePanels) {
740
+ return function UnansweredDock(props) {
741
+ const activeLocale = useLocaleId(locale)
742
+ const copy = useMemo(() => copyFor(activeLocale), [activeLocale])
743
+ const sessionId = props.sessionId === undefined ? undefined : String(props.sessionId)
744
+ const active = props.useProjection('userQuestions', view => view?.active ?? EMPTY_ACTIVE)
745
+ const [open, setOpen] = useState(false)
746
+ const [note, setNote] = useState('')
747
+
748
+ const waiting = useMemo(
749
+ () => active.filter(row => row.state === 'continued'),
750
+ [active],
751
+ )
752
+
753
+ // Every hook above runs unconditionally; only the output is conditional.
754
+ if (sessionId === undefined || waiting.length === 0) return null
755
+
756
+ const reveal = callId => {
757
+ const panels = resolvePanels()
758
+ const shown = panels?.reveal?.(sessionId, callId) === true
759
+ setNote(shown ? copy.reopened : copy.reopenUnavailable)
760
+ if (shown) setOpen(false)
761
+ }
762
+
763
+ return h('div', { style: S.dock },
764
+ h('button', {
765
+ type: 'button',
766
+ className: `${ROOT}-row`,
767
+ 'aria-expanded': open,
768
+ title: copy.unansweredHint,
769
+ style: S.dockButton,
770
+ onClick: () => { setOpen(value => !value); setNote('') },
771
+ },
772
+ h('span', { style: S.dockDot, 'aria-hidden': true }),
773
+ h('span', null, copy.unanswered(waiting.length)),
774
+ h('span', { 'aria-hidden': true, style: { fontSize: 9 } }, open ? '▴' : '▾')),
775
+
776
+ open
777
+ ? h('div', { style: S.dockList }, waiting.map((row, index) => {
778
+ const first = row.questions?.[0]
779
+ const label = first?.header ?? first?.question ?? String(row.callId)
780
+ return h('button', {
781
+ key: String(row.callId),
782
+ type: 'button',
783
+ className: `${ROOT}-row`,
784
+ style: S.dockItem,
785
+ title: first?.question ?? String(row.callId),
786
+ onClick: () => { reveal(row.callId) },
787
+ },
788
+ h('span', { style: S.dockIndex }, String(index + 1)),
789
+ h('span', { style: S.dockItemText }, String(label)))
790
+ }))
791
+ : null,
792
+
793
+ note === '' ? null : h('div', { style: S.dockNote }, note))
794
+ }
795
+ }
796
+
797
+ return {
798
+ inject: ['slots', 'locale'],
799
+ apply(ctx) {
800
+ const Trigger = makeTrigger(ctx.locale)
801
+ const Settings = makeSettings(ctx.locale)
802
+ // The question-card capability is optional and may be provided after
803
+ // this plugin applies, so it is resolved at each click rather than
804
+ // captured once — a cached miss would report the wrong cause.
805
+ const Dock = makeDock(ctx.locale, () => ctx.get('userQuestionPanels'))
806
+ // One stylesheet for all surfaces: the hover and focus rules that inline
807
+ // styles cannot express. Inserted once and removed with this plugin's
808
+ // effect, so disabling the plugin leaves no rule behind.
809
+ ctx.effect(() => {
810
+ const element = document.createElement('style')
811
+ element.dataset.questionPacing = ''
812
+ element.textContent = STYLE_TEXT
813
+ document.head.append(element)
814
+ return () => { element.remove() }
815
+ }, 'question-pacing: styles')
816
+ const label = () => copyFor(safeLocale(ctx.locale)).control
817
+
818
+ // Composer tool row: this session's override.
819
+ ctx.slots.inject('conversation.input.right', () => ctx.slots.register({
820
+ name: 'conversation.input.right',
821
+ id: 'question-pacing-level',
822
+ order: 6,
823
+ label,
824
+ }, Trigger))
825
+
826
+ // Settings: the global defaults.
827
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
828
+ name: 'settings.section',
829
+ id: 'question-pacing',
830
+ order: 55,
831
+ label: () => copyFor(safeLocale(ctx.locale)).settingsTitle,
832
+ }, Settings))
833
+
834
+ // Above the composer card: every question still answerable in this
835
+ // Session that the composer seat is not currently showing.
836
+ ctx.slots.inject('conversation.input.dock', () => ctx.slots.register({
837
+ name: 'conversation.input.dock',
838
+ id: 'question-pacing-unanswered',
839
+ order: 30,
840
+ label,
841
+ }, Dock))
842
+ },
843
+ }
844
+ },
845
+ })