@user-mrz/dsh-system-prompt-studio 0.0.0-stage → 0.1.5

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 ADDED
@@ -0,0 +1,1078 @@
1
+ // dsh-system-prompt-studio — Client 半(Web / 桌面壳共用同一份)。
2
+ //
3
+ // 契约:client-module 扫描器打包 `exports["./client"]`,页面在
4
+ // `window.__ModuleLoader__` 下求值。factory 拿到一个 `require`,返回带
5
+ // `inject` 与 `apply` 的对象。
6
+ //
7
+ // 三个注册点:
8
+ // 1. `conversation.session.header.actions` —— 标题栏入口按钮(已发过消息的对话);
9
+ // 2. `conversation.hero.options` —— 新空会话欢迎区的入口。空会话是官方的
10
+ // hero 态,标题栏整行带 `hideChrome`,`header.actions` 根本不渲染,
11
+ // 只有这个槽在 hero 态存在。缺了它,「只给这个新对话设覆盖」就没有入口。
12
+ // 3. 弹层本身用 react-dom 的 createPortal 挂到 document.body —— 该槽的
13
+ // 说明写明「溢出会被裁剪,弹层必须 portal」,所以不在槽内直接撑开。
14
+ //
15
+ // 数据全部来自 Host 半的回环路由(`api/system-prompt-studio`,文档相对路径,
16
+ // Web 与桌面壳都会走同源转发)。
17
+
18
+ window.__ModuleLoader__.load({
19
+ id: 'dsh-system-prompt-studio',
20
+ factory: (require) => {
21
+ const React = require('react')
22
+ const ReactDOM = require('react-dom')
23
+ const h = React.createElement
24
+
25
+ const inject = ['slots']
26
+
27
+ const API_PATH = 'api/system-prompt-studio'
28
+ const FALLBACK_HOST = 'http://127.0.0.1:3080'
29
+ const STYLE_ID = 'dsh-system-prompt-studio'
30
+
31
+ // ── 文案(内建中文/英文;有 locale 服务时再叠加注册) ────────────────
32
+ const TEXT = {
33
+ zh: {
34
+ action: '系统提示词',
35
+ actionNew: '设置系统提示词',
36
+ newConversationNote: '这个对话还没发过消息,但 agent 已经在了:现在保存,第一句话就带着这段提示词生效。',
37
+ title: '系统提示词',
38
+ subtitle: '按对话覆盖模型实际收到的系统提示词',
39
+ close: '关闭',
40
+ scopeSession: '本对话',
41
+ scopeGlobal: '全局默认',
42
+ scopeGlobalHint: '所有没有自身覆盖的顶层对话都套用(不含子代理)。',
43
+ modeAppend: '追加到末尾',
44
+ modeAppendHint: '保留第一方全部提示词,只在末尾追加你的段落。',
45
+ modeReplace: '替换指定段',
46
+ modeReplaceHint: '用同名段影子覆盖第一方段落;段名从下面的实测清单里选。',
47
+ modeComplete: '完全替换',
48
+ modeCompleteHint: '只发你写的内容。第一方的工具使用说明、结构化输出指引等提示词全部消失,可能明显影响工具调用质量。',
49
+ modeCompleteRisk: '运行时上下文(工作目录 / 沙箱 / 审批策略)仍会随请求发送,不会被这段替换。',
50
+ modeCompleteAck: '我已了解:这会丢掉第一方全部提示词',
51
+ target: '目标段',
52
+ targetHint: '该对话跑过请求后,下拉框就是真实段名;手动填不存在的段名会变成新增段。',
53
+ body: '正文',
54
+ bodyHint: '{{…}} 会原样保留,不会被当作变量插值。',
55
+ chars: '字符',
56
+ enable: '在本对话启用覆盖',
57
+ save: '保存',
58
+ clear: '清除覆盖',
59
+ saving: '保存中…',
60
+ saved: '已保存,本对话下一次模型请求生效。',
61
+ savedLocal: '已保存到内存,但写入磁盘失败,重启后会丢失。',
62
+ cleared: '已清除覆盖。',
63
+ current: '最近一次请求的系统提示词',
64
+ currentEmpty: '(还没有可读的系统提示词)',
65
+ copy: '复制',
66
+ copied: '已复制',
67
+ sections: '本对话装配到的段',
68
+ sectionsStaleNote: '这份清单来自上一次模型请求,早于你刚才的保存。发一条消息后再打开,就能看到新结果。',
69
+ sectionsCompleteNote: '当前是「完全替换」模式:上面这份清单是替换前的全量段,实际发送时只会保留 studio:complete 一个段。',
70
+ sectionName: '段名',
71
+ sectionOrder: '顺序',
72
+ sectionChars: '字符',
73
+ refresh: '刷新',
74
+ loading: '读取中…',
75
+ disabledNoService: '当前 profile 没有装配 systemPrompt 服务,覆盖无法生效。',
76
+ disabledNoAgents: '当前 profile 没有 agents 服务,覆盖无法挂到对话上。',
77
+ disabledOff: '插件在配置里被停用了(enabled: false)。',
78
+ completeBlocked: '配置里 allowComplete=false,完全替换模式被禁用。',
79
+ fetchFailed: '读取失败:',
80
+ saveFailed: '保存失败:',
81
+ prefixCache: '提示:系统提示词一变,该对话的缓存前缀会从首个变化的 token 起失效,下一次请求按新前缀计费。',
82
+ inherited: '该对话当前没有自身覆盖,正在使用全局默认。',
83
+ inheritedFrom: '当前规则继承自:',
84
+ inheritedNone: '该对话是从别的对话分叉出来的,但上游没有可继承的规则。',
85
+ pin: '在此固定',
86
+ pinned: '已固定为本对话自己的规则,之后上游再改也不影响这里。',
87
+ discardTitle: '放弃未保存的修改?',
88
+ discardBody: '你有改动还没保存。关闭面板会丢掉这些改动——它们不会被写入任何地方。',
89
+ discardKeep: '继续编辑',
90
+ discardConfirm: '放弃并关闭',
91
+ emptyText: '启用覆盖但正文为空,请填写正文。',
92
+ targetRequired: '替换模式必须填写目标段名。',
93
+ subagentNote: '子代理会话默认不继承全局默认。',
94
+ },
95
+ en: {
96
+ action: 'System prompt',
97
+ actionNew: 'Set system prompt',
98
+ newConversationNote: 'This conversation has not sent a message yet, but its agent already exists: saving now applies the prompt from the very first message.',
99
+ title: 'System prompt',
100
+ subtitle: 'Override the system prompt this conversation actually sends',
101
+ close: 'Close',
102
+ scopeSession: 'This conversation',
103
+ scopeGlobal: 'Global default',
104
+ scopeGlobalHint: 'Applied to every top-level conversation without an override of its own (not subagents).',
105
+ modeAppend: 'Append',
106
+ modeAppendHint: 'Keep every first-party section and add yours at the end.',
107
+ modeReplace: 'Replace a section',
108
+ modeReplaceHint: 'Shadow one first-party section by name; pick a real name from the list below.',
109
+ modeComplete: 'Replace everything',
110
+ modeCompleteHint: 'Only your text is sent. First-party guidance such as tool instructions and structured-output rules disappears, which can degrade tool use.',
111
+ modeCompleteRisk: 'Runtime context (working directory, sandbox, approval policy) is still sent as a user-side snapshot.',
112
+ modeCompleteAck: 'I understand this drops every first-party prompt.',
113
+ target: 'Target section',
114
+ targetHint: 'After this conversation has run a request, the list holds real section names.',
115
+ body: 'Body',
116
+ bodyHint: '{{…}} is kept literally and is not interpolated.',
117
+ chars: 'chars',
118
+ enable: 'Enable override for this conversation',
119
+ save: 'Save',
120
+ clear: 'Clear override',
121
+ saving: 'Saving…',
122
+ saved: 'Saved. It applies to this conversation on its next model request.',
123
+ savedLocal: 'Saved in memory only: the file write failed, so it will be lost on restart.',
124
+ cleared: 'Override cleared.',
125
+ current: 'System prompt of the latest request',
126
+ currentEmpty: '(nothing readable yet)',
127
+ copy: 'Copy',
128
+ copied: 'Copied',
129
+ sections: 'Sections assembled for this conversation',
130
+ sectionsStaleNote: 'This list is from the previous model request, before your last save. Send a message and reopen to see the new result.',
131
+ sectionsCompleteNote: 'Replace-everything is active: the list above is the full pre-replacement set. Only studio:complete is actually sent.',
132
+ sectionName: 'Section',
133
+ sectionOrder: 'Order',
134
+ sectionChars: 'Chars',
135
+ refresh: 'Refresh',
136
+ loading: 'Loading…',
137
+ disabledNoService: 'This profile has no systemPrompt service, so overrides cannot take effect.',
138
+ disabledNoAgents: 'This profile has no agents service, so overrides cannot attach to a conversation.',
139
+ disabledOff: 'The plugin is disabled in its configuration (enabled: false).',
140
+ completeBlocked: 'allowComplete=false in the configuration, so Replace everything is unavailable.',
141
+ fetchFailed: 'Load failed: ',
142
+ saveFailed: 'Save failed: ',
143
+ prefixCache: 'Note: changing the system prompt invalidates this conversation\'s cached prefix from the first changed token.',
144
+ inherited: 'This conversation has no override of its own and is using the global default.',
145
+ inheritedFrom: 'Current rules inherited from: ',
146
+ inheritedNone: 'This conversation was forked, but the upstream conversation has no rules to inherit.',
147
+ pin: 'Pin here',
148
+ pinned: 'Pinned as this conversation\'s own rules; later upstream changes will not affect it.',
149
+ discardTitle: 'Discard unsaved changes?',
150
+ discardBody: 'You have edits that have not been saved. Closing the panel discards them — they will not be written anywhere.',
151
+ discardKeep: 'Keep editing',
152
+ discardConfirm: 'Discard and close',
153
+ emptyText: 'The override is enabled but the body is empty.',
154
+ targetRequired: 'Replace mode needs a target section name.',
155
+ subagentNote: 'Subagent conversations do not inherit the global default.',
156
+ },
157
+ }
158
+
159
+ /** 极简取词:默认中文,页面语言为 en 时用英文。 */
160
+ function makeText(ctx) {
161
+ let lang = 'zh'
162
+ try {
163
+ const snapshot = ctx.get?.('locale')?.getLocale?.()
164
+ const id = snapshot?.id ?? snapshot?.locale ?? ''
165
+ if (typeof id === 'string' && id.toLowerCase().startsWith('en')) lang = 'en'
166
+ } catch {
167
+ lang = 'zh'
168
+ }
169
+ const table = TEXT[lang] ?? TEXT.zh
170
+ return (key) => table[key] ?? TEXT.zh[key] ?? key
171
+ }
172
+
173
+ /** API 基址候选:文档相对 → 显式 hostURL → 页面 origin → 127.0.0.1:3080。 */
174
+ function baseCandidates(hostURL) {
175
+ const list = ['']
176
+ const push = (value) => {
177
+ if (typeof value !== 'string') return
178
+ const trimmed = value.replace(/\/+$/u, '')
179
+ if (trimmed !== '' && !list.includes(trimmed)) list.push(trimmed)
180
+ }
181
+ push(hostURL)
182
+ try {
183
+ const origin = globalThis.location?.origin
184
+ if (typeof origin === 'string' && origin !== '' && origin !== 'null') push(origin)
185
+ } catch {
186
+ /* 没有 location 的壳 */
187
+ }
188
+ push(FALLBACK_HOST)
189
+ return list
190
+ }
191
+
192
+ function createApi(config) {
193
+ const bases = baseCandidates(config.hostURL)
194
+ let active = null
195
+
196
+ const urlFor = (base, sessionId) => {
197
+ const query = sessionId === '' ? '' : `?session=${encodeURIComponent(sessionId)}`
198
+ return `${base === '' ? '' : `${base}/`}${API_PATH}${query}`
199
+ }
200
+
201
+ async function attempt(method, sessionId, body) {
202
+ const order = active === null ? bases : [active, ...bases.filter((base) => base !== active)]
203
+ let lastError = null
204
+ for (const base of order) {
205
+ try {
206
+ const response = await fetch(urlFor(base, sessionId), {
207
+ method,
208
+ cache: 'no-store',
209
+ headers: body === undefined ? undefined : { 'content-type': 'application/json' },
210
+ body: body === undefined ? undefined : JSON.stringify(body),
211
+ })
212
+ const text = await response.text()
213
+ let payload
214
+ try {
215
+ payload = text === '' ? {} : JSON.parse(text)
216
+ } catch {
217
+ throw new Error(`HTTP ${response.status}(响应不是 JSON)`)
218
+ }
219
+ if (!response.ok) {
220
+ const reason = payload?.message ?? payload?.error ?? `HTTP ${response.status}`
221
+ const error = new Error(reason)
222
+ error.status = response.status
223
+ error.payload = payload
224
+ throw error
225
+ }
226
+ active = base
227
+ return payload
228
+ } catch (error) {
229
+ lastError = error
230
+ }
231
+ }
232
+ throw lastError ?? new Error('no-reachable-host')
233
+ }
234
+
235
+ return {
236
+ load: (sessionId) => attempt('GET', sessionId, undefined),
237
+ save: (body) => attempt('POST', '', body),
238
+ }
239
+ }
240
+
241
+ // ── 样式:只用 --dsw-alias-* 主题令牌 ────────────────────────────────
242
+ const CSS = `
243
+ [data-sps="backdrop"]{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;padding:24px;background:color-mix(in srgb, var(--dsw-alias-bg-base) 62%, transparent);backdrop-filter:blur(3px)}
244
+ [data-sps="dialog"]{display:flex;flex-direction:column;width:min(920px,100%);max-height:min(86vh,900px);border-radius:14px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-overlay);color:var(--dsw-alias-label-primary);box-shadow:0 24px 64px rgba(0,0,0,.32);font-size:13px;overflow:hidden}
245
+ [data-sps="head"]{display:flex;align-items:flex-start;gap:12px;padding:16px 18px 12px;border-bottom:1px solid var(--dsw-alias-border-l1)}
246
+ [data-sps="headmain"]{flex:1;min-width:0}
247
+ [data-sps="title"]{font-size:15px;font-weight:600;line-height:1.3}
248
+ [data-sps="subtitle"]{margin-top:3px;font-size:12px;color:var(--dsw-alias-label-secondary);word-break:break-all}
249
+ [data-sps="close"]{appearance:none;border:0;background:none;color:var(--dsw-alias-label-secondary);cursor:pointer;font:16px/1 monospace;padding:4px 8px;border-radius:6px}
250
+ [data-sps="close"]:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2)}
251
+ [data-sps="body"]{padding:14px 18px 18px;overflow:auto;display:flex;flex-direction:column;gap:14px}
252
+ [data-sps="row"]{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
253
+ [data-sps="tabs"]{display:inline-flex;padding:3px;border-radius:9px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1)}
254
+ [data-sps="tab"]{appearance:none;border:0;background:none;color:var(--dsw-alias-label-secondary);cursor:pointer;font-size:12px;padding:5px 12px;border-radius:7px}
255
+ [data-sps="tab"][data-on="true"]{background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-weight:600}
256
+ [data-sps="mode"]{display:flex;flex-direction:column;gap:8px}
257
+ [data-sps="radio"]{display:flex;gap:9px;align-items:flex-start;padding:9px 11px;border-radius:10px;border:1px solid var(--dsw-alias-border-l1);cursor:pointer}
258
+ [data-sps="radio"][data-on="true"]{border-color:var(--dsw-alias-brand-primary)}
259
+ [data-sps="radio"][data-risk="true"][data-on="true"]{border-color:var(--dsw-alias-state-error-primary)}
260
+ [data-sps="radio"] input{margin:3px 0 0}
261
+ [data-sps="radiomain"]{flex:1;min-width:0}
262
+ [data-sps="radiokey"]{font-weight:600}
263
+ [data-sps="radiosub"]{margin-top:2px;font-size:12px;color:var(--dsw-alias-label-secondary)}
264
+ [data-sps="warn"]{padding:9px 11px;border-radius:9px;border:1px solid var(--dsw-alias-state-warn-primary);background:color-mix(in srgb, var(--dsw-alias-state-warn-primary) 12%, transparent);font-size:12px;line-height:1.5}
265
+ [data-sps="error"]{padding:9px 11px;border-radius:9px;border:1px solid var(--dsw-alias-state-error-primary);background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent);font-size:12px;line-height:1.5;white-space:pre-wrap}
266
+ [data-sps="ok"]{padding:9px 11px;border-radius:9px;border:1px solid var(--dsw-alias-state-success-primary);background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 12%, transparent);font-size:12px}
267
+ [data-sps="muted"]{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:1.5}
268
+ [data-sps="label"]{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary);letter-spacing:.02em}
269
+ [data-sps="input"],[data-sps="textarea"]{width:100%;box-sizing:border-box;border-radius:9px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;padding:8px 10px}
270
+ [data-sps="textarea"]{min-height:200px;resize:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;line-height:1.6}
271
+ [data-sps="input"]:focus,[data-sps="textarea"]:focus{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
272
+ [data-sps="foot"]{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
273
+ [data-sps="spacer"]{flex:1}
274
+ [data-sps="button"]{appearance:none;cursor:pointer;font:inherit;font-size:12px;padding:7px 14px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}
275
+ [data-sps="button"]:hover{border-color:var(--dsw-alias-brand-primary)}
276
+ [data-sps="button"][data-primary="true"]{background:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-bg-base);font-weight:600}
277
+ [data-sps="button"]:disabled{opacity:.55;cursor:not-allowed}
278
+ [data-sps="details"]{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;padding:10px 12px}
279
+ [data-sps="details"] summary{cursor:pointer;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}
280
+ [data-sps="pre"]{margin:8px 0 0;max-height:220px;overflow:auto;white-space:pre-wrap;word-break:break-word;font:12px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:var(--dsw-alias-label-primary)}
281
+ [data-sps="table"]{width:100%;border-collapse:collapse;margin-top:8px;font-size:12px}
282
+ [data-sps="table"] th,[data-sps="table"] td{text-align:left;padding:4px 8px;border-bottom:1px solid var(--dsw-alias-border-l1);font-weight:400}
283
+ [data-sps="table"] th{color:var(--dsw-alias-label-secondary);font-weight:600}
284
+ [data-sps="table"] td[data-num="true"]{text-align:right;font-variant-numeric:tabular-nums}
285
+ [data-sps="entry"]{display:inline-flex;align-items:center;gap:6px;appearance:none;border:1px solid transparent;background:none;color:var(--dsw-alias-label-secondary);cursor:pointer;font:inherit;font-size:12px;padding:4px 8px;border-radius:7px;max-width:220px}
286
+ [data-sps="entry"]:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2)}
287
+ [data-sps="entry"][data-on="true"]{color:var(--dsw-alias-label-primary)}
288
+ [data-sps="entry"][data-variant="hero"]{border-color:var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);border-radius:999px;padding:5px 12px;font-weight:500;gap:7px}
289
+ [data-sps="entry"][data-variant="hero"]:hover{border-color:var(--dsw-alias-brand-primary)}
290
+ [data-sps="entry"][data-variant="hero"]:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
291
+ [data-sps="dot"]{width:6px;height:6px;border-radius:50%;flex:none;background:var(--dsw-alias-brand-primary)}
292
+ [data-sps="entrylabel"]{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
293
+ `
294
+
295
+ function ensureStyle() {
296
+ if (typeof document === 'undefined') return () => {}
297
+ const existing = document.querySelector(`style[data-plugin="${STYLE_ID}"]`)
298
+ if (existing !== null) return () => {}
299
+ const tag = document.createElement('style')
300
+ tag.dataset.plugin = STYLE_ID
301
+ tag.textContent = CSS
302
+ document.head.appendChild(tag)
303
+ return () => {
304
+ try {
305
+ tag.remove()
306
+ } catch {
307
+ /* 已被移除 */
308
+ }
309
+ }
310
+ }
311
+
312
+ function Icon({ size = 16 }) {
313
+ return h(
314
+ 'svg',
315
+ { viewBox: '0 0 24 24', width: size, height: size, 'aria-hidden': true, style: { display: 'block', flex: 'none' } },
316
+ h('rect', { x: 2.5, y: 4, width: 19, height: 13, rx: 3.4, fill: 'currentColor', opacity: 0.22 }),
317
+ h('rect', { x: 2.5, y: 4, width: 19, height: 13, rx: 3.4, fill: 'none', stroke: 'currentColor', strokeWidth: 1.6 }),
318
+ h('path', { d: 'M7 17.4h6l-3.2 3.6z', fill: 'currentColor', opacity: 0.55 }),
319
+ h('circle', { cx: 8, cy: 9.4, r: 1.35, fill: 'currentColor' }),
320
+ h('rect', { x: 11, y: 8.4, width: 7.5, height: 2, rx: 1, fill: 'currentColor' }),
321
+ h('circle', { cx: 8, cy: 13, r: 1.35, fill: 'currentColor' }),
322
+ h('rect', { x: 11, y: 12, width: 4.8, height: 2, rx: 1, fill: 'currentColor' }),
323
+ )
324
+ }
325
+
326
+ /**
327
+ * 入口按钮。两个注册点复用同一个组件,只靠 variant 区分外观与文案:
328
+ *
329
+ * - header:已发过消息的对话,标题栏里的小图标,绿点表示该对话已有自身覆盖;
330
+ * - hero:新空会话的欢迎区,带文字的胶囊按钮——那里空间足够,且「能不能
331
+ * 给一个还没开口的新对话设提示词」正是用户会在这一刻问的问题,图标太隐晦。
332
+ *
333
+ * 两种 variant 的 sessionId 都由槽注入,所以「只改这一个新对话」在 hero 态
334
+ * 也是成立的:会话一创建 agent 就已经在了,保存后第一句话就带着这段提示词。
335
+ */
336
+ function makeEntry(variant) {
337
+ return function Entry(props, helpers) {
338
+ const { t, api, config } = helpers
339
+ const sessionId = typeof props?.sessionId === 'string' ? props.sessionId : ''
340
+ const [open, setOpen] = React.useState(false)
341
+ const [own, setOwn] = React.useState(false)
342
+
343
+ React.useEffect(() => {
344
+ if (sessionId === '') return undefined
345
+ let cancelled = false
346
+ api
347
+ .load(sessionId)
348
+ .then((payload) => {
349
+ if (cancelled) return
350
+ const entry = payload?.session
351
+ setOwn(entry !== null && entry !== undefined && entry.enabled === true)
352
+ })
353
+ .catch(() => {
354
+ /* 读不到就不显示指示点,入口本身仍然可用 */
355
+ })
356
+ return () => {
357
+ cancelled = true
358
+ }
359
+ }, [api, sessionId, open])
360
+
361
+ const hero = variant === 'hero'
362
+ const label = hero ? t('actionNew') : t('action')
363
+ const showLabel = hero || config.showLabel === true
364
+
365
+ return h(
366
+ React.Fragment,
367
+ null,
368
+ h(
369
+ 'button',
370
+ {
371
+ type: 'button',
372
+ 'data-sps': 'entry',
373
+ 'data-variant': variant,
374
+ 'data-on': open ? 'true' : 'false',
375
+ title: t('action'),
376
+ 'aria-label': label,
377
+ onClick: () => setOpen(true),
378
+ },
379
+ h(Icon, { size: hero ? 14 : 15 }),
380
+ own ? h('span', { 'data-sps': 'dot' }) : null,
381
+ showLabel ? h('span', { 'data-sps': 'entrylabel' }, label) : null,
382
+ ),
383
+ open ? h(Dialog, { sessionId, onClose: () => setOpen(false), t, api, variant }) : null,
384
+ )
385
+ }
386
+ }
387
+
388
+ const HeaderAction = makeEntry('header')
389
+ const HeroAction = makeEntry('hero')
390
+
391
+ /** 会话 id 太长,界面上只显示尾部一段,够区分又不会撑破布局。 */
392
+ function shortId(id) {
393
+ const text = typeof id === 'string' ? id : ''
394
+ if (text.length <= 16) return text || '—'
395
+ return `…${text.slice(-12)}`
396
+ }
397
+
398
+ /**
399
+ * 时间戳只显示时分秒。
400
+ *
401
+ * 段清单是「最近一次装配」,通常就在几分钟内,日期是噪音;跨天的旧清单
402
+ * 靠「保存前的清单」这条提示兜底,不需要日期也能理解。
403
+ */
404
+ function formatClock(ts) {
405
+ try {
406
+ const date = new Date(ts)
407
+ const pad = (n) => String(n).padStart(2, '0')
408
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
409
+ } catch {
410
+ return ''
411
+ }
412
+ }
413
+
414
+ function Dialog({ sessionId, onClose, t, api, variant }) {
415
+ const [status, setStatus] = React.useState({ phase: 'loading', payload: null, error: '' })
416
+ const [scope, setScope] = React.useState('session')
417
+ const [mode, setMode] = React.useState('append')
418
+ const [text, setText] = React.useState('')
419
+ const [target, setTarget] = React.useState('')
420
+ const [enabled, setEnabled] = React.useState(true)
421
+ const [ack, setAck] = React.useState(false)
422
+ const [busy, setBusy] = React.useState(false)
423
+ const [notice, setNotice] = React.useState({ kind: '', text: '' })
424
+ /**
425
+ * 未保存改动的保护。
426
+ *
427
+ * `baseline` 记下「上一次从服务端载入/成功保存之后」的形态;`dirty` 由它
428
+ * 现算而不是单独维护一个布尔——这样「改了又改回去」不会误报未保存,
429
+ * 也不会漏报(比如只切了模式、只动了一个勾选框)。
430
+ */
431
+ const [baseline, setBaseline] = React.useState({ mode: 'append', text: '', target: '', enabled: true })
432
+ const [confirmClose, setConfirmClose] = React.useState(false)
433
+ const textareaRef = React.useRef(null)
434
+ const backdropRef = React.useRef(null)
435
+
436
+ const captureBaseline = React.useCallback((payload, which) => {
437
+ const entry = which === 'global' ? payload?.global : payload?.session
438
+ return {
439
+ mode: entry !== null && entry !== undefined && typeof entry.mode === 'string' ? entry.mode : 'append',
440
+ text: entry !== null && entry !== undefined && typeof entry.text === 'string' ? entry.text : '',
441
+ target:
442
+ entry !== null && entry !== undefined && typeof entry.target === 'string' && entry.target !== ''
443
+ ? entry.target
444
+ : payload?.defaultTargetName ?? '',
445
+ enabled: entry !== null && entry !== undefined && typeof entry.enabled === 'boolean' ? entry.enabled : true,
446
+ }
447
+ }, [])
448
+
449
+ const applyPayload = React.useCallback(
450
+ (payload, which) => {
451
+ const next = captureBaseline(payload, which)
452
+ setMode(next.mode)
453
+ setText(next.text)
454
+ setTarget(next.target)
455
+ setEnabled(next.enabled)
456
+ setAck(false)
457
+ setBaseline(next)
458
+ },
459
+ [captureBaseline],
460
+ )
461
+
462
+ const reload = React.useCallback(
463
+ async (which) => {
464
+ setStatus((prev) => ({ ...prev, phase: 'loading', error: '' }))
465
+ try {
466
+ const payload = await api.load(sessionId)
467
+ setStatus({ phase: 'ready', payload, error: '' })
468
+ applyPayload(payload, which)
469
+ } catch (error) {
470
+ setStatus({ phase: 'failed', payload: null, error: String(error?.message ?? error) })
471
+ }
472
+ },
473
+ [api, sessionId, applyPayload],
474
+ )
475
+
476
+ React.useEffect(() => {
477
+ reload('session')
478
+ }, [reload])
479
+
480
+ // 未保存判定:四个用户可编辑的字段逐一对比基线。
481
+ const dirty =
482
+ mode !== baseline.mode || text !== baseline.text || target !== baseline.target || enabled !== baseline.enabled
483
+
484
+ /**
485
+ * 关闭请求的统一入口。
486
+ *
487
+ * 有未保存改动时先转为「确认」态,不直接关——用户写了几百字被一次误触
488
+ * 的 Esc 或遮罩点击清掉,是这个面板最容易造成实际损失的地方。
489
+ */
490
+ const requestClose = React.useCallback(() => {
491
+ if (dirty) {
492
+ setConfirmClose(true)
493
+ return
494
+ }
495
+ onClose()
496
+ }, [dirty, onClose])
497
+
498
+ const confirmDiscard = React.useCallback(() => {
499
+ setConfirmClose(false)
500
+ onClose()
501
+ }, [onClose])
502
+
503
+ const cancelDiscard = React.useCallback(() => {
504
+ setConfirmClose(false)
505
+ // 回到编辑态后把焦点还给正文,用户能接着写。
506
+ try {
507
+ textareaRef.current?.focus?.()
508
+ } catch {
509
+ /* 没有可聚焦的节点 */
510
+ }
511
+ }, [])
512
+
513
+ // Esc 关闭 + 打开时聚焦正文。确认态下 Esc 取消放弃,而不是连按就丢。
514
+ React.useEffect(() => {
515
+ const onKey = (event) => {
516
+ if (event.key !== 'Escape') return
517
+ event.stopPropagation()
518
+ if (confirmClose) cancelDiscard()
519
+ else requestClose()
520
+ }
521
+ document.addEventListener('keydown', onKey, true)
522
+ const timer = setTimeout(() => {
523
+ try {
524
+ textareaRef.current?.focus?.()
525
+ } catch {
526
+ /* 没有可聚焦的节点 */
527
+ }
528
+ }, 30)
529
+ return () => {
530
+ document.removeEventListener('keydown', onKey, true)
531
+ clearTimeout(timer)
532
+ }
533
+ }, [confirmClose, cancelDiscard, requestClose])
534
+
535
+ // 关标签页/刷新的兜底:只在有未保存改动时注册。
536
+ React.useEffect(() => {
537
+ if (!dirty) return undefined
538
+ const onBeforeUnload = (event) => {
539
+ event.preventDefault()
540
+ // 部分浏览器只认 returnValue。
541
+ event.returnValue = ''
542
+ return ''
543
+ }
544
+ window.addEventListener('beforeunload', onBeforeUnload)
545
+ return () => {
546
+ window.removeEventListener('beforeunload', onBeforeUnload)
547
+ }
548
+ }, [dirty])
549
+
550
+ const payload = status.payload
551
+ const capability = payload?.capability ?? {}
552
+ const blocked = {
553
+ off: payload !== null && payload !== undefined && capability.enabled === false,
554
+ noService: payload !== null && payload !== undefined && capability.systemPrompt === false,
555
+ noAgents: payload !== null && payload !== undefined && capability.agents === false,
556
+ complete: payload !== null && payload !== undefined && capability.allowComplete === false,
557
+ }
558
+ const sections = Array.isArray(payload?.sections) ? payload.sections : null
559
+ /**
560
+ * 段清单来自哪一次装配。
561
+ *
562
+ * 装配只在模型请求时发生,保存不触发它——所以清单天生滞后一步。把时间戳
563
+ * 摆到标题上,用户一眼就知道「这是 09:40 那次请求的清单」,而不是对着
564
+ * 旧数据猜自己的保存有没有生效。
565
+ */
566
+ const sectionsAt = typeof payload?.sectionsAt === 'number' && payload.sectionsAt > 0 ? payload.sectionsAt : 0
567
+ const sectionsAtText = sectionsAt === 0 ? '' : formatClock(sectionsAt)
568
+ const maxChars = typeof payload?.limits?.maxChars === 'number' ? payload.limits.maxChars : 200000
569
+ const current = payload?.current ?? null
570
+ const ownEntry = payload?.session ?? null
571
+ const inheritFrom = scope === 'session' ? payload?.effective?.inheritedFrom ?? '' : ''
572
+ const disabled = blocked.off || blocked.noService || blocked.noAgents || busy
573
+ const completeOk = !blocked.complete && (mode !== 'complete' || ack)
574
+
575
+ const onSave = async () => {
576
+ if (text.trim() === '' && enabled) {
577
+ setNotice({ kind: 'error', text: t('emptyText') })
578
+ return
579
+ }
580
+ if (mode === 'replace' && target.trim() === '') {
581
+ setNotice({ kind: 'error', text: t('targetRequired') })
582
+ return
583
+ }
584
+ if (mode === 'complete' && !ack) return
585
+ setBusy(true)
586
+ setNotice({ kind: '', text: '' })
587
+ try {
588
+ const body = {
589
+ action: 'set',
590
+ scope,
591
+ sessionId: scope === 'session' ? sessionId : '',
592
+ patch: { enabled, mode, text, target: mode === 'replace' ? target.trim() : '' },
593
+ }
594
+ const result = await api.save(body)
595
+ setStatus({ phase: 'ready', payload: result, error: '' })
596
+ // 保存成功后,当前形态成为新的基线——否则会一直显示「未保存」。
597
+ setBaseline({ mode, text, target, enabled })
598
+ setNotice({
599
+ kind: result?.persisted === false ? 'error' : 'ok',
600
+ text: result?.persisted === false ? t('savedLocal') : t('saved'),
601
+ })
602
+ } catch (error) {
603
+ setNotice({ kind: 'error', text: `${t('saveFailed')}${String(error?.message ?? error)}` })
604
+ } finally {
605
+ setBusy(false)
606
+ }
607
+ }
608
+
609
+ const onClear = async () => {
610
+ setBusy(true)
611
+ setNotice({ kind: '', text: '' })
612
+ try {
613
+ const body = { action: 'clear', scope, sessionId: scope === 'session' ? sessionId : '' }
614
+ const result = await api.save(body)
615
+ setStatus({ phase: 'ready', payload: result, error: '' })
616
+ applyPayload(result, scope)
617
+ setNotice({ kind: 'ok', text: t('cleared') })
618
+ } catch (error) {
619
+ setNotice({ kind: 'error', text: `${t('saveFailed')}${String(error?.message ?? error)}` })
620
+ } finally {
621
+ setBusy(false)
622
+ }
623
+ }
624
+
625
+ const onPin = async () => {
626
+ setBusy(true)
627
+ setNotice({ kind: '', text: '' })
628
+ try {
629
+ const result = await api.save({ action: 'pin', scope: 'session', sessionId })
630
+ setStatus({ phase: 'ready', payload: result, error: '' })
631
+ applyPayload(result, 'session')
632
+ setNotice({ kind: 'ok', text: t('pinned') })
633
+ } catch (error) {
634
+ setNotice({ kind: 'error', text: `${t('saveFailed')}${String(error?.message ?? error)}` })
635
+ } finally {
636
+ setBusy(false)
637
+ }
638
+ }
639
+
640
+ const onCopy = async () => {
641
+ if (current === null) return
642
+ try {
643
+ await navigator.clipboard.writeText(current.text)
644
+ setNotice({ kind: 'ok', text: t('copied') })
645
+ } catch {
646
+ try {
647
+ const range = document.createRange()
648
+ const node = backdropRef.current?.querySelector('[data-sps="pre"]')
649
+ if (node !== null && node !== undefined) {
650
+ range.selectNodeContents(node)
651
+ const selection = window.getSelection()
652
+ selection?.removeAllRanges?.()
653
+ selection?.addRange?.(range)
654
+ }
655
+ setNotice({ kind: '', text: t('copy') })
656
+ } catch {
657
+ /* 复制不可用,保留原文让用户手动选择 */
658
+ }
659
+ }
660
+ }
661
+
662
+ const modeRow = (key, titleKey, hintKey, risky) =>
663
+ h(
664
+ 'label',
665
+ { 'data-sps': 'radio', 'data-on': mode === key ? 'true' : 'false', 'data-risk': risky ? 'true' : 'false' },
666
+ h('input', {
667
+ type: 'radio',
668
+ name: 'sps-mode',
669
+ checked: mode === key,
670
+ disabled: risky && blocked.complete,
671
+ onChange: () => {
672
+ setMode(key)
673
+ if (key !== 'complete') setAck(false)
674
+ },
675
+ }),
676
+ h(
677
+ 'span',
678
+ { 'data-sps': 'radiomain' },
679
+ h('span', { 'data-sps': 'radiokey' }, t(titleKey)),
680
+ h('span', { 'data-sps': 'radiosub' }, t(hintKey)),
681
+ ),
682
+ )
683
+
684
+ const children = [
685
+ h(
686
+ 'div',
687
+ { key: 'head', 'data-sps': 'head' },
688
+ h(
689
+ 'div',
690
+ { 'data-sps': 'headmain' },
691
+ h('div', { 'data-sps': 'title' }, t('title')),
692
+ h('div', { 'data-sps': 'subtitle' }, `${t('subtitle')} · ${sessionId || '—'}`),
693
+ ),
694
+ h('button', { key: 'x', type: 'button', 'data-sps': 'close', title: t('close'), onClick: requestClose }, '✕'),
695
+ ),
696
+ h(
697
+ 'div',
698
+ { key: 'body', 'data-sps': 'body' },
699
+ // 新空会话:明确告诉用户「现在保存就是给这第一句话用」。
700
+ // 不说清楚的话,这里和标题栏入口长得一样、效果却更值得怀疑。
701
+ variant === 'hero' && sessionId !== ''
702
+ ? h('div', { key: 'fresh', 'data-sps': 'ok' }, t('newConversationNote'))
703
+ : null,
704
+ // 能力不足时的说明
705
+ blocked.off ? h('div', { key: 'off', 'data-sps': 'error' }, t('disabledOff')) : null,
706
+ blocked.noService ? h('div', { key: 'nos', 'data-sps': 'error' }, t('disabledNoService')) : null,
707
+ blocked.noAgents ? h('div', { key: 'noa', 'data-sps': 'error' }, t('disabledNoAgents')) : null,
708
+
709
+ // 继承状态:让「我的规则从哪来」可见,而不是静默生效
710
+ inheritFrom !== ''
711
+ ? h(
712
+ 'div',
713
+ { key: 'inherit', 'data-sps': 'warn', style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
714
+ h('span', { style: { flex: 1, minWidth: 200 } }, `${t('inheritedFrom')} ${shortId(inheritFrom)}`),
715
+ h(
716
+ 'button',
717
+ { type: 'button', 'data-sps': 'button', disabled: busy, onClick: onPin },
718
+ t('pin'),
719
+ ),
720
+ )
721
+ : null,
722
+ // 没有自身条目、也没继承,但父会话存在:说明「上层没有可继承的规则」
723
+ inheritFrom === '' && ownEntry === null && payload?.parentSession
724
+ ? h('div', { key: 'inherit-none', 'data-sps': 'muted' }, t('inheritedNone'))
725
+ : null,
726
+
727
+ // 作用域
728
+ h(
729
+ 'div',
730
+ { key: 'scope', 'data-sps': 'row' },
731
+ h(
732
+ 'div',
733
+ { 'data-sps': 'tabs', role: 'tablist' },
734
+ h(
735
+ 'button',
736
+ {
737
+ type: 'button',
738
+ 'data-sps': 'tab',
739
+ 'data-on': scope === 'session' ? 'true' : 'false',
740
+ onClick: () => {
741
+ setScope('session')
742
+ applyPayload(status.payload, 'session')
743
+ },
744
+ },
745
+ t('scopeSession'),
746
+ ),
747
+ h(
748
+ 'button',
749
+ {
750
+ type: 'button',
751
+ 'data-sps': 'tab',
752
+ 'data-on': scope === 'global' ? 'true' : 'false',
753
+ onClick: () => {
754
+ setScope('global')
755
+ applyPayload(status.payload, 'global')
756
+ },
757
+ },
758
+ t('scopeGlobal'),
759
+ ),
760
+ ),
761
+ scope === 'global' ? h('span', { 'data-sps': 'muted' }, t('scopeGlobalHint')) : null,
762
+ ),
763
+
764
+ // 模式
765
+ h(
766
+ 'div',
767
+ { key: 'mode', 'data-sps': 'mode' },
768
+ modeRow('append', 'modeAppend', 'modeAppendHint', false),
769
+ modeRow('replace', 'modeReplace', 'modeReplaceHint', false),
770
+ modeRow('complete', 'modeComplete', 'modeCompleteHint', true),
771
+ ),
772
+
773
+ mode === 'replace'
774
+ ? h(
775
+ 'div',
776
+ { key: 'target', style: { display: 'flex', flexDirection: 'column', gap: 6 } },
777
+ h('span', { 'data-sps': 'label' }, t('target')),
778
+ sections === null
779
+ ? h('input', {
780
+ 'data-sps': 'input',
781
+ value: target,
782
+ spellCheck: false,
783
+ onChange: (event) => setTarget(event.target.value),
784
+ placeholder: payload?.defaultTargetName ?? 'deployment:persona-suffix',
785
+ })
786
+ : h(
787
+ 'select',
788
+ {
789
+ 'data-sps': 'input',
790
+ value: target,
791
+ onChange: (event) => setTarget(event.target.value),
792
+ },
793
+ sections.map((row) =>
794
+ h(
795
+ 'option',
796
+ { key: row.name, value: row.name },
797
+ `${row.name} · ${row.order ?? '?'} · ${row.chars}`,
798
+ ),
799
+ ),
800
+ target !== '' && !sections.some((row) => row.name === target)
801
+ ? h('option', { value: target }, `${target}(不在清单中,将新增)`)
802
+ : null,
803
+ ),
804
+ h('span', { 'data-sps': 'muted' }, t('targetHint')),
805
+ )
806
+ : null,
807
+
808
+ mode === 'complete'
809
+ ? h(
810
+ 'div',
811
+ { key: 'risk', style: { display: 'flex', flexDirection: 'column', gap: 8 } },
812
+ h('div', { 'data-sps': 'warn' }, t('modeCompleteRisk')),
813
+ blocked.complete
814
+ ? h('div', { 'data-sps': 'error' }, t('completeBlocked'))
815
+ : h(
816
+ 'label',
817
+ { 'data-sps': 'row', style: { gap: 8 } },
818
+ h('input', {
819
+ type: 'checkbox',
820
+ checked: ack,
821
+ onChange: (event) => setAck(event.target.checked),
822
+ }),
823
+ h('span', { 'data-sps': 'muted' }, t('modeCompleteAck')),
824
+ ),
825
+ )
826
+ : null,
827
+
828
+ // 正文
829
+ h(
830
+ 'div',
831
+ { key: 'text', style: { display: 'flex', flexDirection: 'column', gap: 6 } },
832
+ h(
833
+ 'div',
834
+ { 'data-sps': 'row' },
835
+ h('span', { 'data-sps': 'label' }, t('body')),
836
+ h('span', { 'data-sps': 'spacer' }),
837
+ h('span', { 'data-sps': 'muted' }, `${text.length} ${t('chars')} / ${maxChars}`),
838
+ ),
839
+ h('textarea', {
840
+ 'data-sps': 'textarea',
841
+ ref: textareaRef,
842
+ value: text,
843
+ spellCheck: false,
844
+ onChange: (event) => setText(event.target.value),
845
+ }),
846
+ h('span', { 'data-sps': 'muted' }, t('bodyHint')),
847
+ ),
848
+
849
+ h(
850
+ 'label',
851
+ { key: 'enable', 'data-sps': 'row', style: { gap: 8 } },
852
+ h('input', { type: 'checkbox', checked: enabled, onChange: (event) => setEnabled(event.target.checked) }),
853
+ h('span', { 'data-sps': 'muted' }, t('enable')),
854
+ ),
855
+
856
+ // 影响说明
857
+ h('div', { key: 'cache', 'data-sps': 'muted' }, t('prefixCache')),
858
+
859
+ notice.text !== ''
860
+ ? h('div', { key: 'notice', 'data-sps': notice.kind === 'ok' ? 'ok' : 'error' }, notice.text)
861
+ : null,
862
+
863
+ // 只读预览:最近一次请求的系统提示词
864
+ h(
865
+ 'details',
866
+ { key: 'current', 'data-sps': 'details' },
867
+ h(
868
+ 'summary',
869
+ null,
870
+ `${t('current')}${current === null ? ` · ${t('currentEmpty')}` : ` · ${current.chars} ${t('chars')}`}`,
871
+ ),
872
+ payload?.currentNote ? h('div', { 'data-sps': 'muted', style: { marginTop: 6 } }, payload.currentNote) : null,
873
+ current !== null
874
+ ? h('pre', { 'data-sps': 'pre' }, current.text)
875
+ : h('div', { 'data-sps': 'muted', style: { marginTop: 6 } }, t('currentEmpty')),
876
+ current !== null
877
+ ? h(
878
+ 'button',
879
+ { type: 'button', 'data-sps': 'button', style: { marginTop: 8 }, onClick: onCopy },
880
+ t('copy'),
881
+ )
882
+ : null,
883
+ ),
884
+
885
+ // 只读预览:装配到的段
886
+ h(
887
+ 'details',
888
+ { key: 'sections', 'data-sps': 'details' },
889
+ h(
890
+ 'summary',
891
+ null,
892
+ `${t('sections')}${sections === null ? '' : ` · ${sections.length}`}${sectionsAtText === '' ? '' : ` · ${sectionsAtText}`}`,
893
+ ),
894
+ sections === null
895
+ ? h('div', { 'data-sps': 'muted', style: { marginTop: 6 } }, payload?.sectionsNote ?? '')
896
+ : h(
897
+ React.Fragment,
898
+ null,
899
+ // complete 模式:这份清单与实际发送内容必然不一致,必须说清。
900
+ payload?.sectionsComplete === true
901
+ ? h('div', { 'data-sps': 'warn', style: { marginTop: 8 } }, t('sectionsCompleteNote'))
902
+ : null,
903
+ // 保存后清单还没刷新:说明它来自哪一次装配。
904
+ payload?.sectionsStale === true
905
+ ? h('div', { 'data-sps': 'warn', style: { marginTop: 8 } }, t('sectionsStaleNote'))
906
+ : null,
907
+ h(
908
+ 'table',
909
+ { 'data-sps': 'table' },
910
+ h(
911
+ 'thead',
912
+ null,
913
+ h(
914
+ 'tr',
915
+ null,
916
+ h('th', null, t('sectionName')),
917
+ h('th', null, t('sectionOrder')),
918
+ h('th', null, t('sectionChars')),
919
+ ),
920
+ ),
921
+ h(
922
+ 'tbody',
923
+ null,
924
+ sections.map((row) =>
925
+ h(
926
+ 'tr',
927
+ { key: row.name },
928
+ h('td', null, row.name),
929
+ h('td', { 'data-num': 'true' }, row.order ?? '—'),
930
+ h('td', { 'data-num': 'true' }, row.chars),
931
+ ),
932
+ ),
933
+ ),
934
+ ),
935
+ ),
936
+ ),
937
+
938
+ status.error !== ''
939
+ ? h('div', { key: 'err', 'data-sps': 'error' }, `${t('fetchFailed')}${status.error}`)
940
+ : null,
941
+ ),
942
+ h(
943
+ 'div',
944
+ { key: 'foot', 'data-sps': 'head', style: { borderBottom: 'none', borderTop: '1px solid var(--dsw-alias-border-l1)', paddingTop: 12 } },
945
+ h(
946
+ 'div',
947
+ { 'data-sps': 'foot', style: { flex: 1 } },
948
+ h(
949
+ 'button',
950
+ { type: 'button', 'data-sps': 'button', disabled: busy, onClick: () => reload(scope) },
951
+ t('refresh'),
952
+ ),
953
+ h(
954
+ 'button',
955
+ { type: 'button', 'data-sps': 'button', disabled: disabled, onClick: onClear },
956
+ t('clear'),
957
+ ),
958
+ ),
959
+ h('span', { 'data-sps': 'spacer' }),
960
+ h(
961
+ 'button',
962
+ {
963
+ type: 'button',
964
+ 'data-sps': 'button',
965
+ 'data-primary': 'true',
966
+ disabled: disabled || !completeOk,
967
+ onClick: onSave,
968
+ },
969
+ busy ? t('saving') : t('save'),
970
+ ),
971
+ ),
972
+ ]
973
+
974
+ const dialog = h(
975
+ 'div',
976
+ {
977
+ 'data-sps': 'dialog',
978
+ role: 'dialog',
979
+ 'aria-modal': 'true',
980
+ 'aria-label': t('title'),
981
+ onClick: (event) => event.stopPropagation(),
982
+ },
983
+ children,
984
+ )
985
+
986
+ // 放弃改动的确认层:盖在编辑面板之上,默认焦点落在「继续编辑」。
987
+ const discardLayer = confirmClose
988
+ ? h(
989
+ 'div',
990
+ {
991
+ 'data-sps': 'dialog',
992
+ role: 'alertdialog',
993
+ 'aria-modal': 'true',
994
+ 'aria-label': t('discardTitle'),
995
+ style: { width: 'min(420px, 100%)', maxHeight: 'none' },
996
+ onClick: (event) => event.stopPropagation(),
997
+ },
998
+ h(
999
+ 'div',
1000
+ { 'data-sps': 'head' },
1001
+ h('div', { 'data-sps': 'headmain' }, h('div', { 'data-sps': 'title' }, t('discardTitle'))),
1002
+ ),
1003
+ h(
1004
+ 'div',
1005
+ { 'data-sps': 'body' },
1006
+ h('div', { 'data-sps': 'muted' }, t('discardBody')),
1007
+ ),
1008
+ h(
1009
+ 'div',
1010
+ { 'data-sps': 'head', style: { borderBottom: 'none', borderTop: '1px solid var(--dsw-alias-border-l1)', paddingTop: 12 } },
1011
+ h('span', { 'data-sps': 'spacer' }),
1012
+ h('button', { type: 'button', 'data-sps': 'button', onClick: cancelDiscard, autoFocus: true }, t('discardKeep')),
1013
+ h(
1014
+ 'button',
1015
+ {
1016
+ type: 'button',
1017
+ 'data-sps': 'button',
1018
+ style: { borderColor: 'var(--dsw-alias-state-error-primary)', color: 'var(--dsw-alias-state-error-primary)' },
1019
+ onClick: confirmDiscard,
1020
+ },
1021
+ t('discardConfirm'),
1022
+ ),
1023
+ ),
1024
+ )
1025
+ : null
1026
+
1027
+ return ReactDOM.createPortal(
1028
+ h(
1029
+ 'div',
1030
+ {
1031
+ 'data-sps': 'backdrop',
1032
+ ref: backdropRef,
1033
+ // 遮罩点击同样走关闭保护:有未保存改动时先确认,不直接丢。
1034
+ onClick: confirmClose ? cancelDiscard : requestClose,
1035
+ },
1036
+ discardLayer ?? dialog,
1037
+ ),
1038
+ document.body,
1039
+ )
1040
+ }
1041
+
1042
+ function apply(ctx, config) {
1043
+ const cfg = config !== null && typeof config === 'object' ? config : {}
1044
+ if (cfg.visible === false) return
1045
+ const t = makeText(ctx)
1046
+ const api = createApi({ hostURL: typeof cfg.hostURL === 'string' ? cfg.hostURL : '' })
1047
+ const helpers = { t, api, config: { showLabel: cfg.showLabel === true } }
1048
+
1049
+ ctx.effect(() => ensureStyle())
1050
+
1051
+ // 已发过消息的对话:标题栏动作槽。
1052
+ ctx.slots.inject('conversation.session.header.actions', () =>
1053
+ ctx.slots.register(
1054
+ { name: 'conversation.session.header.actions', id: 'system-prompt-studio', order: 30 },
1055
+ (props) => HeaderAction(props, helpers),
1056
+ ),
1057
+ )
1058
+
1059
+ /**
1060
+ * 新空会话:欢迎区选项槽。
1061
+ *
1062
+ * 空会话是 hero 态,标题栏整行 `hideChrome`,上面那个槽不会渲染——
1063
+ * 不给这里补一个入口,「只改这个新对话」在新会话里就没有任何办法触发。
1064
+ * 用独立的 id(不是复用 header 的),两个槽各自独立、互不覆盖。
1065
+ */
1066
+ if (cfg.showOnNewConversation !== false) {
1067
+ ctx.slots.inject('conversation.hero.options', () =>
1068
+ ctx.slots.register(
1069
+ { name: 'conversation.hero.options', id: 'system-prompt-studio-hero', order: 20 },
1070
+ (props) => HeroAction(props, helpers),
1071
+ ),
1072
+ )
1073
+ }
1074
+ }
1075
+
1076
+ return { inject, apply, HeaderAction, HeroAction }
1077
+ },
1078
+ })