@aspen138/dsh-btw 0.1.1 → 0.2.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.
package/client.js CHANGED
@@ -1,583 +1,1295 @@
1
- // dsh-btw — Client half: the right-Sidebar "Side question" page and the
2
- // compact transcript chip.
3
- //
4
- // Data source: the Chat layer's own command nodes. `/btw` is a Host command, so
5
- // its lifecycle is already projected into the conversation as a `command` node
6
- // (name 'btw', args = the question, outcome.text = the answer). This module
7
- // reads those nodes through the `useChat` standard prop and renders them as a
8
- // right-Sidebar page (`ctx.sidebarRightTabs` + `sidebar.right.pane.tab`), so the
9
- // answer docks in the column the user already works in instead of floating over
10
- // the composer. The generic command card is replaced with a one-line chip that
11
- // reopens the page.
12
- //
13
- // Nothing here talks to the Host: no route, no RPC, no extra persistence. The
14
- // page is a view over the same durable command records the Chat already has.
15
-
16
- window.__ModuleLoader__.load({
17
- id: '@aspen138/dsh-btw',
18
- factory(require) {
19
- const React = require('react')
20
- const h = React.createElement
21
-
22
- /** Implementation identity: unique in the tab system, and the body slot key. */
23
- const TYPE_ID = 'dsh-btw/side-questions'
24
-
25
- /** Page kind the navigation controller opens by name. */
26
- const KIND = 'btw'
27
-
28
- /** Set by `apply`; the transcript chip uses it to reveal the page. */
29
- const navigation = { open: undefined, openChild: undefined }
30
-
31
- /** Diagnostic surface for verification runs; never user-visible. */
32
- const debug = { tabs: false, right: false, lastError: null, open: undefined }
33
- try {
34
- if (typeof window !== 'undefined') window.__DSH_BTW__ = debug
35
- } catch {
36
- /* a read-only window is not worth breaking the plugin over */
37
- }
38
-
39
- // ---------------------------------------------------------------- strings
40
-
41
- const STRINGS = {
42
- zh: {
43
- badge: '侧问',
44
- badgeHint: '继承当前对话、不带工具,答案不进入主干上下文',
45
- typeLabel: '侧问',
46
- guideTitle: '侧问',
47
- guideDescription: '问一句小细节,不动主线任务',
48
- running: '正在回答…',
49
- done: '已答',
50
- failed: '失败',
51
- emptyQuestion: '(空问题)',
52
- emptyTitle: '还没有侧问',
53
- emptyHint: '在输入框输入 /btw <问题>,答案会出现在这里,且不进入模型上下文。',
54
- copy: '复制问答',
55
- copied: '已复制',
56
- openChild: '查看子会话',
57
- openChildHint: '在右侧打开这条侧问的子会话:它的工具调用和审批都在那里',
58
- chipOpen: '在右侧打开这条侧问的子会话',
59
- questionPrefix: '问',
60
- answerPrefix: '答',
61
- degraded: '仅文本历史',
62
- count: (n) => `${n} 条`,
63
- },
64
- en: {
65
- badge: 'Side question',
66
- badgeHint: 'Inherits this conversation, no tools; never enters the main context',
67
- typeLabel: 'Side question',
68
- guideTitle: 'Side question',
69
- guideDescription: 'Ask one small thing without touching the task',
70
- running: 'Answering…',
71
- done: 'Answered',
72
- failed: 'Failed',
73
- emptyQuestion: '(empty question)',
74
- emptyTitle: 'No side questions yet',
75
- emptyHint: 'Type /btw <question> in the composer. Answers appear here and never enter the model context.',
76
- copy: 'Copy question and answer',
77
- copied: 'Copied',
78
- openChild: 'Open sub-session',
79
- openChildHint: "Open this side question's own session: its tool calls and approval prompts live there",
80
- chipOpen: "Open this side question's sub-session",
81
- questionPrefix: 'Q',
82
- answerPrefix: 'A',
83
- degraded: 'text history only',
84
- count: (n) => `${n} item${n === 1 ? '' : 's'}`,
85
- },
86
- }
87
-
88
- /** Language used when no locale service is mounted. */
89
- function documentLanguage() {
90
- try {
91
- const lang = String((typeof document !== 'undefined' && document.documentElement && document.documentElement.lang) || 'zh')
92
- return lang.toLowerCase().startsWith('zh') ? 'zh' : 'en'
93
- } catch {
94
- return 'zh'
95
- }
96
- }
97
-
98
- // -------------------------------------------------------------------- css
99
-
100
- const CSS = [
101
- '.dshbtw-page{display:flex;flex-direction:column;gap:10px;padding:12px 12px 24px;font-size:13px;line-height:20px;',
102
- 'color:var(--dsw-alias-label-primary);overflow:auto;height:100%}',
103
- '.dshbtw-empty{display:flex;flex-direction:column;gap:6px;padding:28px 8px;color:var(--dsw-alias-label-secondary);text-align:center}',
104
- '.dshbtw-empty-title{font-weight:600;color:var(--dsw-alias-label-primary)}',
105
- '.dshbtw-empty-hint{font-size:12px;line-height:18px}',
106
- '.dshbtw-card{display:flex;flex-direction:column;gap:6px;padding:10px 12px;border:0.5px solid var(--dsw-alias-border-l1);',
107
- 'border-radius:10px;background:var(--dsw-alias-bg-layer-1)}',
108
- '.dshbtw-card-head{display:flex;align-items:flex-start;gap:6px}',
109
- '.dshbtw-q{flex:1;min-width:0;font-weight:600;white-space:pre-wrap;word-break:break-word}',
110
- '.dshbtw-state{flex:none;font-size:12px;color:var(--dsw-alias-label-secondary)}',
111
- '.dshbtw-state.is-error{color:var(--dsw-alias-state-error-primary)}',
112
- '.dshbtw-a{white-space:pre-wrap;word-break:break-word}',
113
- '.dshbtw-a.is-error{color:var(--dsw-alias-state-error-primary)}',
114
- '.dshbtw-a.is-running{color:var(--dsw-alias-label-secondary);animation:dshbtw-pulse 1.4s ease-in-out infinite}',
115
- '@keyframes dshbtw-pulse{0%,100%{opacity:.55}50%{opacity:1}}',
116
- '@media(prefers-reduced-motion:reduce){.dshbtw-a.is-running{animation:none}}',
117
- '.dshbtw-actions{display:flex;align-items:center;gap:6px;margin-top:2px}',
118
- '.dshbtw-btn{display:inline-flex;align-items:center;justify-content:center;gap:4px;height:22px;padding:0 8px;',
119
- 'border:0.5px solid var(--dsw-alias-border-l1);border-radius:6px;background:transparent;',
120
- 'color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer}',
121
- '.dshbtw-btn:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}',
122
- '.dshbtw-meta{flex:1;min-width:0;font-size:11px;color:var(--dsw-alias-state-idle-primary);overflow:hidden;',
123
- 'text-overflow:ellipsis;white-space:nowrap}',
124
- '.dshbtw-chip{display:flex;align-items:center;gap:6px;width:100%;max-width:100%;padding:2px 0;',
125
- 'border:0;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;',
126
- 'line-height:18px;text-align:left;cursor:pointer}',
127
- '.dshbtw-chip:hover{color:var(--dsw-alias-label-primary)}',
128
- '.dshbtw-chip-mark{flex:none;color:var(--dsw-alias-brand-primary)}',
129
- '.dshbtw-chip-label{flex:none;font-weight:600}',
130
- '.dshbtw-chip-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
131
- '.dshbtw-chip-state{flex:none;color:var(--dsw-alias-state-idle-primary)}',
132
- '.dshbtw-chip-state.is-error{color:var(--dsw-alias-state-error-primary)}',
133
- ].join('')
134
-
135
- // ------------------------------------------------------------------ error
136
-
137
- /** Keep one crashing view from blanking the whole slot entry. */
138
- class Boundary extends React.Component {
139
- constructor(props) {
140
- super(props)
141
- this.state = { error: null }
142
- }
143
- static getDerivedStateFromError(error) {
144
- return { error }
145
- }
146
- componentDidCatch(error) {
147
- try {
148
- console.error('[dsh-btw] view crashed', error)
149
- } catch {
150
- /* logging must never throw */
151
- }
152
- }
153
- render() {
154
- if (this.state.error !== null) return this.props.fallback === undefined ? null : this.props.fallback
155
- return this.props.children
156
- }
157
- }
158
-
159
- // ------------------------------------------------------------------- data
160
-
161
- const EMPTY = Object.freeze([])
162
-
163
- /**
164
- * Collect the `/btw` command nodes of the current Chat target.
165
- *
166
- * A command node is `{kind:'command', data:{commandId,name,args,outcome,…}}`.
167
- * `outcome === null` means the handler is still running; otherwise
168
- * `outcome.kind` is 'success' | 'error' and `outcome.text` may carry the
169
- * answer. The selector never throws: a slot entry that throws is removed by
170
- * the host, so every access is defensive.
171
- */
172
- function selectBtwRecords(snapshot) {
173
- try {
174
- const nodes = snapshot && snapshot.nodes
175
- if (!nodes || typeof nodes.values !== 'function') return EMPTY
176
- const records = []
177
- for (const node of nodes.values()) {
178
- if (!node || typeof node !== 'object') continue
179
- const data = node.data !== null && typeof node.data === 'object' ? node.data : node
180
- if (data.name !== 'btw') continue
181
- records.push(data)
182
- }
183
- if (records.length === 0) return EMPTY
184
- records.sort((left, right) => (Number(left.seq) || 0) - (Number(right.seq) || 0))
185
- return records
186
- } catch {
187
- return EMPTY
188
- }
189
- }
190
-
191
- /** Field-wise stability so a fresh array does not re-render on every snapshot. */
192
- function sameRecords(left, right) {
193
- if (left === right) return true
194
- if (!left || !right || left.length !== right.length) return false
195
- for (let index = 0; index < left.length; index += 1) {
196
- const a = left[index]
197
- const b = right[index]
198
- if (a === b) continue
199
- if (a.commandId !== b.commandId || a.args !== b.args || a.time !== b.time) return false
200
- const ao = a.outcome
201
- const bo = b.outcome
202
- if (ao === bo) continue
203
- if (!ao || !bo) return false
204
- if (ao.kind !== bo.kind || ao.text !== bo.text) return false
205
- }
206
- return true
207
- }
208
-
209
- /** Read the session's side-question records through the Chat hook. */
210
- function useBtwRecords(useChat) {
211
- const records = typeof useChat === 'function' ? useChat(selectBtwRecords, sameRecords) : EMPTY
212
- return Array.isArray(records) ? records : EMPTY
213
- }
214
-
215
- /** Trailer the Host appends to every answer to name its child session. */
216
- const CHILD_MARKER = /\[\[dsh-btw:child=([^\]\s]+)\]\]/u
217
-
218
- /**
219
- * Normalize one command record for rendering.
220
- *
221
- * Strips the child marker out of the visible answer, and keeps the child
222
- * session id when the Host published one: that id is what opens the side
223
- * agent's own conversation (tool calls and native approval prompts) in the
224
- * right Sidebar.
225
- */
226
- function viewOf(record) {
227
- const outcome = record.outcome !== null && typeof record.outcome === 'object' ? record.outcome : undefined
228
- const raw = outcome !== undefined && typeof outcome.text === 'string' ? outcome.text : ''
229
- const match = CHILD_MARKER.exec(raw)
230
- return {
231
- commandId: String(record.commandId ?? ''),
232
- question: typeof record.args === 'string' ? record.args.trim() : '',
233
- answer: raw.replace(CHILD_MARKER, '').replace(/\s+$/u, ''),
234
- childId: match === null ? undefined : match[1],
235
- running: record.outcome === null,
236
- failed: outcome !== undefined && outcome.kind === 'error',
237
- }
238
- }
239
-
240
- // ------------------------------------------------------------------ glyph
241
-
242
- /** Guide artwork for the "开始" page entry: a bubble with a question spark. */
243
- function BtwGlyph(props) {
244
- const size = props !== null && typeof props === 'object' && Number.isFinite(props.size) ? props.size : 20
245
- return h(
246
- 'svg',
247
- { viewBox: '0 0 24 24', width: size, height: size, fill: 'none', 'aria-hidden': true },
248
- h('path', {
249
- d: 'M4 6.5A2.5 2.5 0 0 1 6.5 4h7A2.5 2.5 0 0 1 16 6.5v4A2.5 2.5 0 0 1 13.5 13H9l-3.2 2.9V13H6.5A2.5 2.5 0 0 1 4 10.5z',
250
- stroke: 'currentColor',
251
- strokeWidth: 1.4,
252
- strokeLinejoin: 'round',
253
- }),
254
- h('path', {
255
- d: 'M18.6 10.2l.9 2 2 .9-2 .9-.9 2-.9-2-2-.9 2-.9z',
256
- fill: 'currentColor',
257
- opacity: 0.85,
258
- }),
259
- )
260
- }
261
-
262
- // ------------------------------------------------------------------- chip
263
-
264
- /**
265
- * Transcript chip registered on `conversation.chat.commandview` key 'btw'.
266
- *
267
- * It replaces the generic command card for `/btw` only: the answer belongs
268
- * to the right-Sidebar page, and the transcript keeps a single quiet line
269
- * that reveals it. A fresh question opens the page automatically; an old one
270
- * only opens when clicked, so reopening a session does not move the column.
271
- */
272
- function BtwChip(props) {
273
- const t = props.__btwStrings
274
- const data = props.node !== null && typeof props.node === 'object' ? props.node : {}
275
- const view = viewOf(data)
276
- const state = view.running ? t.running : view.failed ? t.failed : t.done
277
-
278
- // A fresh question reveals the side agent's own conversation: that is
279
- // where its tool calls and approval prompts live. The child id only
280
- // arrives with the settled answer, so this also fires on completion.
281
- React.useEffect(() => {
282
- if (view.childId === undefined) return
283
- const at = Number(data.time)
284
- const fresh = Number.isFinite(at) ? Date.now() - at < 300000 : false
285
- if (!fresh) return
286
- if (typeof navigation.openChild === 'function') navigation.openChild(view.childId, props.sessionId)
287
- }, [view.childId, data.time])
288
-
289
- return h(
290
- 'button',
291
- {
292
- type: 'button',
293
- className: 'dshbtw-chip',
294
- title: t.chipOpen,
295
- onClick: () => {
296
- if (view.childId !== undefined && typeof navigation.openChild === 'function') {
297
- navigation.openChild(view.childId, props.sessionId)
298
- return
299
- }
300
- if (typeof navigation.open === 'function') navigation.open()
301
- },
302
- },
303
- h('style', { key: 'style' }, CSS),
304
- h('span', { key: 'mark', className: 'dshbtw-chip-mark', 'aria-hidden': true }, '◈'),
305
- h('span', { key: 'label', className: 'dshbtw-chip-label' }, t.badge),
306
- h('span', { key: 'text', className: 'dshbtw-chip-text' }, view.question === '' ? t.emptyQuestion : view.question),
307
- h('span', { key: 'state', className: view.failed ? 'dshbtw-chip-state is-error' : 'dshbtw-chip-state' }, state),
308
- )
309
- }
310
-
311
- // ------------------------------------------------------------------ page
312
-
313
- /** One side question: question, answer, and its copy / sub-session actions. */
314
- function SideQuestionCard(props) {
315
- const t = props.strings
316
- const record = props.record
317
- const view = viewOf(record)
318
- const [copied, setCopied] = React.useState(false)
319
-
320
- const copy = () => {
321
- const text = `${t.questionPrefix}: ${view.question}\n\n${t.answerPrefix}: ${view.answer}`
322
- try {
323
- navigator.clipboard.writeText(text).then(
324
- () => setCopied(true),
325
- () => setCopied(false),
326
- )
327
- } catch {
328
- setCopied(false)
329
- }
330
- }
331
-
332
- return h(
333
- 'div',
334
- { className: 'dshbtw-card' },
335
- h(
336
- 'div',
337
- { className: 'dshbtw-card-head' },
338
- h('div', { className: 'dshbtw-q' }, view.question === '' ? t.emptyQuestion : view.question),
339
- h(
340
- 'span',
341
- { className: view.failed ? 'dshbtw-state is-error' : 'dshbtw-state' },
342
- view.running ? t.running : view.failed ? t.failed : t.done,
343
- ),
344
- ),
345
- h(
346
- 'div',
347
- { className: view.running ? 'dshbtw-a is-running' : view.failed ? 'dshbtw-a is-error' : 'dshbtw-a' },
348
- view.running ? t.running : view.answer,
349
- ),
350
- view.running
351
- ? null
352
- : h(
353
- 'div',
354
- { className: 'dshbtw-actions' },
355
- h(
356
- 'button',
357
- { type: 'button', className: 'dshbtw-btn', onClick: copy },
358
- copied ? t.copied : t.copy,
359
- ),
360
- view.childId === undefined
361
- ? null
362
- : h(
363
- 'button',
364
- {
365
- type: 'button',
366
- className: 'dshbtw-btn',
367
- title: t.openChildHint,
368
- onClick: () => {
369
- if (typeof navigation.openChild === 'function') navigation.openChild(view.childId, props.sessionId)
370
- },
371
- },
372
- t.openChild,
373
- ),
374
- ),
375
- )
376
- }
377
-
378
- /**
379
- * The right-Sidebar page body: newest side question first.
380
- *
381
- * Rendered through `sidebar.right.pane.tab` under this package's type id, so
382
- * the tab system owns the pane, the chip, the split and the floating form;
383
- * this component owns only the content.
384
- */
385
- function BtwPage(props) {
386
- const t = props.__btwStrings
387
- const records = useBtwRecords(props.useChat)
388
- const ordered = React.useMemo(() => [...records].reverse(), [records])
389
-
390
- return h(
391
- 'div',
392
- { className: 'dshbtw-page', role: 'region', 'aria-label': t.badge },
393
- h('style', { key: 'style' }, CSS),
394
- ordered.length === 0
395
- ? h(
396
- 'div',
397
- { key: 'empty', className: 'dshbtw-empty' },
398
- h('div', { key: 'title', className: 'dshbtw-empty-title' }, t.emptyTitle),
399
- h('div', { key: 'hint', className: 'dshbtw-empty-hint' }, t.emptyHint),
400
- )
401
- : ordered.map((record) =>
402
- h(SideQuestionCard, {
403
- key: String(record.commandId ?? record.seq),
404
- record,
405
- strings: t,
406
- }),
407
- ),
408
- )
409
- }
410
-
411
- // -------------------------------------------------------------- bootstrap
412
-
413
- /** Strings that may go into a locale dictionary (values must be plain text). */
414
- function stringsOnly(dict) {
415
- const out = {}
416
- for (const key of Object.keys(dict)) {
417
- if (typeof dict[key] === 'string') out[key] = dict[key]
418
- }
419
- return out
420
- }
421
-
422
- /** Active language id, preferring the locale service over the document. */
423
- function activeLanguage(ctx) {
424
- const locale = ctx.get('locale')
425
- if (locale !== null && locale !== undefined && typeof locale.getLocale === 'function') {
426
- try {
427
- const snapshot = locale.getLocale()
428
- // LocaleSnapshot is `{ active, locales, revision }`.
429
- const id = snapshot !== null && typeof snapshot === 'object' ? snapshot.active : undefined
430
- if (typeof id === 'string' && id !== '') return id.toLowerCase().startsWith('zh') ? 'zh' : 'en'
431
- } catch {
432
- /* fall through to the document language */
433
- }
434
- }
435
- return documentLanguage()
436
- }
437
-
438
- /** Resolve visible copy: the locale service when present, else `en`/`zh`. */
439
- function resolveStrings(ctx) {
440
- const base = STRINGS[activeLanguage(ctx)]
441
- const locale = ctx.get('locale')
442
- if (locale === null || locale === undefined || typeof locale.register !== 'function' || typeof locale.bind !== 'function') {
443
- return base
444
- }
445
- let translate
446
- try {
447
- ctx.effect(() => {
448
- const disposers = [
449
- locale.register('dsh-btw', 'zh', stringsOnly(STRINGS.zh)),
450
- locale.register('dsh-btw', 'en', stringsOnly(STRINGS.en)),
451
- ]
452
- return () => {
453
- for (const dispose of disposers) {
454
- try {
455
- dispose()
456
- } catch {
457
- /* a failed dictionary removal must not break unload */
458
- }
459
- }
460
- }
461
- }, 'dsh-btw locale')
462
- translate = locale.bind('dsh-btw')
463
- } catch {
464
- return base
465
- }
466
- if (typeof translate !== 'function') return base
467
- const merged = { ...base }
468
- for (const key of Object.keys(base)) {
469
- if (typeof base[key] !== 'string') continue
470
- try {
471
- const value = translate(key)
472
- if (typeof value === 'string' && value !== '') merged[key] = value
473
- } catch {
474
- /* keep the built-in copy for this key */
475
- }
476
- }
477
- // Pluralizing helpers stay language-specific closures.
478
- merged.count = base.count
479
- return merged
480
- }
481
-
482
- return {
483
- // Hard dependencies of the hand-written module: the slot seat, and the
484
- // right-Sidebar tab registry + navigation controller. Declaring them here
485
- // is what makes `ctx.get` resolve them; the transcript chip still renders
486
- // if the right column is absent from the composition.
487
- inject: ['slots', 'sidebarRightTabs', 'sidebarRight'],
488
- apply(ctx) {
489
- const strings = resolveStrings(ctx)
490
- const tabs = ctx.get('sidebarRightTabs')
491
- const right = ctx.get('sidebarRight')
492
-
493
- navigation.open = () => {
494
- try {
495
- if (right !== null && right !== undefined && typeof right.openTab === 'function') {
496
- right.openTab(KIND)
497
- debug.lastError = null
498
- } else {
499
- debug.lastError = 'sidebarRight.openTab unavailable'
500
- }
501
- } catch (error) {
502
- debug.lastError = error instanceof Error ? error.message : String(error)
503
- try {
504
- console.error('[dsh-btw] could not open the side-question page', error)
505
- } catch {
506
- /* ignore */
507
- }
508
- }
509
- }
510
-
511
- /**
512
- * Open one side agent's own conversation in the right Sidebar.
513
- *
514
- * This is the built-in subagent tab: it renders the child's live
515
- * conversation, so the side agent's tool calls and its **approval
516
- * prompts** appear exactly where DSH puts them. Falls back to the
517
- * side-question page when the address is rejected.
518
- */
519
- navigation.openChild = (childId, parentId) => {
520
- if (typeof childId !== 'string' || childId === '') {
521
- navigation.open()
522
- return
523
- }
524
- const address = `dsh-resource://subagentchat/session/${childId}?parent=${parentId ?? ''}&mode=continuable`
525
- try {
526
- if (right !== null && right !== undefined && typeof right.openResource === 'function') {
527
- right.openResource(address)
528
- debug.lastError = null
529
- return
530
- }
531
- debug.lastError = 'sidebarRight.openResource unavailable'
532
- } catch (error) {
533
- debug.lastError = error instanceof Error ? error.message : String(error)
534
- }
535
- navigation.open()
536
- }
537
-
538
- debug.tabs = tabs !== null && tabs !== undefined
539
- debug.right = right !== null && right !== undefined
540
- debug.open = navigation.open
541
- debug.openChild = navigation.openChild
542
-
543
- // The page type: a page (no resource patterns), opened by kind.
544
- if (tabs !== null && tabs !== undefined && typeof tabs.register === 'function') {
545
- ctx.effect(
546
- () =>
547
- tabs.register({
548
- id: TYPE_ID,
549
- kind: KIND,
550
- priority: 'extension',
551
- title: () => strings.typeLabel,
552
- guide: [
553
- {
554
- id: 'questions',
555
- order: 20,
556
- title: () => strings.guideTitle,
557
- description: () => strings.guideDescription,
558
- icon: BtwGlyph,
559
- },
560
- ],
561
- }),
562
- 'dsh-btw tab type',
563
- )
564
-
565
- ctx.slots.inject('sidebar.right.pane.tab', () =>
566
- ctx.slots.register(
567
- { name: 'sidebar.right.pane.tab', key: TYPE_ID },
568
- (props) => h(Boundary, { fallback: null }, h(BtwPage, { ...props, __btwStrings: strings })),
569
- ),
570
- )
571
- }
572
-
573
- // The transcript chip works even without the right-Sidebar registry.
574
- ctx.slots.inject('conversation.chat.commandview', () =>
575
- ctx.slots.register(
576
- { name: 'conversation.chat.commandview', key: 'btw' },
577
- (props) => h(Boundary, { fallback: null }, h(BtwChip, { ...props, __btwStrings: strings })),
578
- ),
579
- )
580
- },
581
- }
582
- },
583
- })
1
+ // dsh-btw — Client half: the right-Sidebar "Side question" page and the
2
+ // compact transcript chip.
3
+ //
4
+ // Data source: the Chat layer's own command nodes. `/btw` is a Host command, so
5
+ // its lifecycle is already projected into the conversation as a `command` node
6
+ // (name 'btw', args = the question, outcome.text = the answer). This module
7
+ // reads those nodes through the `useChat` standard prop and renders them as a
8
+ // right-Sidebar page (`ctx.sidebarRightTabs` + `sidebar.right.pane.tab`), so the
9
+ // answer docks in the column the user already works in instead of floating over
10
+ // the composer. The generic command card is replaced with a one-line chip that
11
+ // reopens the page.
12
+ //
13
+ // Nothing here talks to the Host: no route, no RPC, no extra persistence. The
14
+ // page is a view over the same durable command records the Chat already has.
15
+
16
+ window.__ModuleLoader__.load({
17
+ id: '@aspen138/dsh-btw',
18
+ factory(require) {
19
+ const React = require('react')
20
+ const h = React.createElement
21
+
22
+ // ------------------------------------------------------------ markdown
23
+
24
+ /** The Markdown renderer this bundle owns (see markdown.js for its tests). */
25
+
26
+  /** Split one line into inline tokens: code, bold, italic, links, plain. */
27
+ function inline(text, keyPrefix) {
28
+ const out = []
29
+ let rest = text
30
+ let index = 0
31
+ const push = (type, value, extra) => {
32
+ const key = `${keyPrefix}-${index}`
33
+ index += 1
34
+ if (type === 'code') out.push(h('code', { key, className: 'dshbtw-md-code' }, value))
35
+ else if (type === 'strong') out.push(h('strong', { key }, value))
36
+ else if (type === 'em') out.push(h('em', { key }, value))
37
+ else if (type === 'link') out.push(h('a', { key, href: extra, target: '_blank', rel: 'noreferrer noopener', className: 'dshbtw-md-link' }, value))
38
+ else out.push(value)
39
+ }
40
+
41
+ while (rest.length > 0) {
42
+ const code = /^`([^`]+)`/u.exec(rest)
43
+ if (code !== null) {
44
+ push('code', code[1])
45
+ rest = rest.slice(code[0].length)
46
+ continue
47
+ }
48
+ const strong = /^\*\*([^*]+)\*\*/u.exec(rest) ?? /^__([^_]+)__/u.exec(rest)
49
+ if (strong !== null) {
50
+ push('strong', strong[1])
51
+ rest = rest.slice(strong[0].length)
52
+ continue
53
+ }
54
+ const link = /^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/u.exec(rest)
55
+ if (link !== null) {
56
+ push('link', link[1], link[2])
57
+ rest = rest.slice(link[0].length)
58
+ continue
59
+ }
60
+ const em = /^\*([^*\n]+)\*/u.exec(rest) ?? /^_([^_\n]+)_/u.exec(rest)
61
+ if (em !== null) {
62
+ push('em', em[1])
63
+ rest = rest.slice(em[0].length)
64
+ continue
65
+ }
66
+ // Plain run up to the next special character.
67
+ const plain = /^[^`*_[\]]+/u.exec(rest)
68
+ if (plain !== null) {
69
+ // Bare URLs become links, which is the one autolink worth having.
70
+ const url = /(https?:\/\/[^\s<>()]+)/u.exec(plain[0])
71
+ if (url === null) {
72
+ push('text', plain[0])
73
+ } else {
74
+ const before = plain[0].slice(0, url.index)
75
+ if (before !== '') push('text', before)
76
+ push('link', url[1], url[1])
77
+ const after = plain[0].slice(url.index + url[1].length)
78
+ if (after !== '') push('text', after)
79
+ }
80
+ rest = rest.slice(plain[0].length)
81
+ continue
82
+ }
83
+ push('text', rest[0])
84
+ rest = rest.slice(1)
85
+ }
86
+ return out
87
+ }
88
+
89
+ /** Render one paragraph-ish line with inline markup. */
90
+ function line(text, key) {
91
+ return h('div', { key, className: 'dshbtw-md-p' }, inline(text, key))
92
+ }
93
+
94
+ /**
95
+ * Render Markdown source into React elements.
96
+ *
97
+ * Supported: fenced and indented code, ATX headings, bullet and ordered
98
+ * lists (one level of nesting), blockquotes, horizontal rules, paragraphs,
99
+ * and the inline subset above. Unknown syntax degrades to plain text.
100
+ *
101
+ * @param source - raw answer text.
102
+ * @returns React children.
103
+ */
104
+ function renderMarkdown(source) {
105
+ const text = typeof source === 'string' ? source : ''
106
+ if (text === '') return null
107
+ const lines = text.replace(/\r\n?/gu, '\n').split('\n')
108
+ const blocks = []
109
+ let index = 0
110
+ let key = 0
111
+
112
+ while (index < lines.length) {
113
+ const current = lines[index]
114
+
115
+ const fence = /^\s*(```+|~~~+)\s*([\w-]*)\s*$/u.exec(current)
116
+ if (fence !== null) {
117
+ const marker = fence[1][0]
118
+ const body = []
119
+ index += 1
120
+ while (index < lines.length && !new RegExp(`^\\s*${marker}{3,}\\s*$`, 'u').test(lines[index])) {
121
+ body.push(lines[index])
122
+ index += 1
123
+ }
124
+ index += 1
125
+ blocks.push(h('pre', { key: `k${key}`, className: 'dshbtw-md-pre' }, h('code', null, body.join('\n'))))
126
+ key += 1
127
+ continue
128
+ }
129
+
130
+ const heading = /^\s*(#{1,6})\s+(.*)$/u.exec(current)
131
+ if (heading !== null) {
132
+ const level = Math.min(6, heading[1].length)
133
+ blocks.push(h(`h${level}`, { key: `k${key}`, className: 'dshbtw-md-h' }, inline(heading[2], `h${key}`)))
134
+ key += 1
135
+ index += 1
136
+ continue
137
+ }
138
+
139
+ if (/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/u.test(current)) {
140
+ blocks.push(h('hr', { key: `k${key}`, className: 'dshbtw-md-hr' }))
141
+ key += 1
142
+ index += 1
143
+ continue
144
+ }
145
+
146
+ if (/^\s*>/u.test(current)) {
147
+ const body = []
148
+ while (index < lines.length && /^\s*>/u.test(lines[index])) {
149
+ body.push(lines[index].replace(/^\s*>\s?/u, ''))
150
+ index += 1
151
+ }
152
+ blocks.push(h('blockquote', { key: `k${key}`, className: 'dshbtw-md-quote' }, renderMarkdown(body.join('\n'))))
153
+ key += 1
154
+ continue
155
+ }
156
+
157
+ const bullet = /^(\s*)[-*+]\s+(.*)$/u.exec(current)
158
+ const ordered = /^(\s*)\d+[.)]\s+(.*)$/u.exec(current)
159
+ if (bullet !== null || ordered !== null) {
160
+ const isOrdered = ordered !== null
161
+ const items = []
162
+ while (index < lines.length) {
163
+ const match = isOrdered ? /^(\s*)\d+[.)]\s+(.*)$/u.exec(lines[index]) : /^(\s*)[-*+]\s+(.*)$/u.exec(lines[index])
164
+ if (match === null) break
165
+ items.push({ indent: match[1].length, text: match[2] })
166
+ index += 1
167
+ }
168
+ const tag = isOrdered ? 'ol' : 'ul'
169
+ const manyLevels = items.some((item) => item.indent > 0)
170
+ if (!manyLevels) {
171
+ blocks.push(
172
+ h(
173
+ tag,
174
+ { key: `k${key}`, className: 'dshbtw-md-list' },
175
+ items.map((item, at) => h('li', { key: at }, inline(item.text, `li${key}-${at}`))),
176
+ ),
177
+ )
178
+ } else {
179
+ // Keep the hierarchy readable without a full nested-list model.
180
+ blocks.push(
181
+ h(
182
+ 'ul',
183
+ { key: `k${key}`, className: 'dshbtw-md-list is-flat' },
184
+ items.map((item, at) =>
185
+ h(
186
+ 'li',
187
+ { key: at, style: { marginLeft: `${Math.min(item.indent, 8) * 0.6}em` } },
188
+ inline(item.text, `li${key}-${at}`),
189
+ ),
190
+ ),
191
+ ),
192
+ )
193
+ }
194
+ key += 1
195
+ continue
196
+ }
197
+
198
+ if (current.trim() === '') {
199
+ index += 1
200
+ continue
201
+ }
202
+
203
+ // Paragraph: consume until a blank line or another block start.
204
+ const paragraph = []
205
+ while (index < lines.length) {
206
+ const candidate = lines[index]
207
+ if (candidate.trim() === '') break
208
+ if (/^\s*(```|~~~|#{1,6}\s|>\s?|[-*+]\s|\d+[.)]\s)/u.test(candidate)) break
209
+ paragraph.push(candidate)
210
+ index += 1
211
+ }
212
+ if (paragraph.length === 0) {
213
+ // Defensive: never loop forever on an unrecognized line.
214
+ paragraph.push(lines[index])
215
+ index += 1
216
+ }
217
+ blocks.push(
218
+ h(
219
+ 'div',
220
+ { key: `k${key}`, className: 'dshbtw-md-block' },
221
+ paragraph.map((item, at) => line(item, `p${key}-${at}`)),
222
+ ),
223
+ )
224
+ key += 1
225
+ }
226
+
227
+ return blocks
228
+ }
229
+
230
+ const md = { renderMarkdown }
231
+
232
+
233
+ /** Implementation identity: unique in the tab system, and the body slot key. */
234
+ const TYPE_ID = 'dsh-btw/side-questions'
235
+
236
+ /** Page kind the navigation controller opens by name. */
237
+ const KIND = 'btw'
238
+
239
+ /** Set by `apply`; the transcript chip uses it to reveal the page. */
240
+ const navigation = { open: undefined, openChild: undefined }
241
+
242
+ /** Diagnostic surface for verification runs; never user-visible. */
243
+ const debug = { tabs: false, right: false, lastError: null, open: undefined }
244
+ try {
245
+ if (typeof window !== 'undefined') window.__DSH_BTW__ = debug
246
+ } catch {
247
+ /* a read-only window is not worth breaking the plugin over */
248
+ }
249
+
250
+ // ---------------------------------------------------------------- strings
251
+
252
+ const STRINGS = {
253
+ zh: {
254
+ badge: '侧问',
255
+ badgeHint: '继承当前对话、不带工具,答案不进入主干上下文',
256
+ typeLabel: '侧问',
257
+ guideTitle: '侧问',
258
+ guideDescription: '问一句小细节,不动主线任务',
259
+ running: '正在回答…',
260
+ done: '已答',
261
+ failed: '失败',
262
+ emptyQuestion: '(空问题)',
263
+ emptyTitle: '还没有侧问',
264
+ emptyHint: '在输入框输入 /btw <问题>,答案会出现在这里,且不进入模型上下文。',
265
+ copy: '复制问答',
266
+ copied: '已复制',
267
+ followPlaceholder: '在这个侧问里继续追问…',
268
+ followSend: '追问',
269
+ followSent: '已填入输入框,回车发送',
270
+ settingsTitle: '侧问',
271
+ setLoading: '正在读取配置…',
272
+ setLoadFailed: '读取配置失败',
273
+ setSaving: '正在保存…',
274
+ setSaved: '已保存,下一次侧问生效',
275
+ setSaveFailed: '保存失败',
276
+ setUnsupported: '当前 profile 没有 configEditor,配置只能手改 cordis.patch.yml',
277
+ setSave: '保存',
278
+ set_sideAgentPreset: '子 agent 权限',
279
+ set_sideAgentPresetHint: '侧问起的临时 agent 能做什么。read-only 只读;workspace-write 只能改工作区;danger-full-access 不受限。',
280
+ set_approvalPolicy: '审批策略',
281
+ set_approvalPolicyHint: 'ask:需要审批的操作走审批通道;inherit:跟随会话默认。',
282
+ set_answerMaxChars: '答案长度上限',
283
+ set_answerMaxCharsHint: '超过这个字数的答案会被截断,避免撑爆面板。',
284
+ set_sideAgentTimeoutMs: '单次侧问超时',
285
+ set_sideAgentTimeoutMsHint: '毫秒。超时后中止子 agent,不会一直挂着。',
286
+ set_maxQuestionChars: '问题长度上限',
287
+ set_maxQuestionCharsHint: '超过就直接拒绝,不浪费一次子 agent。',
288
+ set_disposeChild: '答完释放子 agent',
289
+ set_disposeChildHint: '关掉:保留执行句柄,便于继续追问(会占资源)。',
290
+ "opt_read-only": '只读',
291
+ "opt_workspace-write": '只能改工作区',
292
+ "opt_danger-full-access": '不受限',
293
+ "opt_inherit": '跟随会话',
294
+ on: '开',
295
+ off: '关',
296
+ openChild: '查看子会话',
297
+ openChildHint: '在右侧打开这条侧问的子会话:它的工具调用和审批都在那里',
298
+ chipOpen: '在右侧打开这条侧问的子会话',
299
+ questionPrefix: '问',
300
+ answerPrefix: '答',
301
+ degraded: '仅文本历史',
302
+ count: (n) => `${n} 条`,
303
+ },
304
+ en: {
305
+ badge: 'Side question',
306
+ badgeHint: 'Inherits this conversation, no tools; never enters the main context',
307
+ typeLabel: 'Side question',
308
+ guideTitle: 'Side question',
309
+ guideDescription: 'Ask one small thing without touching the task',
310
+ running: 'Answering…',
311
+ done: 'Answered',
312
+ failed: 'Failed',
313
+ emptyQuestion: '(empty question)',
314
+ emptyTitle: 'No side questions yet',
315
+ emptyHint: 'Type /btw <question> in the composer. Answers appear here and never enter the model context.',
316
+ copy: 'Copy question and answer',
317
+ copied: 'Copied',
318
+ followPlaceholder: 'Ask a follow-up in this side question…',
319
+ followSend: 'Follow up',
320
+ followSent: 'Placed in the composer — press Enter',
321
+ settingsTitle: 'Side question',
322
+ setLoading: 'Loading configuration…',
323
+ setLoadFailed: 'Could not load configuration',
324
+ setSaving: 'Saving…',
325
+ setSaved: 'Saved — applies to the next side question',
326
+ setSaveFailed: 'Could not save',
327
+ setUnsupported: 'This profile has no configEditor; edit cordis.patch.yml by hand',
328
+ setSave: 'Save',
329
+ set_sideAgentPreset: 'Side agent permissions',
330
+ set_sideAgentPresetHint: 'What the disposable side agent may do. read-only reads; workspace-write edits this workspace; danger-full-access is unrestricted.',
331
+ set_approvalPolicy: 'Approval policy',
332
+ set_approvalPolicyHint: 'ask routes approval-gated operations through the approval flow; inherit follows the session default.',
333
+ set_answerMaxChars: 'Answer length cap',
334
+ set_answerMaxCharsHint: 'Longer answers are truncated so the panel stays readable.',
335
+ set_sideAgentTimeoutMs: 'Side question timeout',
336
+ set_sideAgentTimeoutMsHint: 'Milliseconds. The child is cancelled instead of hanging forever.',
337
+ set_maxQuestionChars: 'Question length cap',
338
+ set_maxQuestionCharsHint: 'Longer questions are refused before a child agent is spent.',
339
+ set_disposeChild: 'Release the side agent after answering',
340
+ set_disposeChildHint: 'Off keeps the execution handle for follow-ups, at the cost of resources.',
341
+ "opt_read-only": 'Read only',
342
+ "opt_workspace-write": 'Workspace writes only',
343
+ "opt_danger-full-access": 'Unrestricted',
344
+ "opt_inherit": 'Follow the session',
345
+ on: 'On',
346
+ off: 'Off',
347
+ openChild: 'Open sub-session',
348
+ openChildHint: "Open this side question's own session: its tool calls and approval prompts live there",
349
+ chipOpen: "Open this side question's sub-session",
350
+ questionPrefix: 'Q',
351
+ answerPrefix: 'A',
352
+ degraded: 'text history only',
353
+ count: (n) => `${n} item${n === 1 ? '' : 's'}`,
354
+ },
355
+ }
356
+
357
+ /** Language used when no locale service is mounted. */
358
+ function documentLanguage() {
359
+ try {
360
+ const lang = String((typeof document !== 'undefined' && document.documentElement && document.documentElement.lang) || 'zh')
361
+ return lang.toLowerCase().startsWith('zh') ? 'zh' : 'en'
362
+ } catch {
363
+ return 'zh'
364
+ }
365
+ }
366
+
367
+ // -------------------------------------------------------------------- css
368
+
369
+ const CSS = [
370
+ '.dshbtw-page{display:flex;flex-direction:column;gap:10px;padding:12px 12px 24px;font-size:13px;line-height:20px;',
371
+ 'color:var(--dsw-alias-label-primary);overflow:auto;height:100%}',
372
+ '.dshbtw-empty{display:flex;flex-direction:column;gap:6px;padding:28px 8px;color:var(--dsw-alias-label-secondary);text-align:center}',
373
+ '.dshbtw-empty-title{font-weight:600;color:var(--dsw-alias-label-primary)}',
374
+ '.dshbtw-empty-hint{font-size:12px;line-height:18px}',
375
+ '.dshbtw-card{display:flex;flex-direction:column;gap:6px;padding:10px 12px;border:0.5px solid var(--dsw-alias-border-l1);',
376
+ 'border-radius:10px;background:var(--dsw-alias-bg-layer-1)}',
377
+ '.dshbtw-card-head{display:flex;align-items:flex-start;gap:6px}',
378
+ '.dshbtw-q{flex:1;min-width:0;font-weight:600;white-space:pre-wrap;word-break:break-word}',
379
+ '.dshbtw-state{flex:none;font-size:12px;color:var(--dsw-alias-label-secondary)}',
380
+ '.dshbtw-state.is-error{color:var(--dsw-alias-state-error-primary)}',
381
+ '.dshbtw-a{white-space:pre-wrap;word-break:break-word}',
382
+ '.dshbtw-a.is-markdown{white-space:normal}',
383
+ '.dshbtw-md-p{margin:0 0 2px}',
384
+ '.dshbtw-md-block{margin:0 0 4px}',
385
+ '.dshbtw-md-h{margin:10px 0 4px;font-size:13px;font-weight:600;line-height:18px}',
386
+ '.dshbtw-md-h:first-child{margin-top:0}',
387
+ '.dshbtw-md-list{margin:0 0 4px;padding-left:20px}',
388
+ '.dshbtw-md-list.is-flat{list-style:disc}',
389
+ '.dshbtw-md-list li{margin:1px 0}',
390
+ '.dshbtw-md-pre{margin:4px 0;padding:8px 10px;overflow:auto;border-radius:6px;',
391
+ 'background:var(--dsw-alias-bg-layer-2);border:0.5px solid var(--dsw-alias-border-l1);',
392
+ 'font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;line-height:18px;white-space:pre}',
393
+ '.dshbtw-md-code{padding:1px 4px;border-radius:4px;background:var(--dsw-alias-bg-layer-2);',
394
+ 'font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px}',
395
+ '.dshbtw-md-quote{margin:4px 0;padding:2px 0 2px 8px;border-left:2px solid var(--dsw-alias-border-l2);',
396
+ 'color:var(--dsw-alias-label-secondary)}',
397
+ '.dshbtw-md-hr{margin:8px 0;border:0;border-top:0.5px solid var(--dsw-alias-border-l1)}',
398
+ '.dshbtw-md-link{color:var(--dsw-alias-brand-primary);text-decoration:none}',
399
+ '.dshbtw-md-link:hover{text-decoration:underline}',
400
+ '.dshbtw-follow{display:flex;align-items:center;gap:6px;margin-top:4px}',
401
+ '.dshbtw-follow-input{flex:1;min-width:0;height:24px;padding:0 8px;border:0.5px solid var(--dsw-alias-border-l1);',
402
+ 'border-radius:6px;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12px}',
403
+ '.dshbtw-follow-input::placeholder{color:var(--dsw-alias-state-idle-primary)}',
404
+ '.dshbtw-follow-input:focus{outline:none;border-color:var(--dsw-alias-brand-primary)}',
405
+ '.dshbtw-set{display:flex;flex-direction:column;gap:14px;padding:4px 2px 24px;font-size:13px;line-height:20px;',
406
+ 'color:var(--dsw-alias-label-primary)}',
407
+ '.dshbtw-set-row{display:flex;flex-direction:column;gap:4px}',
408
+ '.dshbtw-set-label{font-weight:600}',
409
+ '.dshbtw-set-hint{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}',
410
+ '.dshbtw-set-field{display:flex;align-items:center;gap:8px}',
411
+ '.dshbtw-set-input{width:120px;height:26px;padding:0 8px;border:0.5px solid var(--dsw-alias-border-l1);',
412
+ 'border-radius:6px;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px}',
413
+ '.dshbtw-set-select{height:26px;padding:0 6px;border:0.5px solid var(--dsw-alias-border-l1);border-radius:6px;',
414
+ 'background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px}',
415
+ '.dshbtw-set-toggle{display:inline-flex;align-items:center;gap:8px;cursor:pointer}',
416
+ '.dshbtw-set-save{align-self:flex-start;height:28px;padding:0 14px;border:0;border-radius:7px;',
417
+ 'background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-bg-base);font:inherit;font-size:13px;cursor:pointer}',
418
+ '.dshbtw-set-save:disabled{opacity:.5;cursor:default}',
419
+ '.dshbtw-set-status{font-size:12px;color:var(--dsw-alias-label-secondary)}',
420
+ '.dshbtw-set-status.is-error{color:var(--dsw-alias-state-error-primary)}',
421
+ '.dshbtw-set-status.is-ok{color:var(--dsw-alias-state-success-primary)}',
422
+ '.dshbtw-a.is-error{color:var(--dsw-alias-state-error-primary)}',
423
+ '.dshbtw-a.is-running{color:var(--dsw-alias-label-secondary);animation:dshbtw-pulse 1.4s ease-in-out infinite}',
424
+ '@keyframes dshbtw-pulse{0%,100%{opacity:.55}50%{opacity:1}}',
425
+ '@media(prefers-reduced-motion:reduce){.dshbtw-a.is-running{animation:none}}',
426
+ '.dshbtw-actions{display:flex;align-items:center;gap:6px;margin-top:2px}',
427
+ '.dshbtw-btn{display:inline-flex;align-items:center;justify-content:center;gap:4px;height:22px;padding:0 8px;',
428
+ 'border:0.5px solid var(--dsw-alias-border-l1);border-radius:6px;background:transparent;',
429
+ 'color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer}',
430
+ '.dshbtw-btn:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}',
431
+ '.dshbtw-meta{flex:1;min-width:0;font-size:11px;color:var(--dsw-alias-state-idle-primary);overflow:hidden;',
432
+ 'text-overflow:ellipsis;white-space:nowrap}',
433
+ '.dshbtw-chip{display:flex;align-items:center;gap:6px;width:100%;max-width:100%;padding:2px 0;',
434
+ 'border:0;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;',
435
+ 'line-height:18px;text-align:left;cursor:pointer}',
436
+ '.dshbtw-chip:hover{color:var(--dsw-alias-label-primary)}',
437
+ '.dshbtw-chip-mark{flex:none;color:var(--dsw-alias-brand-primary)}',
438
+ '.dshbtw-chip-label{flex:none;font-weight:600}',
439
+ '.dshbtw-chip-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
440
+ '.dshbtw-chip-state{flex:none;color:var(--dsw-alias-state-idle-primary)}',
441
+ '.dshbtw-chip-state.is-error{color:var(--dsw-alias-state-error-primary)}',
442
+ '.dshbtw-hbtn{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0 7px;',
443
+ 'border:0.5px solid var(--dsw-alias-border-l1);border-radius:999px;background:transparent;',
444
+ 'color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:1;cursor:pointer}',
445
+ '.dshbtw-hbtn:hover{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}',
446
+ '.dshbtw-hbtn-mark{color:var(--dsw-alias-brand-primary)}',
447
+ '.dshbtw-hbtn-count{min-width:10px;text-align:center;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}',
448
+ ].join('')
449
+
450
+ // ------------------------------------------------------------------ error
451
+
452
+ /** Keep one crashing view from blanking the whole slot entry. */
453
+ class Boundary extends React.Component {
454
+ constructor(props) {
455
+ super(props)
456
+ this.state = { error: null }
457
+ }
458
+ static getDerivedStateFromError(error) {
459
+ return { error }
460
+ }
461
+ componentDidCatch(error) {
462
+ try {
463
+ console.error('[dsh-btw] view crashed', error)
464
+ } catch {
465
+ /* logging must never throw */
466
+ }
467
+ }
468
+ render() {
469
+ if (this.state.error !== null) return this.props.fallback === undefined ? null : this.props.fallback
470
+ return this.props.children
471
+ }
472
+ }
473
+
474
+ // ------------------------------------------------------------------- data
475
+
476
+ const EMPTY = Object.freeze([])
477
+
478
+ /**
479
+ * Collect the `/btw` command nodes of the current Chat target.
480
+ *
481
+ * A command node is `{kind:'command', data:{commandId,name,args,outcome,…}}`.
482
+ * `outcome === null` means the handler is still running; otherwise
483
+ * `outcome.kind` is 'success' | 'error' and `outcome.text` may carry the
484
+ * answer. The selector never throws: a slot entry that throws is removed by
485
+ * the host, so every access is defensive.
486
+ */
487
+ function selectBtwRecords(snapshot) {
488
+ try {
489
+ const nodes = snapshot && snapshot.nodes
490
+ if (!nodes || typeof nodes.values !== 'function') return EMPTY
491
+ const records = []
492
+ for (const node of nodes.values()) {
493
+ if (!node || typeof node !== 'object') continue
494
+ const data = node.data !== null && typeof node.data === 'object' ? node.data : node
495
+ if (data.name !== 'btw') continue
496
+ records.push(data)
497
+ }
498
+ if (records.length === 0) return EMPTY
499
+ records.sort((left, right) => (Number(left.seq) || 0) - (Number(right.seq) || 0))
500
+ return records
501
+ } catch {
502
+ return EMPTY
503
+ }
504
+ }
505
+
506
+ /** Field-wise stability so a fresh array does not re-render on every snapshot. */
507
+ function sameRecords(left, right) {
508
+ if (left === right) return true
509
+ if (!left || !right || left.length !== right.length) return false
510
+ for (let index = 0; index < left.length; index += 1) {
511
+ const a = left[index]
512
+ const b = right[index]
513
+ if (a === b) continue
514
+ if (a.commandId !== b.commandId || a.args !== b.args || a.time !== b.time) return false
515
+ const ao = a.outcome
516
+ const bo = b.outcome
517
+ if (ao === bo) continue
518
+ if (!ao || !bo) return false
519
+ if (ao.kind !== bo.kind || ao.text !== bo.text) return false
520
+ }
521
+ return true
522
+ }
523
+
524
+ /** Read the session's side-question records through the Chat hook. */
525
+ function useBtwRecords(useChat) {
526
+ const records = typeof useChat === 'function' ? useChat(selectBtwRecords, sameRecords) : EMPTY
527
+ return Array.isArray(records) ? records : EMPTY
528
+ }
529
+
530
+ /** Trailer the Host appends to every answer to name its child session. */
531
+ const CHILD_MARKER = /\[\[dsh-btw:child=([^\]\s]+)\]\]/u
532
+
533
+ /** The internal follow-up form the panel writes into the composer. */
534
+ const CONTINUE_FORM = /^--continue\s+(\S+)\s+([\s\S]+)$/u
535
+
536
+ /**
537
+ * Normalize one command record for rendering.
538
+ *
539
+ * Strips the child marker out of the visible answer, and keeps the child
540
+ * session id when the Host published one: that id is what opens the side
541
+ * agent's own conversation (tool calls and native approval prompts) in the
542
+ * right Sidebar.
543
+ */
544
+ function viewOf(record) {
545
+ const outcome = record.outcome !== null && typeof record.outcome === 'object' ? record.outcome : undefined
546
+ const raw = outcome !== undefined && typeof outcome.text === 'string' ? outcome.text : ''
547
+ const match = CHILD_MARKER.exec(raw)
548
+ const args = typeof record.args === 'string' ? record.args.trim() : ''
549
+ const follow = CONTINUE_FORM.exec(args)
550
+ return {
551
+ commandId: String(record.commandId ?? ''),
552
+ question: follow === null ? args : follow[2].trim(),
553
+ followUp: follow !== null,
554
+ answer: raw.replace(CHILD_MARKER, '').replace(/\s+$/u, ''),
555
+ childId: match === null ? (follow === null ? undefined : follow[1]) : match[1],
556
+ running: record.outcome === null,
557
+ failed: outcome !== undefined && outcome.kind === 'error',
558
+ }
559
+ }
560
+
561
+ // ------------------------------------------------------------------ glyph
562
+
563
+ /** Guide artwork for the "开始" page entry: a bubble with a question spark. */
564
+ function BtwGlyph(props) {
565
+ const size = props !== null && typeof props === 'object' && Number.isFinite(props.size) ? props.size : 20
566
+ return h(
567
+ 'svg',
568
+ { viewBox: '0 0 24 24', width: size, height: size, fill: 'none', 'aria-hidden': true },
569
+ h('path', {
570
+ d: 'M4 6.5A2.5 2.5 0 0 1 6.5 4h7A2.5 2.5 0 0 1 16 6.5v4A2.5 2.5 0 0 1 13.5 13H9l-3.2 2.9V13H6.5A2.5 2.5 0 0 1 4 10.5z',
571
+ stroke: 'currentColor',
572
+ strokeWidth: 1.4,
573
+ strokeLinejoin: 'round',
574
+ }),
575
+ h('path', {
576
+ d: 'M18.6 10.2l.9 2 2 .9-2 .9-.9 2-.9-2-2-.9 2-.9z',
577
+ fill: 'currentColor',
578
+ opacity: 0.85,
579
+ }),
580
+ )
581
+ }
582
+
583
+ // ------------------------------------------------------------------- chip
584
+
585
+ /**
586
+ * Transcript chip registered on `conversation.chat.commandview` key 'btw'.
587
+ *
588
+ * It replaces the generic command card for `/btw` only: the answer belongs
589
+ * to the right-Sidebar page, and the transcript keeps a single quiet line
590
+ * that reveals it. A fresh question opens the page automatically; an old one
591
+ * only opens when clicked, so reopening a session does not move the column.
592
+ */
593
+ function BtwChip(props) {
594
+ const t = props.__btwStrings
595
+ const data = props.node !== null && typeof props.node === 'object' ? props.node : {}
596
+ const view = viewOf(data)
597
+ const state = view.running ? t.running : view.failed ? t.failed : t.done
598
+
599
+ // A fresh question reveals the side agent's own conversation: that is
600
+ // where its tool calls and approval prompts live. The child id only
601
+ // arrives with the settled answer, so this also fires on completion.
602
+ React.useEffect(() => {
603
+ if (view.childId === undefined) return
604
+ const at = Number(data.time)
605
+ const fresh = Number.isFinite(at) ? Date.now() - at < 300000 : false
606
+ if (!fresh) return
607
+ if (typeof navigation.openChild === 'function') navigation.openChild(view.childId, props.sessionId)
608
+ }, [view.childId, data.time])
609
+
610
+ return h(
611
+ 'button',
612
+ {
613
+ type: 'button',
614
+ className: 'dshbtw-chip',
615
+ 'data-dshbtw': 'chip',
616
+ 'data-state': view.running ? 'running' : view.failed ? 'failed' : 'done',
617
+ ...(view.childId === undefined ? {} : { 'data-child': view.childId }),
618
+ title: t.chipOpen,
619
+ onClick: () => {
620
+ if (view.childId !== undefined && typeof navigation.openChild === 'function') {
621
+ navigation.openChild(view.childId, props.sessionId)
622
+ return
623
+ }
624
+ if (typeof navigation.open === 'function') navigation.open()
625
+ },
626
+ },
627
+ h('style', { key: 'style' }, CSS),
628
+ h('span', { key: 'mark', className: 'dshbtw-chip-mark', 'aria-hidden': true }, '◈'),
629
+ h('span', { key: 'label', className: 'dshbtw-chip-label' }, t.badge),
630
+ h('span', { key: 'text', className: 'dshbtw-chip-text' }, view.question === '' ? t.emptyQuestion : view.question),
631
+ h('span', { key: 'state', className: view.failed ? 'dshbtw-chip-state is-error' : 'dshbtw-chip-state' }, state),
632
+ )
633
+ }
634
+
635
+ // ---------------------------------------------------------------- header
636
+
637
+ /**
638
+ * Persistent "side question" button in the Session header utilities.
639
+ *
640
+ * Closing the right-Sidebar tab must never strand the history: this button
641
+ * stays in the header whenever the session has side questions and reopens
642
+ * the page. It renders nothing for a session that never used `/btw`.
643
+ */
644
+ function BtwHeaderButton(props) {
645
+ const t = props.__btwStrings
646
+ const records = useBtwRecords(props.useChat)
647
+ if (records.length === 0) return null
648
+ return h(
649
+ 'button',
650
+ {
651
+ type: 'button',
652
+ className: 'dshbtw-hbtn',
653
+ 'data-dshbtw': 'header-button',
654
+ 'data-count': String(records.length),
655
+ title: t.chipOpen,
656
+ 'aria-label': `${t.badge}(${records.length})`,
657
+ onClick: () => {
658
+ if (typeof navigation.open === 'function') navigation.open()
659
+ },
660
+ },
661
+ h('style', { key: 'style' }, CSS),
662
+ h('span', { key: 'mark', className: 'dshbtw-hbtn-mark', 'aria-hidden': true }, '◈'),
663
+ h('span', { key: 'label' }, t.badge),
664
+ h('span', { key: 'count', className: 'dshbtw-hbtn-count' }, String(records.length)),
665
+ )
666
+ }
667
+
668
+ // ------------------------------------------------------------------ page
669
+
670
+ /**
671
+ * Render one answer.
672
+ *
673
+ * Markdown comes from this bundle's own renderer (`markdown.js`), loaded as
674
+ * a sibling client entry: a hand-written plugin must not require another
675
+ * Harness Client package, and the answer text must never be injected as
676
+ * HTML. A failed render degrades to plain pre-wrapped text.
677
+ */
678
+ function AnswerBody(props) {
679
+ const t = props.strings
680
+ const view = props.view
681
+ if (view.running) {
682
+ return h('div', { className: 'dshbtw-a is-running', 'data-dshbtw': 'answer', 'data-rendered': 'running' }, t.running)
683
+ }
684
+ const body = view.failed ? view.answer : view.answer
685
+ let rendered = null
686
+ if (!view.failed && typeof md.renderMarkdown === 'function') {
687
+ try {
688
+ rendered = md.renderMarkdown(body)
689
+ } catch {
690
+ rendered = null
691
+ }
692
+ }
693
+ if (rendered !== null && (!Array.isArray(rendered) || rendered.length > 0)) {
694
+ const blocks = Array.isArray(rendered) ? rendered.length : 0
695
+ const lists = Array.isArray(rendered)
696
+ ? rendered.filter(
697
+ (node) => node !== null && typeof node === 'object' && (node.type === 'ul' || node.type === 'ol'),
698
+ ).length
699
+ : 0
700
+ return h(
701
+ 'div',
702
+ {
703
+ className: 'dshbtw-a is-markdown',
704
+ 'data-dshbtw': 'answer',
705
+ 'data-rendered': 'markdown',
706
+ 'data-blocks': String(blocks),
707
+ 'data-lists': String(lists),
708
+ },
709
+ h('style', { key: 'style' }, CSS),
710
+ rendered,
711
+ )
712
+ }
713
+ return h(
714
+ 'div',
715
+ {
716
+ className: view.failed ? 'dshbtw-a is-error' : 'dshbtw-a',
717
+ 'data-dshbtw': 'answer',
718
+ 'data-rendered': 'text',
719
+ 'data-chars': String(body.length),
720
+ },
721
+ body,
722
+ )
723
+ }
724
+
725
+ /** One side question: question, Markdown answer, copy, follow-up, sub-session. */
726
+ function SideQuestionCard(props) {
727
+ const t = props.strings
728
+ const record = props.record
729
+ const view = viewOf(record)
730
+ const [copied, setCopied] = React.useState(false)
731
+ const [draft, setDraft] = React.useState('')
732
+ const [sent, setSent] = React.useState(false)
733
+
734
+ const copy = () => {
735
+ const text = `${t.questionPrefix}: ${view.question}\n\n${t.answerPrefix}: ${view.answer}`
736
+ try {
737
+ navigator.clipboard.writeText(text).then(
738
+ () => setCopied(true),
739
+ () => setCopied(false),
740
+ )
741
+ } catch {
742
+ setCopied(false)
743
+ }
744
+ }
745
+
746
+ const followUp = () => {
747
+ const question = draft.trim()
748
+ if (question === '' || view.childId === undefined) return
749
+ if (typeof props.onFollowUp !== 'function') return
750
+ const ok = props.onFollowUp(view.childId, question)
751
+ if (ok !== false) {
752
+ setDraft('')
753
+ setSent(true)
754
+ setTimeout(() => setSent(false), 3000)
755
+ }
756
+ }
757
+
758
+ return h(
759
+ 'div',
760
+ {
761
+ className: 'dshbtw-card',
762
+ 'data-dshbtw': 'card',
763
+ 'data-command': view.commandId,
764
+ 'data-state': view.running ? 'running' : view.failed ? 'failed' : 'done',
765
+ 'data-followup': view.followUp ? 'true' : 'false',
766
+ ...(view.childId === undefined ? {} : { 'data-child': view.childId }),
767
+ },
768
+ h(
769
+ 'div',
770
+ { className: 'dshbtw-card-head' },
771
+ h('div', { className: 'dshbtw-q' }, view.question === '' ? t.emptyQuestion : view.question),
772
+ h(
773
+ 'span',
774
+ { className: view.failed ? 'dshbtw-state is-error' : 'dshbtw-state' },
775
+ view.running ? t.running : view.failed ? t.failed : t.done,
776
+ ),
777
+ ),
778
+ h(AnswerBody, { key: 'a', view, strings: t }),
779
+ view.running
780
+ ? null
781
+ : h(
782
+ 'div',
783
+ { className: 'dshbtw-actions' },
784
+ h(
785
+ 'button',
786
+ { type: 'button', className: 'dshbtw-btn', onClick: copy },
787
+ copied ? t.copied : t.copy,
788
+ ),
789
+ view.childId === undefined
790
+ ? null
791
+ : h(
792
+ 'button',
793
+ {
794
+ type: 'button',
795
+ className: 'dshbtw-btn',
796
+ title: t.openChildHint,
797
+ onClick: () => {
798
+ if (typeof navigation.openChild === 'function') navigation.openChild(view.childId, props.sessionId)
799
+ },
800
+ },
801
+ t.openChild,
802
+ ),
803
+ ),
804
+ view.running || view.childId === undefined
805
+ ? null
806
+ : h(
807
+ 'div',
808
+ { key: 'follow', className: 'dshbtw-follow' },
809
+ h('input', {
810
+ key: 'input',
811
+ className: 'dshbtw-follow-input',
812
+ 'data-dshbtw': 'follow-input',
813
+ type: 'text',
814
+ value: draft,
815
+ placeholder: t.followPlaceholder,
816
+ onChange: (event) => setDraft(event.target.value),
817
+ onKeyDown: (event) => {
818
+ if (event.key === 'Enter') {
819
+ event.preventDefault()
820
+ followUp()
821
+ }
822
+ },
823
+ }),
824
+ h(
825
+ 'button',
826
+ {
827
+ key: 'send',
828
+ type: 'button',
829
+ className: 'dshbtw-btn',
830
+ disabled: draft.trim() === '',
831
+ onClick: followUp,
832
+ },
833
+ sent ? t.followSent : t.followSend,
834
+ ),
835
+ ),
836
+ )
837
+ }
838
+
839
+ /**
840
+ * The right-Sidebar page body: newest side question first.
841
+ *
842
+ * Rendered through `sidebar.right.pane.tab` under this package's type id, so
843
+ * the tab system owns the pane, the chip, the split and the floating form;
844
+ * this component owns only the content.
845
+ */
846
+ function BtwPage(props) {
847
+ const t = props.__btwStrings
848
+ const records = useBtwRecords(props.useChat)
849
+ const ordered = React.useMemo(() => [...records].reverse(), [records])
850
+ const inputActions = props.inputActions
851
+
852
+ /**
853
+ * Prepare a follow-up in the composer.
854
+ *
855
+ * The panel deliberately does not submit: a follow-up runs the same
856
+ * command the user could type, and submitting on their behalf would spend
857
+ * a child-agent turn without a visible confirmation step. The draft lands
858
+ * in the composer so Enter sends it.
859
+ */
860
+ const onFollowUp = React.useCallback(
861
+ (childId, question) => {
862
+ const line = `/btw --continue ${childId} ${question}`
863
+ try {
864
+ if (inputActions !== null && inputActions !== undefined && typeof inputActions.setDraft === 'function') {
865
+ inputActions.setDraft(line)
866
+ return true
867
+ }
868
+ } catch (error) {
869
+ try {
870
+ console.error('[dsh-btw] follow-up could not reach the composer', error)
871
+ } catch {
872
+ /* ignore */
873
+ }
874
+ }
875
+ return false
876
+ },
877
+ [inputActions],
878
+ )
879
+
880
+ return h(
881
+ 'div',
882
+ {
883
+ className: 'dshbtw-page',
884
+ role: 'region',
885
+ 'aria-label': t.badge,
886
+ 'data-dshbtw': 'page',
887
+ 'data-count': String(ordered.length),
888
+ },
889
+ h('style', { key: 'style' }, CSS),
890
+ ordered.length === 0
891
+ ? h(
892
+ 'div',
893
+ { key: 'empty', className: 'dshbtw-empty' },
894
+ h('div', { key: 'title', className: 'dshbtw-empty-title' }, t.emptyTitle),
895
+ h('div', { key: 'hint', className: 'dshbtw-empty-hint' }, t.emptyHint),
896
+ )
897
+ : ordered.map((record) =>
898
+ h(SideQuestionCard, {
899
+ key: String(record.commandId ?? record.seq),
900
+ record,
901
+ strings: t,
902
+ sessionId: props.sessionId,
903
+ onFollowUp,
904
+ }),
905
+ ),
906
+ )
907
+ }
908
+
909
+ // ------------------------------------------------------------------- set
910
+
911
+ /** Same-origin route served by this bundle's Host half. */
912
+ const SETTINGS_ROUTE = '/api/dsh-btw/settings'
913
+
914
+ /** Read the plugin's editable settings from the Host. */
915
+ async function loadSettings() {
916
+ const response = await fetch(SETTINGS_ROUTE, { cache: 'no-store', credentials: 'same-origin' })
917
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
918
+ const value = await response.json()
919
+ if (value === null || typeof value !== 'object' || value.ok !== true) {
920
+ throw new Error(value?.error ?? 'settings unavailable')
921
+ }
922
+ return value
923
+ }
924
+
925
+ /** Write back the keys the user changed. */
926
+ async function saveSettings(values) {
927
+ const response = await fetch(SETTINGS_ROUTE, {
928
+ method: 'POST',
929
+ credentials: 'same-origin',
930
+ headers: { 'content-type': 'application/json' },
931
+ body: JSON.stringify(values),
932
+ })
933
+ const value = await response.json().catch(() => undefined)
934
+ if (!response.ok || value === undefined || value.ok !== true) {
935
+ throw new Error(value?.error ?? `HTTP ${response.status}`)
936
+ }
937
+ return value
938
+ }
939
+
940
+ /** One labelled row in the settings page. */
941
+ function SettingRow(props) {
942
+ return h(
943
+ 'div',
944
+ { className: 'dshbtw-set-row' },
945
+ h('div', { key: 'label', className: 'dshbtw-set-label' }, props.label),
946
+ props.hint === undefined ? null : h('div', { key: 'hint', className: 'dshbtw-set-hint' }, props.hint),
947
+ h('div', { key: 'field', className: 'dshbtw-set-field' }, props.children),
948
+ )
949
+ }
950
+
951
+ /**
952
+ * The plugin's settings page (`settings.section`).
953
+ *
954
+ * Writes go to the profile patch through the Host route, so a change
955
+ * survives a restart and is visible in the plugin manager. The page reads
956
+ * the effective values on mount instead of trusting a cached copy.
957
+ */
958
+ function BtwSettings(props) {
959
+ const t = props.__btwStrings
960
+ const [values, setValues] = React.useState(null)
961
+ const [status, setStatus] = React.useState({ kind: 'idle', text: '' })
962
+ const [saving, setSaving] = React.useState(false)
963
+ const [dirty, setDirty] = React.useState(false)
964
+
965
+ React.useEffect(() => {
966
+ let alive = true
967
+ loadSettings()
968
+ .then((value) => {
969
+ if (!alive) return
970
+ setValues(value.values ?? {})
971
+ setStatus(
972
+ value.supported === false
973
+ ? { kind: 'error', text: t.setUnsupported }
974
+ : { kind: 'idle', text: '' },
975
+ )
976
+ })
977
+ .catch((error) => {
978
+ if (!alive) return
979
+ setStatus({ kind: 'error', text: `${t.setLoadFailed}:${error.message}` })
980
+ })
981
+ return () => {
982
+ alive = false
983
+ }
984
+ }, [t])
985
+
986
+ const patch = (key, value) => {
987
+ setValues((current) => ({ ...(current ?? {}), [key]: value }))
988
+ setDirty(true)
989
+ }
990
+
991
+ const save = async () => {
992
+ if (values === null) return
993
+ setSaving(true)
994
+ setStatus({ kind: 'idle', text: t.setSaving })
995
+ try {
996
+ await saveSettings(values)
997
+ setDirty(false)
998
+ setStatus({ kind: 'ok', text: t.setSaved })
999
+ } catch (error) {
1000
+ setStatus({ kind: 'error', text: `${t.setSaveFailed}:${error.message}` })
1001
+ } finally {
1002
+ setSaving(false)
1003
+ }
1004
+ }
1005
+
1006
+ if (values === null) {
1007
+ return h(
1008
+ 'div',
1009
+ {
1010
+ className: 'dshbtw-set',
1011
+ role: 'region',
1012
+ 'aria-label': t.settingsTitle,
1013
+ 'data-dshbtw': 'settings',
1014
+ },
1015
+ h('style', { key: 'style' }, CSS),
1016
+ h('div', { className: 'dshbtw-set-status' }, status.text === '' ? t.setLoading : status.text),
1017
+ )
1018
+ }
1019
+
1020
+ const numberField = (key, hint) =>
1021
+ h(SettingRow, {
1022
+ key,
1023
+ label: t[`set_${key}`] ?? key,
1024
+ hint,
1025
+ }, h('input', {
1026
+ className: 'dshbtw-set-input',
1027
+ type: 'number',
1028
+ value: values[key] ?? '',
1029
+ onChange: (event) => patch(key, event.target.value === '' ? '' : Number(event.target.value)),
1030
+ }))
1031
+
1032
+ const selectField = (key, options, hint) =>
1033
+ h(
1034
+ SettingRow,
1035
+ { key, label: t[`set_${key}`] ?? key, hint },
1036
+ h(
1037
+ 'select',
1038
+ {
1039
+ className: 'dshbtw-set-select',
1040
+ value: values[key] ?? '',
1041
+ onChange: (event) => patch(key, event.target.value),
1042
+ },
1043
+ options.map((option) => h('option', { key: option, value: option }, t[`opt_${option}`] ?? option)),
1044
+ ),
1045
+ )
1046
+
1047
+ return h(
1048
+ 'div',
1049
+ {
1050
+ className: 'dshbtw-set',
1051
+ role: 'region',
1052
+ 'aria-label': t.settingsTitle,
1053
+ 'data-dshbtw': 'settings',
1054
+ },
1055
+ h('style', { key: 'style' }, CSS),
1056
+ h(SettingRow, { key: 'preset', label: t.set_sideAgentPreset, hint: t.set_sideAgentPresetHint },
1057
+ h(
1058
+ 'select',
1059
+ {
1060
+ className: 'dshbtw-set-select',
1061
+ value: values.sideAgentPreset ?? 'workspace-write',
1062
+ onChange: (event) => patch('sideAgentPreset', event.target.value),
1063
+ },
1064
+ ['read-only', 'workspace-write', 'danger-full-access', 'inherit'].map((option) =>
1065
+ h('option', { key: option, value: option }, t[`opt_${option}`] ?? option),
1066
+ ),
1067
+ )),
1068
+ h(SettingRow, { key: 'approval', label: t.set_approvalPolicy, hint: t.set_approvalPolicyHint },
1069
+ h(
1070
+ 'select',
1071
+ {
1072
+ className: 'dshbtw-set-select',
1073
+ value: values.approvalPolicy ?? 'ask',
1074
+ onChange: (event) => patch('approvalPolicy', event.target.value),
1075
+ },
1076
+ ['ask', 'inherit'].map((option) => h('option', { key: option, value: option }, option)),
1077
+ )),
1078
+ numberField('answerMaxChars', t.set_answerMaxCharsHint),
1079
+ numberField('sideAgentTimeoutMs', t.set_sideAgentTimeoutMsHint),
1080
+ numberField('maxQuestionChars', t.set_maxQuestionCharsHint),
1081
+ h(SettingRow, { key: 'dispose', label: t.set_disposeChild, hint: t.set_disposeChildHint },
1082
+ h('label', { className: 'dshbtw-set-toggle' },
1083
+ h('input', {
1084
+ type: 'checkbox',
1085
+ checked: values.disposeChild !== false,
1086
+ onChange: (event) => patch('disposeChild', event.target.checked),
1087
+ }),
1088
+ h('span', null, values.disposeChild !== false ? t.on : t.off),
1089
+ )),
1090
+ h('button', { key: 'save', className: 'dshbtw-set-save', disabled: saving || !dirty, onClick: save },
1091
+ saving ? t.setSaving : t.setSave),
1092
+ status.text === ''
1093
+ ? null
1094
+ : h('div', {
1095
+ key: 'status',
1096
+ 'data-dshbtw': 'settings-status',
1097
+ 'data-kind': status.kind,
1098
+ className:
1099
+ status.kind === 'error' ? 'dshbtw-set-status is-error'
1100
+ : status.kind === 'ok' ? 'dshbtw-set-status is-ok'
1101
+ : 'dshbtw-set-status',
1102
+ }, status.text),
1103
+ )
1104
+ }
1105
+
1106
+ // -------------------------------------------------------------- bootstrap
1107
+
1108
+ /** Strings that may go into a locale dictionary (values must be plain text). */
1109
+ function stringsOnly(dict) {
1110
+ const out = {}
1111
+ for (const key of Object.keys(dict)) {
1112
+ if (typeof dict[key] === 'string') out[key] = dict[key]
1113
+ }
1114
+ return out
1115
+ }
1116
+
1117
+ /** Active language id, preferring the locale service over the document. */
1118
+ function activeLanguage(ctx) {
1119
+ const locale = ctx.get('locale')
1120
+ if (locale !== null && locale !== undefined && typeof locale.getLocale === 'function') {
1121
+ try {
1122
+ const snapshot = locale.getLocale()
1123
+ // LocaleSnapshot is `{ active, locales, revision }`.
1124
+ const id = snapshot !== null && typeof snapshot === 'object' ? snapshot.active : undefined
1125
+ if (typeof id === 'string' && id !== '') return id.toLowerCase().startsWith('zh') ? 'zh' : 'en'
1126
+ } catch {
1127
+ /* fall through to the document language */
1128
+ }
1129
+ }
1130
+ return documentLanguage()
1131
+ }
1132
+
1133
+ /** Resolve visible copy: the locale service when present, else `en`/`zh`. */
1134
+ function resolveStrings(ctx) {
1135
+ const base = STRINGS[activeLanguage(ctx)]
1136
+ const locale = ctx.get('locale')
1137
+ if (locale === null || locale === undefined || typeof locale.register !== 'function' || typeof locale.bind !== 'function') {
1138
+ return base
1139
+ }
1140
+ let translate
1141
+ try {
1142
+ ctx.effect(() => {
1143
+ const disposers = [
1144
+ locale.register('dsh-btw', 'zh', stringsOnly(STRINGS.zh)),
1145
+ locale.register('dsh-btw', 'en', stringsOnly(STRINGS.en)),
1146
+ ]
1147
+ return () => {
1148
+ for (const dispose of disposers) {
1149
+ try {
1150
+ dispose()
1151
+ } catch {
1152
+ /* a failed dictionary removal must not break unload */
1153
+ }
1154
+ }
1155
+ }
1156
+ }, 'dsh-btw locale')
1157
+ translate = locale.bind('dsh-btw')
1158
+ } catch {
1159
+ return base
1160
+ }
1161
+ if (typeof translate !== 'function') return base
1162
+ const merged = { ...base }
1163
+ for (const key of Object.keys(base)) {
1164
+ if (typeof base[key] !== 'string') continue
1165
+ try {
1166
+ const value = translate(key)
1167
+ if (typeof value === 'string' && value !== '') merged[key] = value
1168
+ } catch {
1169
+ /* keep the built-in copy for this key */
1170
+ }
1171
+ }
1172
+ // Pluralizing helpers stay language-specific closures.
1173
+ merged.count = base.count
1174
+ return merged
1175
+ }
1176
+
1177
+ return {
1178
+ // Hard dependencies of the hand-written module: the slot seat, and the
1179
+ // right-Sidebar tab registry + navigation controller. Declaring them here
1180
+ // is what makes `ctx.get` resolve them; the transcript chip still renders
1181
+ // if the right column is absent from the composition.
1182
+ inject: ['slots', 'sidebarRightTabs', 'sidebarRight'],
1183
+ apply(ctx) {
1184
+ const strings = resolveStrings(ctx)
1185
+ const tabs = ctx.get('sidebarRightTabs')
1186
+ const right = ctx.get('sidebarRight')
1187
+
1188
+ navigation.open = () => {
1189
+ try {
1190
+ if (right !== null && right !== undefined && typeof right.openTab === 'function') {
1191
+ right.openTab(KIND)
1192
+ debug.lastError = null
1193
+ } else {
1194
+ debug.lastError = 'sidebarRight.openTab unavailable'
1195
+ }
1196
+ } catch (error) {
1197
+ debug.lastError = error instanceof Error ? error.message : String(error)
1198
+ try {
1199
+ console.error('[dsh-btw] could not open the side-question page', error)
1200
+ } catch {
1201
+ /* ignore */
1202
+ }
1203
+ }
1204
+ }
1205
+
1206
+ /**
1207
+ * Open one side agent's own conversation in the right Sidebar.
1208
+ *
1209
+ * This is the built-in subagent tab: it renders the child's live
1210
+ * conversation, so the side agent's tool calls and its **approval
1211
+ * prompts** appear exactly where DSH puts them. Falls back to the
1212
+ * side-question page when the address is rejected.
1213
+ */
1214
+ navigation.openChild = (childId, parentId) => {
1215
+ if (typeof childId !== 'string' || childId === '') {
1216
+ navigation.open()
1217
+ return
1218
+ }
1219
+ const address = `dsh-resource://subagentchat/session/${childId}?parent=${parentId ?? ''}&mode=continuable`
1220
+ try {
1221
+ if (right !== null && right !== undefined && typeof right.openResource === 'function') {
1222
+ right.openResource(address)
1223
+ debug.lastError = null
1224
+ return
1225
+ }
1226
+ debug.lastError = 'sidebarRight.openResource unavailable'
1227
+ } catch (error) {
1228
+ debug.lastError = error instanceof Error ? error.message : String(error)
1229
+ }
1230
+ navigation.open()
1231
+ }
1232
+
1233
+ debug.tabs = tabs !== null && tabs !== undefined
1234
+ debug.right = right !== null && right !== undefined
1235
+ debug.open = navigation.open
1236
+ debug.openChild = navigation.openChild
1237
+
1238
+ // The page type: a page (no resource patterns), opened by kind.
1239
+ if (tabs !== null && tabs !== undefined && typeof tabs.register === 'function') {
1240
+ ctx.effect(
1241
+ () =>
1242
+ tabs.register({
1243
+ id: TYPE_ID,
1244
+ kind: KIND,
1245
+ priority: 'extension',
1246
+ title: () => strings.typeLabel,
1247
+ guide: [
1248
+ {
1249
+ id: 'questions',
1250
+ order: 20,
1251
+ title: () => strings.guideTitle,
1252
+ description: () => strings.guideDescription,
1253
+ icon: BtwGlyph,
1254
+ },
1255
+ ],
1256
+ }),
1257
+ 'dsh-btw tab type',
1258
+ )
1259
+
1260
+ ctx.slots.inject('sidebar.right.pane.tab', () =>
1261
+ ctx.slots.register(
1262
+ { name: 'sidebar.right.pane.tab', key: TYPE_ID },
1263
+ (props) => h(Boundary, { fallback: null }, h(BtwPage, { ...props, __btwStrings: strings })),
1264
+ ),
1265
+ )
1266
+ }
1267
+
1268
+ // The transcript chip works even without the right-Sidebar registry.
1269
+ ctx.slots.inject('conversation.chat.commandview', () =>
1270
+ ctx.slots.register(
1271
+ { name: 'conversation.chat.commandview', key: 'btw' },
1272
+ (props) => h(Boundary, { fallback: null }, h(BtwChip, { ...props, __btwStrings: strings })),
1273
+ ),
1274
+ )
1275
+
1276
+ // Always-present way back in: the header button reopens the page after
1277
+ // the user closes its tab.
1278
+ ctx.slots.inject('conversation.session.header.utilities', () =>
1279
+ ctx.slots.register(
1280
+ { name: 'conversation.session.header.utilities', id: 'dsh-btw-header', order: 30 },
1281
+ (props) => h(Boundary, { fallback: null }, h(BtwHeaderButton, { ...props, __btwStrings: strings })),
1282
+ ),
1283
+ )
1284
+
1285
+ // The settings page: edits the same profile row the plugin patch owns.
1286
+ ctx.slots.inject('settings.section', () =>
1287
+ ctx.slots.register(
1288
+ { name: 'settings.section', id: 'dsh-btw-settings', order: 55, label: strings.settingsTitle },
1289
+ (props) => h(Boundary, { fallback: null }, h(BtwSettings, { ...props, __btwStrings: strings })),
1290
+ ),
1291
+ )
1292
+ },
1293
+ }
1294
+ },
1295
+ })