@xiangyixie/dsh-superagent 0.15.4 → 0.16.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/lib/client.js CHANGED
@@ -1,15 +1,19 @@
1
1
  /**
2
2
  * dsh-superagent — browser half.
3
3
  *
4
- * One left-sidebar navigation entry ("超级智能体") that opens the existing
5
- * loopback console page inside a main panel. The console keeps its own
6
- * conversation, task lines, summary, artifacts and history; this module adds
7
- * no second UI, it only seats the page in the host frame.
4
+ * The "超级智能体" entry opens a main panel that is rendered natively inside
5
+ * the host React tree: host primitives (Button, FishLogo, the host icon set)
6
+ * plus the host's measured geometry, so the panel reads as one of the shell's
7
+ * own spaces. Nothing is framed: the page never carries its own chrome.
8
+ *
9
+ * Data still comes from the loopback console through the node half's
10
+ * same-origin relay (`/superagent/api` → `/api`), so no CORS or token handling
11
+ * lives in the browser.
8
12
  *
9
13
  * Failure containment is deliberate: this file must never take the host page
10
14
  * down. The top level only registers a factory; everything else runs inside
11
- * `withFallback`, so a bad address route or a missing slot leaves the entry
12
- * absent instead of breaking the frame.
15
+ * `apply`, so a bad relay or a missing slot leaves the entry absent instead of
16
+ * breaking the frame.
13
17
  *
14
18
  * @module dsh-superagent/client
15
19
  */
@@ -18,17 +22,17 @@ window.__ModuleLoader__.load({
18
22
  id: '@xiangyixie/dsh-superagent',
19
23
  factory: require => {
20
24
  // The host rejects the whole composition when a client module exposes no
21
- // `apply`, so publish a valid face first and only then fill it in. Anything
22
- // that fails below costs the sidebar row, never the page.
25
+ // `apply`, so publish a valid face first and only then fill it in.
23
26
  const exports = { apply() {} }
24
27
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
25
28
 
26
29
  const PANEL_ID = 'superagent'
27
30
  const PANEL_LABEL = '超级智能体'
28
- /** Host web-server route owned by this plugin's node half. */
29
- const ADDRESS_ROUTE = '/superagent/console-address'
30
- const RETRIES = 3
31
- const RETRY_MS = 700
31
+ /** Same-origin relay owned by this plugin's node half. */
32
+ const API = '/superagent/api/console'
33
+ const RETRIES = 8
34
+ const RETRY_MS = 500
35
+ const STYLE_ID = 'dsh-superagent-native-style'
32
36
 
33
37
  let react = null
34
38
  try {
@@ -37,213 +41,1006 @@ window.__ModuleLoader__.load({
37
41
  console.error('[dsh-superagent] cannot load react; the sidebar entry stays absent', error)
38
42
  }
39
43
 
40
- const h = react ? react.createElement : null
44
+ // Route A: the host exposes its own component library to plugin clients.
45
+ // Anything missing here degrades to a plain element, never to a second
46
+ // visual language (the metrics below are the host's).
47
+ let ui = null
48
+ try {
49
+ ui = require('@deepseek-ai/dsh-client-ui-primitives')
50
+ } catch (error) {
51
+ ui = null
52
+ }
41
53
 
42
- /** Decorative four-point spark used by the sidebar row. */
43
- function EntryIcon(props) {
44
- const size = typeof props?.size === 'number' ? props.size : 16
45
- return h(
46
- 'svg',
47
- {
48
- viewBox: '0 0 16 16',
49
- width: size,
50
- height: size,
51
- fill: 'none',
52
- stroke: 'currentColor',
53
- strokeWidth: 1.4,
54
- strokeLinecap: 'round',
55
- strokeLinejoin: 'round',
56
- 'aria-hidden': 'true',
54
+ const h = react ? react.createElement : null
55
+ const Button = ui && typeof ui.Button === 'function' ? ui.Button : null
56
+ const FishLogo = ui && typeof ui.FishLogo === 'function' ? ui.FishLogo : null
57
+ const MarkdownText = ui && typeof ui.MarkdownText === 'function' ? ui.MarkdownText : null
58
+ const UserMessageBubble = ui && typeof ui.UserMessageBubble === 'function' ? ui.UserMessageBubble : null
59
+ const StateDot = ui && typeof ui.StateDot === 'function' ? ui.StateDot : null
60
+ const ICONS = {
61
+ spark: ui?.IconSparkleRegular ?? ui?.IconSparkleMedium,
62
+ send: ui?.IconSendOutlineRegular ?? ui?.IconSendOutlineMedium,
63
+ plus: ui?.IconPlusOutlineRegular ?? ui?.IconPlusOutlineMedium,
64
+ newChat: ui?.IconNewChatOutlineRegular ?? ui?.IconNewChatOutlineMedium,
65
+ refresh: ui?.IconRefreshOutlineRegular ?? ui?.IconRefreshOutlineMedium,
66
+ stop: ui?.IconStopFillRegular ?? ui?.IconStopFillMedium,
67
+ clock: ui?.IconClockOutlineRegular ?? ui?.IconClockOutlineMedium,
68
+ check: ui?.IconCheckOutlineRegular ?? ui?.IconCheckOutlineMedium,
69
+ close: ui?.IconCloseOutlineRegular ?? ui?.IconCloseOutlineMedium,
70
+ folder: ui?.IconFolderCloseRegular ?? ui?.IconFolderCloseMedium,
71
+ }
72
+ // MarkdownText reads `labels.code` on every fenced block, so the host
73
+ // component is only safe with this shape filled in.
74
+ const MARKDOWN_LABELS = {
75
+ code: {
76
+ copyLabel: '复制',
77
+ copiedLabel: '已复制',
78
+ toolbarLabels: {
79
+ codeLabel: '代码',
80
+ wrapLabel: '换行',
81
+ unwrapLabel: '取消换行',
57
82
  },
58
- h('path', { d: 'M8 1.6l1.7 4.7L14.4 8l-4.7 1.7L8 14.4 6.3 9.7 1.6 8l4.7-1.7z' }),
59
- )
83
+ },
84
+ footnotes: '脚注',
60
85
  }
61
86
 
62
- const frameStyle = { position: 'absolute', inset: 0, width: '100%', height: '100%', border: '0', display: 'block' }
63
- const seatStyle = { position: 'relative', width: '100%', height: '100%', minHeight: '520px', background: 'transparent' }
64
- const STYLE_ID = 'dsh-superagent-seat-style'
65
-
66
87
  /**
67
- * The loading/error seat borrows the host's own tokens instead of its own
68
- * palette: label aliases for text, border-l2 for the outline, the
69
- * interactive hover/active fills and the 2px business focus ring.
88
+ * One class sheet for the panel. Every value is copied from the host's own
89
+ * modules: header 76px / 10-28-0-20, sidebar rows 32px / radius 12 / 5px 9px,
90
+ * hero title 26-32 / 500, hero pad 0 24, composer card radius 28, input
91
+ * 4-8-0-14 with a 36px docked floor and 52px hero floor, toolbar 2-8-6 with
92
+ * 12px gaps, send 34px circle on button-info-fill, stats row 22px.
70
93
  */
71
- function ensureSeatStyle() {
72
- if (typeof document === 'undefined') return
73
- if (!document.head || document.getElementById(STYLE_ID)) return
94
+ const CSS = `
95
+ .dsa-root{--dsa-col:clamp(680px,calc(var(--dsh-chat-user-width,100%) * .64),920px);display:flex;flex-direction:column;height:100%;min-width:0;background:var(--dsw-alias-bg-base,rgb(21,21,23));color:var(--dsw-alias-label-primary,#f9fafb);font-family:var(--dsw-font-family,inherit);font-size:14px;line-height:22px}
96
+ .dsa-header{display:flex;align-items:center;gap:10px;flex:none;box-sizing:border-box;min-height:76px;padding:10px 28px 0 20px;border-bottom:.5px solid var(--dsw-alias-border-l3,rgba(255,255,255,.12))}
97
+ .dsa-crumbs{display:flex;align-items:center;gap:4px;flex:1;min-width:0;overflow:hidden;white-space:nowrap}
98
+ .dsa-crumb{display:inline-block;max-width:220px;overflow:hidden;padding:4px 8px;border:0;border-radius:var(--dsw-radius-md,12px);background:transparent;color:var(--dsw-alias-label-tertiary,rgb(129,133,140));font-size:14px;line-height:20px;text-overflow:ellipsis;white-space:nowrap}
99
+ .dsa-crumb-current{font-weight:500;color:var(--dsw-alias-label-primary,#f9fafb)}
100
+ .dsa-sep{color:var(--dsw-alias-label-caption,rgb(129,133,140));font-size:14px;line-height:20px}
101
+ .dsa-head-actions{display:flex;flex:none;align-items:center;gap:8px;margin-left:20px}
102
+ .dsa-iconbtn{display:inline-flex;flex:none;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:var(--dsw-radius-sm,8px);background:transparent;color:var(--dsw-alias-label-secondary,rgb(207,211,214));cursor:pointer}
103
+ .dsa-iconbtn svg{width:15px;height:15px}
104
+ .dsa-iconbtn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}
105
+ .dsa-iconbtn:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-alias-state-business-primary,#7aaaff);outline-offset:-2px}
106
+ .dsa-status{display:inline-flex;align-items:center;gap:6px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary,rgb(129,133,140))}
107
+ .dsa-dot{width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-label-caption,rgb(129,133,140))}
108
+ .dsa-dot[data-state=live]{background:var(--dsw-alias-state-success-primary,#22c55e)}
109
+ .dsa-dot[data-state=warn]{background:var(--dsw-alias-state-warn-primary,#f59e0b)}
110
+ .dsa-body{display:flex;flex:1;min-height:0}
111
+ .dsa-main{position:relative;display:flex;flex-direction:column;flex:1;min-width:0}
112
+ .dsa-scroll{flex:1;min-height:0;overflow-y:auto;display:flex;flex-direction:column;margin-right:2px;padding:0 32px;scrollbar-gutter:stable}
113
+ .dsa-scroll::-webkit-scrollbar{width:10px}
114
+ .dsa-scroll::-webkit-scrollbar-thumb{border-radius:5px;background:var(--dsw-alias-scrollbar-bg-l1,rgba(255,255,255,.16))}
115
+ .dsa-flow{width:min(100%,var(--dsa-col));margin:0 auto;padding:16px 0 8px;box-sizing:border-box}
116
+ .dsa-hero{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:0 24px}
117
+ .dsa-hero-stack{display:flex;flex-direction:column;gap:12px;width:100%;max-width:calc(var(--dsa-col) + 32px);padding-bottom:32px}
118
+ .dsa-hero-title{display:flex;align-items:center;justify-content:center;gap:10px;font-size:26px;line-height:32px;font-weight:500;color:var(--dsw-alias-label-primary,#f9fafb)}
119
+ .dsa-hero-note{text-align:center;font-size:13px;line-height:20px;color:var(--dsw-alias-label-tertiary,rgb(129,133,140))}
120
+ .dsa-composer{flex:none;padding:0 16px 4px;background:var(--dsw-alias-bg-base,rgb(21,21,23))}
121
+ .dsa-card{display:flex;flex-direction:column;gap:12px;box-sizing:border-box;width:100%;max-width:calc(var(--dsa-col) + 32px);margin:0 auto;padding-top:8px;border-radius:var(--dsw-radius-panel,28px);background:var(--dsw-specific-input-major,rgb(35,35,36));box-shadow:var(--dsw-elevation-soft,0 2px 12px rgba(0,0,0,.18))}
122
+ .dsa-input{box-sizing:border-box;width:100%;min-height:36px;max-height:336px;padding:4px 8px 0 14px;border:0;outline:none;background:transparent;color:var(--dsw-alias-label-primary,#f9fafb);font:inherit;font-size:var(--dsh-content-font-size,14px);line-height:calc(24px + var(--dsh-content-font-delta,0px));resize:none;overflow-y:auto}
123
+ .dsa-input::placeholder{color:var(--dsw-alias-label-caption,rgb(129,133,140))}
124
+ .dsa-card[data-hero=true] .dsa-input{min-height:52px}
125
+ .dsa-row{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:2px 8px 6px;min-width:0}
126
+ .dsa-tools,.dsa-trailing{display:flex;align-items:center;min-width:0;gap:12px}
127
+ .dsa-trailing{margin-left:auto;flex:none}
128
+ .dsa-add{display:grid;place-items:center;flex:none;width:28px;height:28px;border:0;border-radius:999px;background:var(--dsw-specific-selector,rgba(255,255,255,.08));color:var(--dsw-alias-label-primary,#f9fafb);cursor:pointer}
129
+ .dsa-add:hover{background:var(--dsw-alias-interactive-bg-hover-solid,rgba(255,255,255,.14))}
130
+ .dsa-chip{height:28px;padding:0 20px 0 8px;border:0;border-radius:var(--dsw-radius-sm,8px);background-color:transparent;background-repeat:no-repeat;background-position:right 4px center;background-size:12px 12px;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12' fill='none'%3E%3Cpath d='M3 4.5L6 7.5L9 4.5' stroke='%2381858C' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");color:var(--dsw-alias-label-secondary,rgb(207,211,214));font-size:13px;line-height:20px;font-weight:500;white-space:nowrap;cursor:pointer;appearance:none}
131
+ .dsa-chip:hover{background-color:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}
132
+ .dsa-send{display:grid;place-items:center;flex:none;width:34px;height:34px;border:0;border-radius:999px;background:var(--dsw-alias-button-info-fill,#3964fe);color:var(--dsw-alias-label-on-color,#fff);cursor:pointer;transform:translateY(-2px);transition:background-color 100ms ease}
133
+ .dsa-send:hover:not(:disabled){background:var(--dsw-alias-button-info-hover,#2f57e6)}
134
+ .dsa-send:disabled{opacity:.4;cursor:default}
135
+ .dsa-send svg{width:15px;height:15px}
136
+ .dsa-send[data-mode=stop] svg{width:10px;height:10px;border-radius:2px}
137
+ .dsa-spin{width:14px;height:14px;border-radius:50%;border:2px solid rgba(255,255,255,.35);border-top-color:var(--dsw-alias-label-on-color,#fff);animation:dsa-spin .8s linear infinite}
138
+ @keyframes dsa-spin{to{transform:rotate(360deg)}}
139
+ .dsa-stats{min-height:calc(22px + var(--dsh-content-font-delta-secondary,0px));display:flex;align-items:center;justify-content:center;gap:10px;font-size:12px;line-height:20px;color:var(--dsw-alias-label-tertiary,rgb(129,133,140))}
140
+ .dsa-msg{padding:0 0 4px}
141
+ .dsa-user{display:flex;flex-direction:column;align-items:flex-end;gap:6px;margin-bottom:16px}
142
+ .dsa-bubble{max-width:min(calc(var(--dsa-col) * .702),82%);padding:10px 16px;border-radius:var(--dsw-radius-xl,20px);background:var(--dsw-specific-bubble,var(--dsw-static-deepseek-50,#eef4ff));color:var(--dsw-alias-label-primary,#f9fafb);font-size:var(--dsh-content-font-size,14px);line-height:calc(22px + var(--dsh-content-font-delta,0px));white-space:pre-wrap;overflow-wrap:anywhere}
143
+ .dsa-bubble[data-pending=true]{opacity:.6}
144
+ .dsa-assistant{display:flex;flex-direction:column;gap:6px;margin-bottom:16px;font-size:var(--dsh-content-font-size,14px);line-height:calc(24px + var(--dsh-content-font-delta,0px));overflow-wrap:anywhere}
145
+ .dsa-md-plain{white-space:pre-wrap;overflow-wrap:anywhere}
146
+ .dsa-tools-row{display:flex;flex-wrap:wrap;gap:6px}
147
+ .dsa-tool{display:inline-flex;align-items:center;gap:6px;height:24px;padding:0 8px;border-radius:var(--dsw-radius-xs,4px);background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.06));font-size:12px;line-height:16px;color:var(--dsw-alias-label-secondary,rgb(207,211,214))}
148
+ .dsa-tool[data-status=err]{color:var(--dsw-alias-state-error-primary,#f25a5a)}
149
+ .dsa-reasoning{font-size:13px;line-height:20px;color:var(--dsw-alias-label-tertiary,rgb(129,133,140));white-space:pre-wrap}
150
+ .dsa-typing{display:inline-flex;align-items:center;gap:8px;font-size:13px;line-height:20px;color:var(--dsw-alias-label-tertiary,rgb(129,133,140))}
151
+ .dsa-approvals{display:flex;flex-direction:column;gap:8px;width:min(calc(100% - 64px),var(--dsa-col));margin:0 auto;padding:0 0 8px}
152
+ .dsa-approval{display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--dsw-alias-state-warn-secondary,var(--dsw-static-amber-400,#fbbf24));border-radius:var(--dsw-radius-xl,20px);background:var(--dsw-specific-input-major,rgb(35,35,36));box-shadow:var(--dsw-shadow-lv2,0 4px 16px rgba(0,0,0,.18))}
153
+ .dsa-approval-bar{display:flex;align-items:center;gap:8px;padding:8px 14px;background:var(--dsw-alias-state-warn-tertiary,var(--dsw-static-amber-100,#fef3c7));color:var(--dsw-alias-state-warn-label,var(--dsw-static-amber-600,#d97706));font-size:13px;line-height:20px;font-weight:500}
154
+ .dsa-approval-main{display:flex;flex-direction:column;gap:10px;padding:12px 14px}
155
+ .dsa-approval-title{font-size:14px;line-height:22px;font-weight:500;color:var(--dsw-alias-label-primary,#f9fafb)}
156
+ .dsa-approval-body{font-size:13px;line-height:20px;color:var(--dsw-alias-label-secondary,rgb(207,211,214));overflow-wrap:anywhere}
157
+ .dsa-approval-actions{display:flex;flex-wrap:wrap;gap:8px;justify-content:flex-end}
158
+ .dsa-rail{display:flex;flex:none;flex-direction:column;width:260px;min-width:0;box-sizing:border-box;padding:6px 8px;border-left:.5px solid var(--dsw-alias-border-l3,rgba(255,255,255,.12))}
159
+ .dsa-rail-head{display:flex;align-items:center;justify-content:space-between;gap:6px;padding:6px 8px;font-size:13px;line-height:20px;color:var(--dsw-alias-label-tertiary,rgb(129,133,140))}
160
+ .dsa-rail-list{display:flex;flex-direction:column;gap:2px;min-height:0;overflow-y:auto;margin-bottom:8px}
161
+ .dsa-rowitem{display:flex;align-items:center;gap:6px;box-sizing:border-box;width:100%;height:32px;padding:0 8px 0 9px;border:0;border-radius:var(--dsw-radius-md,12px);background:transparent;color:var(--dsw-alias-label-primary,#f9fafb);font:inherit;font-size:14px;line-height:20px;text-align:left;cursor:pointer}
162
+ .dsa-rowitem:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}
163
+ .dsa-rowitem[data-selected=true]{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}
164
+ .dsa-rowitem:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-alias-state-business-primary,#7aaaff);outline-offset:-2px}
165
+ .dsa-rowtitle{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
166
+ .dsa-rowtime{flex:none;font-size:10px;line-height:16px;color:var(--dsw-alias-label-tertiary,rgb(129,133,140));margin-inline-end:-1px}
167
+ .dsa-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;height:100%;padding:24px;text-align:center}
168
+ .dsa-note{font-size:13px;line-height:1.6;color:var(--dsw-alias-label-secondary,rgb(207,211,214))}
169
+ .dsa-hint{font-size:12px;line-height:18px;color:var(--dsw-alias-label-caption,rgb(129,133,140))}
170
+ .dsa-toast{display:flex;align-items:center;gap:8px;margin:8px auto 0;width:min(calc(100% - 64px),var(--dsa-col));padding:6px 10px;border-radius:var(--dsw-radius-md,12px);background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08));color:var(--dsw-alias-label-secondary,rgb(207,211,214));font-size:12px;line-height:18px}
171
+ .dsa-toast[data-kind=err]{color:var(--dsw-alias-state-error-primary,#f25a5a)}
172
+ `
173
+
174
+ /** Inject the sheet once; the panel is mounted once per window. */
175
+ function ensureStyle() {
176
+ if (typeof document === 'undefined' || !document.head) return
177
+ if (document.getElementById(STYLE_ID)) return
74
178
  const style = document.createElement('style')
75
179
  style.id = STYLE_ID
76
- style.textContent = [
77
- '.dsh-superagent-note{position:absolute;inset:0;display:flex;flex-direction:column;',
78
- 'align-items:center;justify-content:center;gap:10px;padding:24px;text-align:center;',
79
- 'font-size:13px;line-height:1.6;color:var(--dsw-alias-label-secondary,inherit)}',
80
- '.dsh-superagent-note-hint{color:var(--dsw-alias-label-caption,inherit);font-size:12px}',
81
- '.dsh-superagent-retry{height:32px;padding:0 12px;border-radius:8px;font:inherit;',
82
- 'font-size:13px;font-weight:500;cursor:pointer;',
83
- 'border:1px solid var(--dsw-alias-border-l2,currentColor);background:transparent;',
84
- 'color:var(--dsw-alias-label-primary,inherit);transition:background .12s ease}',
85
- '.dsh-superagent-retry:hover{background:var(--dsw-alias-interactive-bg-hover,transparent)}',
86
- '.dsh-superagent-retry:active{background:var(--dsw-alias-interactive-bg-active,transparent)}',
87
- '.dsh-superagent-retry:focus-visible{outline:2px solid ',
88
- 'var(--dsw-alias-state-business-primary,currentColor);outline-offset:2px}',
89
- ].join('')
180
+ style.textContent = CSS
90
181
  document.head.appendChild(style)
91
182
  }
92
183
 
93
- /** The shell's own theme, as the console page expects it. */
94
- function shellTheme() {
184
+ /** Host icon, or nothing when the primitives module is absent. */
185
+ function Icon(props) {
186
+ const component = ICONS[props.of]
187
+ if (typeof component !== 'function') return null
188
+ return h(component, { size: props.size ?? 16, className: props.className })
189
+ }
190
+
191
+ /** Local echo while a sent message waits for the host to accept it. */
192
+ let localSeq = 0
193
+
194
+ /** One text run out of a content-part array. */
195
+ function contentText(content) {
196
+ if (typeof content === 'string') return content
197
+ if (!Array.isArray(content)) return ''
198
+ return content
199
+ .filter(part => part && part.type === 'text' && typeof part.text === 'string')
200
+ .map(part => part.text)
201
+ .join('')
202
+ }
203
+
204
+ function shortId(value) {
205
+ const text = typeof value === 'string' ? value : ''
206
+ return text ? text.slice(0, 8) : ''
207
+ }
208
+
209
+ function clockOf(value) {
210
+ const time = value ? Date.parse(value) : NaN
211
+ if (!Number.isFinite(time)) return ''
212
+ const date = new Date(time)
213
+ const sameDay = new Date().toDateString() === date.toDateString()
214
+ const pad = number => String(number).padStart(2, '0')
215
+ return sameDay
216
+ ? `${pad(date.getHours())}:${pad(date.getMinutes())}`
217
+ : `${date.getMonth() + 1}/${date.getDate()}`
218
+ }
219
+
220
+ function sessionTitle(session) {
221
+ if (!session || typeof session !== 'object') return ''
222
+ if (typeof session.title === 'string' && session.title.trim()) return session.title.trim()
223
+ if (typeof session.first === 'string' && session.first.trim()) return session.first.trim().slice(0, 60)
224
+ return shortId(session.sessionId) || '会话'
225
+ }
226
+
227
+ /** JSON call against the same-origin relay. */
228
+ async function call(path, init) {
229
+ const options = { cache: 'no-store', ...(init ?? {}) }
230
+ const headers = { accept: 'application/json', ...(init?.headers ?? {}) }
231
+ if (init && init.body) headers['content-type'] = 'application/json'
232
+ options.headers = headers
233
+ const response = await fetch(`${API}${path}`, options)
234
+ let body = null
95
235
  try {
96
- return document.body?.hasAttribute('data-ds-dark-theme') ? 'dark' : 'light'
236
+ body = await response.json()
97
237
  } catch {
98
- return 'light'
238
+ // A non-JSON answer means the relay or a gate answered instead.
99
239
  }
240
+ if (!response.ok || body?.ok === false) {
241
+ const error = new Error(body?.message ?? `HTTP ${response.status}`)
242
+ error.hint = typeof body?.hint === 'string' ? body.hint : ''
243
+ error.status = response.status
244
+ throw error
245
+ }
246
+ return body?.data ?? null
100
247
  }
101
248
 
102
- /**
103
- * The page this module runs inside, as `protocol//host`. The console page
104
- * has to name its framer in `frame-ancestors`, and a desktop shell serves
105
- * its chrome from a custom scheme, so passing the scheme along keeps that
106
- * list correct when the shell switches to another one.
107
- * @returns {string} the framing page's scheme and host, or '' when opaque.
108
- */
109
- function parentOrigin() {
110
- try {
111
- const protocol = String(window.location?.protocol ?? '')
112
- if (!/^[a-z][a-z0-9+.-]*:$/i.test(protocol)) return ''
113
- const host = String(window.location?.host ?? '')
114
- return host ? `${protocol}//${host}` : protocol
115
- } catch {
116
- return ''
249
+ function wait(ms) {
250
+ return new Promise(resolve => setTimeout(resolve, ms))
251
+ }
252
+
253
+ /** Blank model for one panel mount. */
254
+ function initialModel() {
255
+ return {
256
+ phase: 'loading',
257
+ reason: '',
258
+ hint: '',
259
+ sessionId: null,
260
+ capabilities: null,
261
+ messages: [],
262
+ approvals: [],
263
+ runs: [],
264
+ sessions: [],
265
+ sessionsReason: '',
266
+ conn: 'connecting',
267
+ mode: 'queue',
268
+ toast: null,
269
+ canceling: false,
270
+ approvalBusy: {},
271
+ typing: false,
272
+ sending: false,
273
+ currentId: null,
274
+ railBusy: false,
117
275
  }
118
276
  }
119
277
 
278
+ /** Replace one message in place and keep every other row identical. */
279
+ function patchMessage(messages, id, patch) {
280
+ return messages.map(message => (message.id === id ? { ...message, ...patch } : message))
281
+ }
282
+
283
+ /** Drop one key from a busy-map without touching the rest. */
284
+ function omitKey(map, key) {
285
+ const next = { ...(map ?? {}) }
286
+ delete next[key]
287
+ return next
288
+ }
289
+
290
+ /** Add or update a tool chip on the streaming assistant message. */
291
+ function upsertTool(messages, id, tool) {
292
+ return messages.map(message => {
293
+ if (message.id !== id) return message
294
+ const tools = Array.isArray(message.tools) ? message.tools.slice() : []
295
+ const index = tools.findIndex(entry => entry.callId === tool.callId)
296
+ if (index >= 0) tools[index] = { ...tools[index], ...tool }
297
+ else tools.push(tool)
298
+ return { ...message, tools }
299
+ })
300
+ }
301
+
302
+ /** The streaming assistant row, created on first use. */
303
+ function assistantRow(model, at) {
304
+ if (model.currentId && model.messages.some(message => message.id === model.currentId)) {
305
+ return { model, id: model.currentId }
306
+ }
307
+ localSeq += 1
308
+ const id = `assistant-local-${localSeq}`
309
+ const row = { id, role: 'assistant', text: '', reasoning: '', tools: [], at: at ?? Date.now(), streaming: true }
310
+ return { model: { ...model, messages: [...model.messages, row], currentId: id }, id }
311
+ }
312
+
120
313
  /**
121
- * Ask the plugin's node half where the console listens. The answer carries
122
- * the one-time token because this route is same-origin and loopback-only.
123
- * @returns {Promise<{src: string} | {reason: string}>} iframe address or why it is missing.
314
+ * Fold one session event into the model, mirroring what the console page
315
+ * does with the same frames.
124
316
  */
125
- async function readAddress() {
126
- let response
127
- try {
128
- response = await fetch(ADDRESS_ROUTE, { headers: { accept: 'application/json' }, cache: 'no-store' })
129
- } catch (error) {
130
- return { reason: `取不到控制台地址:${error?.message ?? error}` }
317
+ function applySessionEvent(model, event) {
318
+ if (!event || typeof event !== 'object') return model
319
+ const data = event.data && typeof event.data === 'object' ? event.data : {}
320
+ switch (event.type) {
321
+ case 'turn/start':
322
+ case 'step/start':
323
+ return { ...model, typing: true }
324
+ case 'turn/end': {
325
+ let next = { ...model, typing: false, canceling: false }
326
+ if (next.currentId) {
327
+ next = { ...next, messages: patchMessage(next.messages, next.currentId, { streaming: false }), currentId: null }
328
+ }
329
+ return next
330
+ }
331
+ case 'user/message': {
332
+ if (data.source && data.source.kind && data.source.kind !== 'user') return model
333
+ const text = contentText(data.content).trim()
334
+ if (!text) return model
335
+ const pendingIndex = model.messages.findIndex(message => message.role === 'user' && message.pending && message.text.trim() === text)
336
+ if (pendingIndex >= 0) {
337
+ const messages = model.messages.slice()
338
+ messages[pendingIndex] = { ...messages[pendingIndex], pending: false, at: event.time ?? messages[pendingIndex].at }
339
+ return { ...model, messages, typing: true }
340
+ }
341
+ localSeq += 1
342
+ const row = { id: `user-${localSeq}`, role: 'user', text, at: event.time ?? Date.now() }
343
+ return { ...model, messages: [...model.messages, row], typing: true }
344
+ }
345
+ case 'assistant/message': {
346
+ const finalText = contentText(data.message?.content)
347
+ const reasoning = contentText((data.message?.content ?? []).filter(part => part && part.type === 'reasoning'))
348
+ let next = model
349
+ const created = assistantRow(next, event.time)
350
+ next = created.model
351
+ const id = created.id
352
+ const patch = { streaming: false }
353
+ if (finalText) patch.text = finalText
354
+ if (reasoning) patch.reasoning = reasoning
355
+ if (data.interrupted === true) patch.interrupted = true
356
+ next = { ...next, messages: patchMessage(next.messages, id, patch), currentId: null }
357
+ const calls = Array.isArray(data.message?.content)
358
+ ? data.message.content.filter(part => part && part.type === 'tool-call')
359
+ : []
360
+ for (const entry of calls) {
361
+ next = { ...next, messages: upsertTool(next.messages, id, {
362
+ callId: entry.id ?? entry.callId,
363
+ name: entry.name ?? 'tool',
364
+ status: 'ok',
365
+ arguments: entry.arguments,
366
+ }) }
367
+ }
368
+ return next
369
+ }
370
+ case 'tool/call': {
371
+ const created = assistantRow(model, event.time)
372
+ const next = { ...created.model, typing: true }
373
+ return { ...next, messages: upsertTool(next.messages, created.id, {
374
+ callId: data.callId,
375
+ name: data.name ?? 'tool',
376
+ status: 'running',
377
+ arguments: data.arguments,
378
+ }) }
379
+ }
380
+ case 'tool/result': {
381
+ const callId = data.callId ?? data.message?.toolCallId ?? data.message?.source?.callId
382
+ if (!callId) return model
383
+ return {
384
+ ...model,
385
+ messages: model.messages.map(message => {
386
+ if (!Array.isArray(message.tools) || !message.tools.some(tool => tool.callId === callId)) return message
387
+ return {
388
+ ...message,
389
+ tools: message.tools.map(tool => (tool.callId === callId
390
+ ? { ...tool, status: data.message?.isError ? 'err' : 'ok' }
391
+ : tool)),
392
+ }
393
+ }),
394
+ }
395
+ }
396
+ default:
397
+ return model
131
398
  }
132
- let body = null
133
- try {
134
- body = await response.json()
135
- } catch {
136
- // A non-JSON answer means the host web server did not route to us.
399
+ }
400
+
401
+ /** Fold one assistant streaming frame into the model. */
402
+ function applyAssistantFrame(model, frame) {
403
+ if (!frame || typeof frame !== 'object') return model
404
+ if (frame.type === 'start') {
405
+ const created = assistantRow(model, Date.now())
406
+ return { ...created.model, typing: true }
137
407
  }
138
- const data = body?.data
139
- if (response.ok && data?.ready === true && data.url && data.token) {
140
- const parent = parentOrigin()
141
- const hint = parent ? `&parent=${encodeURIComponent(parent)}` : ''
142
- return { src: `${data.url}/?token=${encodeURIComponent(data.token)}${hint}&theme=${shellTheme()}` }
408
+ if (frame.type === 'chunk' && frame.chunk) {
409
+ const created = assistantRow(model, Date.now())
410
+ const id = created.id
411
+ const current = created.model.messages.find(message => message.id === id) ?? {}
412
+ if (frame.chunk.type === 'text-delta' && typeof frame.chunk.text === 'string') {
413
+ return { ...created.model, messages: patchMessage(created.model.messages, id, { text: `${current.text ?? ''}${frame.chunk.text}` }) }
414
+ }
415
+ if (frame.chunk.type === 'reasoning-delta' && typeof frame.chunk.text === 'string') {
416
+ return { ...created.model, messages: patchMessage(created.model.messages, id, { reasoning: `${current.reasoning ?? ''}${frame.chunk.text}` }) }
417
+ }
418
+ return created.model
143
419
  }
144
- const reason = body?.message
145
- ?? (typeof data?.reason === 'string' ? data.reason : null)
146
- ?? (response.status === 404
147
- ? '宿主还没接入 Superagent 控制台(console-address 路由未注册)。'
148
- : `控制台暂不可用(HTTP ${response.status})。`)
149
- return { reason }
420
+ if (frame.type === 'end' && model.currentId) {
421
+ return {
422
+ ...model,
423
+ messages: patchMessage(model.messages, model.currentId, { streaming: false }),
424
+ currentId: null,
425
+ typing: false,
426
+ }
427
+ }
428
+ return model
150
429
  }
151
430
 
152
- /**
153
- * The main panel: the console page itself, filling the frame.
154
- * @returns {object} React element.
155
- */
156
- function ConsoleSurface() {
157
- const [view, setView] = react.useState({ phase: 'loading', src: null, reason: '' })
431
+ /** Fold one console frame into the model. */
432
+ function applyFrame(model, frame) {
433
+ if (!frame || typeof frame !== 'object') return model
434
+ switch (frame.type) {
435
+ case 'hello':
436
+ return { ...model, sessionId: frame.sessionId ?? model.sessionId, capabilities: frame.capabilities ?? model.capabilities, conn: 'live' }
437
+ case 'session':
438
+ if (!frame.sessionId || frame.sessionId === model.sessionId) return model
439
+ return { ...model, sessionId: frame.sessionId, messages: [], approvals: [], approvalBusy: {}, currentId: null, typing: false, canceling: false }
440
+ case 'stream.snapshot': {
441
+ let next = { ...model, messages: [], currentId: null }
442
+ if (frame.header?.id) next.sessionId = frame.header.id
443
+ for (const record of Array.isArray(frame.records) ? frame.records : []) {
444
+ if (record?.type === 'event' && record.event) next = applySessionEvent(next, record.event)
445
+ }
446
+ return next
447
+ }
448
+ case 'session.event':
449
+ return applySessionEvent(model, frame.event)
450
+ case 'assistant.frame':
451
+ return applyAssistantFrame(model, frame.frame)
452
+ case 'accepted': {
453
+ const index = model.messages.findIndex(message => message.role === 'user' && message.pending && message.text.trim() === String(frame.text ?? '').trim())
454
+ if (index < 0) return model
455
+ return { ...model, messages: patchMessage(model.messages, model.messages[index].id, { pending: false, at: Date.now() }) }
456
+ }
457
+ case 'approval': {
458
+ const approval = frame.approval
459
+ if (frame.action === 'asked' && approval?.id) {
460
+ const others = model.approvals.filter(entry => entry.id !== approval.id)
461
+ return { ...model, approvals: [...others, approval] }
462
+ }
463
+ if (frame.id) {
464
+ return { ...model, approvals: model.approvals.filter(entry => entry.id !== frame.id) }
465
+ }
466
+ return model
467
+ }
468
+ case 'runs':
469
+ return { ...model, runs: Array.isArray(frame.runs) ? frame.runs : [] }
470
+ case 'canceling':
471
+ return { ...model, canceling: true }
472
+ case 'error':
473
+ return { ...model, conn: frame.code === 'follow-failed' || frame.code === 'state-failed' ? 'warn' : model.conn }
474
+ case 'closed':
475
+ return { ...model, conn: 'warn' }
476
+ default:
477
+ return model
478
+ }
479
+ }
480
+
481
+ function Header(props) {
482
+ const { model, title, onNew, onRefresh } = props
483
+ return h('header', { className: 'dsa-header' },
484
+ h('div', { className: 'dsa-crumbs' },
485
+ h('span', { className: 'dsa-crumb' }, PANEL_LABEL),
486
+ h('span', { className: 'dsa-sep' }, '/'),
487
+ h('span', { className: 'dsa-crumb dsa-crumb-current' }, title)),
488
+ h('div', { className: 'dsa-head-actions' },
489
+ h('span', { className: 'dsa-status' },
490
+ h('span', { className: 'dsa-dot', 'data-state': model.conn }),
491
+ model.conn === 'live' ? '已连接' : model.conn === 'warn' ? '流中断' : '连接中'),
492
+ h('button', { type: 'button', className: 'dsa-iconbtn', title: '刷新', onClick: onRefresh },
493
+ h(Icon, { of: 'refresh' })),
494
+ h('button', { type: 'button', className: 'dsa-iconbtn', title: '新建会话', onClick: onNew },
495
+ h(Icon, { of: 'newChat' }))))
496
+ }
497
+
498
+ function UserMessage(props) {
499
+ const pending = props.message.pending === true
500
+ return h('div', { className: 'dsa-user', style: pending ? { opacity: 0.6 } : undefined },
501
+ UserMessageBubble
502
+ ? h(UserMessageBubble, { className: pending ? 'dsa-bubble-pending' : undefined }, props.message.text)
503
+ : h('div', { className: 'dsa-bubble', 'data-pending': pending ? 'true' : 'false' }, props.message.text))
504
+ }
505
+
506
+ function AssistantMessage(props) {
507
+ const message = props.message
508
+ const tools = Array.isArray(message.tools) ? message.tools : []
509
+ const children = []
510
+ if (message.reasoning) {
511
+ children.push(h('div', { key: 'reasoning', className: 'dsa-reasoning' }, message.reasoning))
512
+ }
513
+ if (tools.length > 0) {
514
+ children.push(h('div', { key: 'tools', className: 'dsa-tools-row' }, tools.map(tool => h('span', {
515
+ key: tool.callId ?? tool.name,
516
+ className: 'dsa-tool',
517
+ 'data-status': tool.status,
518
+ title: typeof tool.arguments === 'string' ? tool.arguments : undefined,
519
+ }, tool.name))))
520
+ }
521
+ if (message.text) {
522
+ children.push(MarkdownText
523
+ ? h(MarkdownText, {
524
+ key: 'text',
525
+ text: message.text,
526
+ streaming: message.streaming === true,
527
+ labels: MARKDOWN_LABELS,
528
+ })
529
+ : h('div', { key: 'text', className: 'dsa-md-plain' }, message.text))
530
+ }
531
+ return h('div', { className: 'dsa-assistant' }, children)
532
+ }
533
+
534
+ function Transcript(props) {
535
+ const rows = []
536
+ for (const message of props.model.messages) {
537
+ rows.push(h('div', { key: message.id, className: 'dsa-msg' },
538
+ message.role === 'user'
539
+ ? h(UserMessage, { message })
540
+ : h(AssistantMessage, { message })))
541
+ }
542
+ if (props.model.typing) {
543
+ rows.push(h('div', { key: 'typing', className: 'dsa-typing' }, '正在生成…'))
544
+ }
545
+ return h('div', {
546
+ className: 'dsa-scroll',
547
+ ref: props.scrollRef,
548
+ }, h('div', { className: 'dsa-flow' }, rows))
549
+ }
550
+
551
+ function Approvals(props) {
552
+ if (!props.approvals.length) return null
553
+ return h('div', { className: 'dsa-approvals' }, props.approvals.map(entry => {
554
+ const busy = props.busy?.[entry.id] === true
555
+ return h('div', {
556
+ key: entry.id,
557
+ className: 'dsa-approval',
558
+ 'aria-busy': busy ? 'true' : undefined,
559
+ },
560
+ h('div', { className: 'dsa-approval-bar' },
561
+ StateDot ? h(StateDot, { state: 'warning', size: 10 }) : null,
562
+ h('span', null, '等待你的批准')),
563
+ h('div', { className: 'dsa-approval-main' },
564
+ h('div', { className: 'dsa-approval-title' }, entry.toolName ?? '工具调用'),
565
+ entry.callArguments || entry.reason
566
+ ? h('div', { className: 'dsa-approval-body' }, entry.callArguments ?? entry.reason)
567
+ : null,
568
+ h('div', { className: 'dsa-approval-actions' },
569
+ h(Button ?? 'button', {
570
+ variant: Button ? 'outline' : undefined,
571
+ className: Button ? undefined : 'dsa-add',
572
+ type: Button ? undefined : 'button',
573
+ disabled: busy,
574
+ onClick: () => props.onDecide(entry.id, 'reject'),
575
+ }, '拒绝'),
576
+ h(Button ?? 'button', {
577
+ variant: Button ? 'primary' : undefined,
578
+ type: Button ? undefined : 'button',
579
+ disabled: busy,
580
+ onClick: () => props.onDecide(entry.id, 'allow'),
581
+ }, '允许一次'),
582
+ h(Button ?? 'button', {
583
+ variant: Button ? 'outline' : undefined,
584
+ type: Button ? undefined : 'button',
585
+ disabled: busy,
586
+ onClick: () => props.onDecide(entry.id, 'allow-tool'),
587
+ }, '本会话都放行'))))
588
+ }))
589
+ }
590
+
591
+ function Composer(props) {
592
+ const { hero, disabled, onSend } = props
593
+ const [text, setText] = react.useState('')
594
+ const [busy, setBusy] = react.useState(false)
595
+ const areaRef = react.useRef(null)
596
+ const fileRef = react.useRef(null)
597
+
598
+ const grow = () => {
599
+ const area = areaRef.current
600
+ if (!area) return
601
+ area.style.height = 'auto'
602
+ area.style.height = `${Math.min(area.scrollHeight, 336)}px`
603
+ }
604
+
605
+ /** Files are copied into the workspace by the console, then the path is typed. */
606
+ const attach = async files => {
607
+ const list = Array.from(files || []).filter(Boolean)
608
+ if (list.length === 0) return
609
+ setBusy(true)
610
+ for (const file of list) {
611
+ try {
612
+ const bytes = new Uint8Array(await file.arrayBuffer())
613
+ let binary = ''
614
+ for (let index = 0; index < bytes.length; index += 1) binary += String.fromCharCode(bytes[index])
615
+ const data = await call('/upload', {
616
+ method: 'POST',
617
+ body: JSON.stringify({ sessionId: props.model.sessionId, name: file.name, data: btoa(binary) }),
618
+ })
619
+ if (data?.path) {
620
+ setText(current => `${current}${current && !current.endsWith(' ') ? ' ' : ''}${data.path} `)
621
+ }
622
+ } catch (error) {
623
+ props.onError?.(`${file.name}:${error.message}`)
624
+ }
625
+ }
626
+ setBusy(false)
627
+ grow()
628
+ }
629
+
630
+ const submit = () => {
631
+ const value = text.trim()
632
+ if (!value || disabled) return
633
+ setText('')
634
+ if (areaRef.current) areaRef.current.style.height = 'auto'
635
+ onSend(value)
636
+ }
637
+
638
+ return h('div', { className: 'dsa-composer' },
639
+ h('div', { className: 'dsa-card', 'data-hero': hero ? 'true' : 'false' },
640
+ h('textarea', {
641
+ ref: areaRef,
642
+ className: 'dsa-input',
643
+ rows: 1,
644
+ value: text,
645
+ placeholder: hero ? '想让我做什么?' : '继续这条对话…',
646
+ disabled,
647
+ onInput: event => {
648
+ setText(event.target.value)
649
+ grow()
650
+ },
651
+ onKeyDown: event => {
652
+ if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent?.isComposing) {
653
+ event.preventDefault()
654
+ submit()
655
+ }
656
+ },
657
+ }),
658
+ h('div', { className: 'dsa-row' },
659
+ h('div', { className: 'dsa-tools' },
660
+ h('input', {
661
+ ref: fileRef,
662
+ type: 'file',
663
+ multiple: true,
664
+ style: { display: 'none' },
665
+ onChange: event => {
666
+ attach(event.target.files)
667
+ event.target.value = ''
668
+ },
669
+ }),
670
+ h('button', {
671
+ type: 'button',
672
+ className: 'dsa-add',
673
+ title: '放进工作区',
674
+ disabled: busy,
675
+ onClick: () => fileRef.current?.click(),
676
+ }, h(Icon, { of: 'plus', size: 16 })),
677
+ h('select', {
678
+ className: 'dsa-chip',
679
+ value: props.mode ?? 'queue',
680
+ onChange: event => props.onMode(event.target.value),
681
+ title: '发送方式',
682
+ },
683
+ h('option', { value: 'queue' }, '排队'),
684
+ h('option', { value: 'steer' }, '插话'))),
685
+ h('div', { className: 'dsa-trailing' },
686
+ props.running
687
+ ? h('button', {
688
+ type: 'button',
689
+ className: 'dsa-send',
690
+ 'data-mode': 'stop',
691
+ 'aria-label': '停止本轮',
692
+ title: '停止本轮',
693
+ disabled: props.canceling === true,
694
+ onClick: () => props.onStop?.(),
695
+ }, props.canceling ? h('span', { className: 'dsa-spin' }) : h(Icon, { of: 'stop', size: 10 }))
696
+ : h('button', {
697
+ type: 'button',
698
+ className: 'dsa-send',
699
+ disabled: disabled || !text.trim(),
700
+ title: '发送',
701
+ onClick: submit,
702
+ }, h(Icon, { of: 'send', size: 15 }))))),
703
+ h('div', { className: 'dsa-stats' },
704
+ h('span', null, props.model.sessionId ? `会话 ${shortId(props.model.sessionId)}` : '还没有会话'),
705
+ h('span', null, `${props.model.runs.length} 条任务线`)))
706
+ }
707
+
708
+ function Rail(props) {
709
+ const { model, onSwitch } = props
710
+ return h('aside', { className: 'dsa-rail' },
711
+ h('div', { className: 'dsa-rail-head' },
712
+ h('span', null, '会话'),
713
+ h('span', null, `${model.sessions.length}`)),
714
+ h('div', { className: 'dsa-rail-list' },
715
+ model.sessions.length === 0
716
+ ? h('div', { className: 'dsa-hint', style: { padding: '8px' } }, model.sessionsReason || '还没有历史会话')
717
+ : model.sessions.map(session => h('button', {
718
+ key: session.sessionId,
719
+ type: 'button',
720
+ className: 'dsa-rowitem',
721
+ 'data-selected': session.sessionId === model.sessionId ? 'true' : 'false',
722
+ title: sessionTitle(session),
723
+ onClick: () => onSwitch(session.sessionId),
724
+ },
725
+ h('span', { className: 'dsa-rowtitle' }, sessionTitle(session)),
726
+ h('span', { className: 'dsa-rowtime' }, clockOf(session.updatedAt))))),
727
+ h('div', { className: 'dsa-rail-head' },
728
+ h('span', null, '任务线'),
729
+ h('span', null, `${model.runs.length}`)),
730
+ h('div', { className: 'dsa-rail-list' },
731
+ model.runs.length === 0
732
+ ? h('div', { className: 'dsa-hint', style: { padding: '8px' } }, '这一轮还没有任务线')
733
+ : model.runs.map(run => h('div', {
734
+ key: run.id,
735
+ className: 'dsa-rowitem',
736
+ title: run.goal ?? '',
737
+ },
738
+ h('span', { className: 'dsa-rowtitle' }, run.goal ?? '任务线'),
739
+ h('span', { className: 'dsa-rowtime' }, run.status === 'running' ? '运行中' : run.status === 'completed' ? '完成' : '已停')))))
740
+ }
741
+
742
+ function Hero(props) {
743
+ const ready = props.model.capabilities?.chat !== false
744
+ return h('div', { className: 'dsa-hero' },
745
+ h('div', { className: 'dsa-hero-stack' },
746
+ h('div', { className: 'dsa-hero-title' },
747
+ FishLogo ? h(FishLogo, { size: 32 }) : h(Icon, { of: 'spark', size: 26 }),
748
+ h('span', null, PANEL_LABEL)),
749
+ h('div', { className: 'dsa-hero-note' }, ready
750
+ ? '说一句话就开始:它会拆任务、并行走、把结果收回来说给你。'
751
+ : (props.model.capabilities?.reason ?? '这个宿主暂时不能对话')),
752
+ h(Composer, { ...props, hero: true, disabled: props.disabled || !ready })))
753
+ }
754
+
755
+ function Seat(props) {
756
+ const { model, dispatch } = props
757
+ if (model.phase === 'loading') {
758
+ return h('div', { className: 'dsa-root' },
759
+ h('div', { className: 'dsa-empty' },
760
+ h('div', { className: 'dsa-note' }, '正在连接 Superagent 专属空间…')))
761
+ }
762
+ if (model.phase === 'error') {
763
+ return h('div', { className: 'dsa-root' },
764
+ h('div', { className: 'dsa-empty' },
765
+ h('div', { className: 'dsa-note' }, model.reason),
766
+ h('div', { className: 'dsa-hint' }, model.hint || '在「高级」里确认控制台端口已开启(consolePort),或重试。'),
767
+ h(Button ?? 'button', {
768
+ variant: Button ? 'outline' : undefined,
769
+ type: Button ? undefined : 'button',
770
+ onClick: () => dispatch({ type: 'retry' }),
771
+ }, '重试')))
772
+ }
773
+ const title = (() => {
774
+ const current = model.sessions.find(session => session.sessionId === model.sessionId)
775
+ return current ? sessionTitle(current) : model.sessionId ? `会话 ${shortId(model.sessionId)}` : '新会话'
776
+ })()
777
+ const empty = model.messages.length === 0
778
+ const notify = text => dispatch({ type: 'toast', text })
779
+ return h('div', { className: 'dsa-root' },
780
+ h(Header, {
781
+ model,
782
+ title,
783
+ onNew: () => dispatch({ type: 'new-session' }),
784
+ onRefresh: () => dispatch({ type: 'refresh' }),
785
+ }),
786
+ h(Toast, { toast: model.toast }),
787
+ h('div', { className: 'dsa-body' },
788
+ h('div', { className: 'dsa-main' },
789
+ empty
790
+ ? h(Hero, {
791
+ model,
792
+ mode: model.mode,
793
+ disabled: model.sending,
794
+ running: model.typing,
795
+ canceling: model.canceling,
796
+ onStop: () => dispatch({ type: 'cancel' }),
797
+ onSend: text => dispatch({ type: 'send', text }),
798
+ onMode: mode => dispatch({ type: 'mode', mode }),
799
+ onError: notify,
800
+ })
801
+ : h(Transcript, { model, scrollRef: model.scrollRef }),
802
+ h(Approvals, {
803
+ approvals: model.approvals,
804
+ busy: model.approvalBusy,
805
+ onDecide: (id, decision) => dispatch({ type: 'decide', id, decision }),
806
+ }),
807
+ empty ? null : h(Composer, {
808
+ model,
809
+ mode: model.mode,
810
+ disabled: model.sending || model.capabilities?.chat === false,
811
+ running: model.typing,
812
+ canceling: model.canceling,
813
+ onStop: () => dispatch({ type: 'cancel' }),
814
+ onSend: text => dispatch({ type: 'send', text }),
815
+ onMode: mode => dispatch({ type: 'mode', mode }),
816
+ onError: notify,
817
+ })),
818
+ h(Rail, {
819
+ model,
820
+ onSwitch: sessionId => dispatch({ type: 'switch', sessionId }),
821
+ })))
822
+ }
823
+
824
+ /** One-line status above the composer; errors stay until replaced. */
825
+ function Toast(props) {
826
+ if (!props.toast) return null
827
+ return h('div', { className: 'dsa-toast', 'data-kind': props.toast.kind }, props.toast.text)
828
+ }
829
+
830
+ function Panel() {
831
+ const [model, setModel] = react.useState(initialModel)
158
832
  const [attempt, setAttempt] = react.useState(0)
833
+ const scrollRef = react.useRef(null)
834
+ const modelRef = react.useRef(model)
835
+ modelRef.current = model
836
+
837
+ const patch = updater => setModel(current => updater(current))
159
838
 
839
+ /** Pull the session list; a failure only dims the rail. */
840
+ const loadSessions = async () => {
841
+ try {
842
+ const data = await call('/sessions')
843
+ patch(current => ({
844
+ ...current,
845
+ sessions: Array.isArray(data?.sessions) ? data.sessions : [],
846
+ sessionsReason: typeof data?.reason === 'string' ? data.reason : '',
847
+ }))
848
+ } catch (error) {
849
+ patch(current => ({ ...current, sessionsReason: error.message }))
850
+ }
851
+ }
852
+
853
+ // Connect once per attempt: wait for the relay, then follow the feed.
160
854
  react.useEffect(() => {
161
855
  let alive = true
162
- let timer = null
163
- let tries = 0
164
- const settle = next => {
165
- if (alive) setView(next)
166
- }
167
- const load = async () => {
168
- const address = await readAddress()
169
- if (!alive) return
170
- if (address.src) {
171
- settle({ phase: 'ready', src: address.src, reason: '' })
172
- return
173
- }
174
- // The node half binds the console after the plugin is ready; a first
175
- // miss is ordinary startup, not a failure the user should see.
176
- if (tries < RETRIES) {
177
- tries += 1
178
- timer = setTimeout(load, RETRY_MS)
179
- return
856
+ let source = null
857
+ const open = async () => {
858
+ for (let index = 0; index < RETRIES; index += 1) {
859
+ try {
860
+ const data = await call('/state')
861
+ if (!alive) return
862
+ patch(current => ({
863
+ ...current,
864
+ phase: 'ready',
865
+ reason: '',
866
+ hint: '',
867
+ sessionId: data?.sessionId ?? null,
868
+ capabilities: data?.capabilities ?? null,
869
+ approvals: Array.isArray(data?.approvals) ? data.approvals : [],
870
+ runs: Array.isArray(data?.runs) ? data.runs : [],
871
+ }))
872
+ break
873
+ } catch (error) {
874
+ if (index === RETRIES - 1) {
875
+ if (!alive) return
876
+ patch(current => ({ ...current, phase: 'error', reason: error.message, hint: error.hint ?? '' }))
877
+ return
878
+ }
879
+ await wait(RETRY_MS)
880
+ }
180
881
  }
181
- settle({ phase: 'error', src: null, reason: address.reason })
882
+ if (!alive) return
883
+ loadSessions()
884
+ if (typeof EventSource === 'undefined') return
885
+ source = new EventSource(`${API}/events`)
886
+ source.addEventListener('console', message => {
887
+ let frame = null
888
+ try {
889
+ frame = JSON.parse(message.data)
890
+ } catch {
891
+ return
892
+ }
893
+ patch(current => applyFrame(current, frame))
894
+ if (frame?.type === 'session' || frame?.type === 'runs') loadSessions()
895
+ })
896
+ source.onopen = () => patch(current => ({ ...current, conn: 'live' }))
897
+ source.onerror = () => patch(current => ({ ...current, conn: 'warn' }))
182
898
  }
183
- load()
899
+ open()
184
900
  return () => {
185
901
  alive = false
186
- if (timer) clearTimeout(timer)
902
+ source?.close()
187
903
  }
188
904
  }, [attempt])
189
905
 
190
- let frame = null
191
- // The shell can switch appearance while the panel is open; hand the new
192
- // theme to the page instead of reloading it (a reload would drop the
193
- // conversation the page is showing).
906
+ // Keep the newest row in view while the answer streams.
907
+ react.useEffect(() => {
908
+ const node = scrollRef.current
909
+ if (node) node.scrollTop = node.scrollHeight
910
+ }, [model.messages.length, model.typing])
911
+
912
+ // A notice clears itself; errors do not stack up.
194
913
  react.useEffect(() => {
195
- const push = () => {
914
+ if (!model.toast) return undefined
915
+ const timer = setTimeout(() => patch(current => ({ ...current, toast: null })), 6000)
916
+ return () => clearTimeout(timer)
917
+ }, [model.toast])
918
+
919
+ const actions = {
920
+ send: async action => {
921
+ const text = String(action.text ?? '')
922
+ const sessionId = modelRef.current.sessionId
923
+ localSeq += 1
924
+ const id = `user-local-${localSeq}`
925
+ patch(current => ({
926
+ ...current,
927
+ sending: true,
928
+ typing: true,
929
+ messages: [...current.messages, { id, role: 'user', text, at: Date.now(), pending: true }],
930
+ }))
196
931
  try {
197
- frame?.contentWindow?.postMessage({ type: 'dsh-superagent-theme', theme: shellTheme() }, '*')
198
- } catch {
199
- // The frame may be gone between renders; the next mount re-reads it.
932
+ await call('/message', {
933
+ method: 'POST',
934
+ body: JSON.stringify({ text, mode: modelRef.current.mode ?? 'queue', sessionId }),
935
+ })
936
+ } catch (error) {
937
+ patch(current => ({
938
+ ...current,
939
+ sending: false,
940
+ typing: false,
941
+ messages: current.messages.filter(message => message.id !== id),
942
+ }))
943
+ throw error
200
944
  }
201
- }
202
- push()
203
- if (typeof MutationObserver === 'undefined' || typeof document === 'undefined' || !document.body) return
204
- const observer = new MutationObserver(push)
205
- observer.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme'] })
206
- return () => observer.disconnect()
207
- }, [view.phase, attempt])
945
+ patch(current => ({ ...current, sending: false }))
946
+ },
947
+ decide: async action => {
948
+ const { id, decision } = action
949
+ patch(current => ({ ...current, approvalBusy: { ...current.approvalBusy, [id]: true } }))
950
+ try {
951
+ await call('/approval', { method: 'POST', body: JSON.stringify({ id, decision }) })
952
+ patch(current => ({
953
+ ...current,
954
+ approvals: current.approvals.filter(entry => entry.id !== id),
955
+ approvalBusy: omitKey(current.approvalBusy, id),
956
+ }))
957
+ } catch (error) {
958
+ // The card stays and the failure surfaces instead of vanishing.
959
+ patch(current => ({ ...current, approvalBusy: omitKey(current.approvalBusy, id) }))
960
+ throw error
961
+ }
962
+ },
963
+ cancel: async () => {
964
+ patch(current => ({ ...current, canceling: true }))
965
+ try {
966
+ await call('/cancel', { method: 'POST', body: JSON.stringify({ sessionId: modelRef.current.sessionId }) })
967
+ } catch (error) {
968
+ patch(current => ({ ...current, canceling: false }))
969
+ throw error
970
+ }
971
+ },
972
+ switch: async action => {
973
+ const { sessionId } = action
974
+ if (!sessionId || sessionId === modelRef.current.sessionId) return
975
+ await call('/session/switch', { method: 'POST', body: JSON.stringify({ sessionId }) })
976
+ patch(current => ({ ...current, phase: 'loading', messages: [], approvals: [], currentId: null, typing: false }))
977
+ setAttempt(value => value + 1)
978
+ },
979
+ 'new-session': async () => {
980
+ await call('/session', { method: 'POST', body: JSON.stringify({}) })
981
+ patch(current => ({ ...current, phase: 'loading', messages: [], approvals: [], currentId: null, typing: false }))
982
+ setAttempt(value => value + 1)
983
+ },
984
+ refresh: () => {
985
+ patch(current => ({ ...current, phase: 'loading' }))
986
+ setAttempt(value => value + 1)
987
+ },
988
+ retry: () => {
989
+ patch(current => ({ ...current, phase: 'loading', reason: '' }))
990
+ setAttempt(value => value + 1)
991
+ },
992
+ mode: action => patch(current => ({ ...current, mode: action.mode })),
993
+ toast: action => patch(current => ({ ...current, toast: { kind: 'err', text: String(action.text ?? '') } })),
994
+ }
208
995
 
209
- const children = []
210
- if (view.phase === 'ready') {
211
- children.push(h('iframe', {
212
- key: 'frame',
213
- ref: element => {
214
- frame = element
215
- },
216
- src: view.src,
217
- title: 'Superagent 专属空间',
218
- style: frameStyle,
219
- allow: 'clipboard-write',
220
- }))
221
- } else if (view.phase === 'loading') {
222
- children.push(h('div', { key: 'note', className: 'dsh-superagent-note' }, '正在连接 Superagent 专属空间…'))
223
- } else {
224
- children.push(h(
225
- 'div',
226
- { key: 'note', className: 'dsh-superagent-note' },
227
- h('div', null, view.reason),
228
- h('div', { className: 'dsh-superagent-note-hint' }, '在「高级」里确认控制台端口已开启(consolePort),或重试。'),
229
- h('button', {
230
- className: 'dsh-superagent-retry',
231
- type: 'button',
232
- onClick: () => setAttempt(n => n + 1),
233
- }, '重试'),
234
- ))
996
+ const dispatch = action => {
997
+ // The shell must survive a failed action: show it, never throw.
998
+ const run = actions[action.type]
999
+ if (!run) return
1000
+ Promise.resolve(run(action)).catch(error => {
1001
+ patch(current => ({
1002
+ ...current,
1003
+ reason: error.message,
1004
+ hint: error.hint ?? '',
1005
+ toast: { kind: 'err', text: `${error.message}${error.hint ? ` ${error.hint}` : ''}` },
1006
+ phase: current.phase === 'loading' ? 'error' : current.phase,
1007
+ }))
1008
+ })
235
1009
  }
236
- return h('div', { style: seatStyle }, children)
1010
+
1011
+ return h(Seat, { model: { ...model, scrollRef }, dispatch })
1012
+ }
1013
+
1014
+ /**
1015
+ * The sidebar row's glyph. The host draws the row itself, so only the mark
1016
+ * belongs to this module; it uses the shell's icon set for the same reason
1017
+ * the panel does.
1018
+ */
1019
+ function EntryIcon(props) {
1020
+ const size = typeof props?.size === 'number' ? props.size : 16
1021
+ const host = ICONS.spark
1022
+ if (typeof host === 'function') return h(host, { size })
1023
+ return h('svg', {
1024
+ viewBox: '0 0 16 16',
1025
+ width: size,
1026
+ height: size,
1027
+ fill: 'none',
1028
+ stroke: 'currentColor',
1029
+ strokeWidth: 1.4,
1030
+ strokeLinecap: 'round',
1031
+ strokeLinejoin: 'round',
1032
+ 'aria-hidden': 'true',
1033
+ }, h('path', { d: 'M8 1.6l1.7 4.7L14.4 8l-4.7 1.7L8 14.4 6.3 9.7 1.6 8l4.7-1.7z' }))
237
1034
  }
238
1035
 
239
1036
  /** @param {object} ctx - client root context. */
240
1037
  function apply(ctx) {
241
1038
  try {
242
1039
  if (!h) return
243
- ensureSeatStyle()
1040
+ ensureStyle()
244
1041
  ctx.slots.inject('main', () => ctx.slots.register(
245
1042
  { name: 'main', key: PANEL_ID },
246
- ConsoleSurface,
1043
+ Panel,
247
1044
  ))
248
1045
  ctx.slots.inject('sidebar.panellist', () => ctx.slots.register(
249
1046
  {
@@ -260,10 +1057,9 @@ window.__ModuleLoader__.load({
260
1057
  }
261
1058
  }
262
1059
 
263
- let inject = ['slots']
264
1060
  try {
265
1061
  exports.apply = apply
266
- exports.inject = inject
1062
+ exports.inject = ['slots']
267
1063
  } catch (error) {
268
1064
  console.error('[dsh-superagent] client exports could not be published', error)
269
1065
  }