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