dsh-workflow-bar 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,847 @@
1
+ /**
2
+ * dsh-workflow-bar — browser half.
3
+ *
4
+ * Two registrations over one store-shaped state:
5
+ * - `sidebar.panellist` adds the "Workflows" row to the left sidebar;
6
+ * - `main` renders the management page that row selects.
7
+ *
8
+ * The page talks to the Host through the plugin's same-origin JSON API, so the
9
+ * panel, the slash commands, and the agent tool all read and write one library.
10
+ */
11
+
12
+ window.__ModuleLoader__.load({
13
+ id: 'dsh-workflow-bar',
14
+ factory(require) {
15
+ const React = require('react')
16
+ const h = React.createElement
17
+ const { useCallback, useEffect, useMemo, useRef, useState } = React
18
+
19
+ /** Identity shared by the sidebar row and the main-slot page. */
20
+ const PANEL_ID = 'workflow-bar'
21
+ const API_PATH = '/workflow-bar/api'
22
+ const NAME_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/u
23
+
24
+ /** One API round trip; resolves the payload or throws a readable Error. */
25
+ async function call(method, params) {
26
+ let response
27
+ try {
28
+ response = await fetch(API_PATH, {
29
+ method: 'POST',
30
+ headers: { 'content-type': 'application/json' },
31
+ body: JSON.stringify({ method, params: params ?? {} }),
32
+ cache: 'no-store',
33
+ credentials: 'same-origin',
34
+ })
35
+ } catch (cause) {
36
+ const error = new Error('无法连接 Workflow Bar 宿主服务,宿主可能仍在加载。')
37
+ error.cause = cause
38
+ throw error
39
+ }
40
+ let payload = null
41
+ try {
42
+ payload = await response.json()
43
+ } catch {
44
+ // A non-JSON body is reported as the HTTP failure below.
45
+ }
46
+ if (!response.ok || !payload || payload.ok === false) {
47
+ const error = new Error(payload?.message || `请求失败(HTTP ${response.status})`)
48
+ if (payload?.code) error.code = payload.code
49
+ throw error
50
+ }
51
+ return payload
52
+ }
53
+
54
+ /** Copy text to the clipboard with a document-exec fallback. */
55
+ async function copyText(text) {
56
+ try {
57
+ if (navigator.clipboard?.writeText) {
58
+ await navigator.clipboard.writeText(text)
59
+ return true
60
+ }
61
+ } catch {
62
+ // Fall through to the textarea path.
63
+ }
64
+ try {
65
+ const area = document.createElement('textarea')
66
+ area.value = text
67
+ area.setAttribute('readonly', 'readonly')
68
+ area.style.position = 'fixed'
69
+ area.style.opacity = '0'
70
+ document.body.appendChild(area)
71
+ area.select()
72
+ const copied = document.execCommand('copy')
73
+ document.body.removeChild(area)
74
+ return copied
75
+ } catch {
76
+ return false
77
+ }
78
+ }
79
+
80
+ const STYLES = `
81
+ .wfb-root {
82
+ display: flex;
83
+ flex-direction: column;
84
+ height: 100%;
85
+ min-height: 0;
86
+ color: var(--dsw-alias-label-primary);
87
+ background: var(--dsw-alias-bg-base);
88
+ font-size: 13px;
89
+ line-height: 1.5;
90
+ }
91
+ .wfb-root * { box-sizing: border-box; }
92
+ .wfb-header {
93
+ display: flex;
94
+ align-items: center;
95
+ gap: 10px;
96
+ padding: 14px 20px;
97
+ border-bottom: 0.5px solid var(--dsw-alias-border-l2);
98
+ flex: none;
99
+ flex-wrap: wrap;
100
+ }
101
+ .wfb-title { font-size: 15px; font-weight: 600; }
102
+ .wfb-count { font-size: 12px; color: var(--dsw-alias-label-tertiary); }
103
+ .wfb-dir {
104
+ margin-left: auto;
105
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
106
+ font-size: 11px;
107
+ color: var(--dsw-alias-label-caption);
108
+ overflow: hidden;
109
+ text-overflow: ellipsis;
110
+ white-space: nowrap;
111
+ max-width: 40%;
112
+ }
113
+ .wfb-btn {
114
+ appearance: none;
115
+ border: 0.5px solid var(--dsw-alias-border-l3);
116
+ background: transparent;
117
+ color: var(--dsw-alias-label-primary);
118
+ border-radius: 8px;
119
+ padding: 5px 10px;
120
+ font: inherit;
121
+ font-size: 12.5px;
122
+ cursor: pointer;
123
+ white-space: nowrap;
124
+ }
125
+ .wfb-btn:hover { background: var(--dsw-alias-interactive-bg-hover); }
126
+ .wfb-btn:disabled { opacity: 0.45; cursor: default; }
127
+ .wfb-btn[data-variant='primary'] {
128
+ background: var(--dsw-alias-button-primary-fill);
129
+ border-color: transparent;
130
+ color: var(--dsw-alias-label-primary-foreground);
131
+ }
132
+ .wfb-btn[data-variant='primary']:hover { background: var(--dsw-alias-button-primary-hover); }
133
+ .wfb-btn[data-variant='danger'] { color: var(--dsw-alias-state-error-primary); }
134
+ .wfb-btn[data-variant='danger']:hover { background: var(--dsw-alias-interactive-bg-hover-danger); }
135
+ .wfb-body { display: flex; flex: 1; min-height: 0; }
136
+ .wfb-list {
137
+ width: min(290px, 36%);
138
+ min-width: 200px;
139
+ flex: none;
140
+ border-right: 0.5px solid var(--dsw-alias-border-l2);
141
+ display: flex;
142
+ flex-direction: column;
143
+ min-height: 0;
144
+ }
145
+ /* Anchored to the list column so the shared input width rule cannot win by
146
+ order: the field stretches to the column minus its margins, never overflows. */
147
+ .wfb-list > .wfb-search { width: auto; min-width: 0; margin: 12px 8px 8px; }
148
+ .wfb-rows { flex: 1; overflow: auto; padding: 0 8px 12px; }
149
+ .wfb-row {
150
+ display: block;
151
+ width: 100%;
152
+ text-align: left;
153
+ padding: 8px 10px;
154
+ border: none;
155
+ border-radius: 8px;
156
+ background: transparent;
157
+ color: inherit;
158
+ font: inherit;
159
+ cursor: pointer;
160
+ }
161
+ .wfb-row:hover { background: var(--dsw-alias-interactive-bg-hover); }
162
+ .wfb-row[data-selected='true'] { background: var(--dsw-alias-interactive-bg-active); }
163
+ .wfb-row-name {
164
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
165
+ font-size: 12.5px;
166
+ overflow: hidden;
167
+ text-overflow: ellipsis;
168
+ white-space: nowrap;
169
+ }
170
+ .wfb-row-desc {
171
+ font-size: 12px;
172
+ color: var(--dsw-alias-label-tertiary);
173
+ overflow: hidden;
174
+ text-overflow: ellipsis;
175
+ white-space: nowrap;
176
+ }
177
+ .wfb-detail { flex: 1; overflow: auto; padding: 20px 24px 40px; min-width: 0; }
178
+ .wfb-empty {
179
+ flex: 1;
180
+ display: flex;
181
+ flex-direction: column;
182
+ align-items: center;
183
+ justify-content: center;
184
+ gap: 10px;
185
+ padding: 40px 24px;
186
+ color: var(--dsw-alias-label-tertiary);
187
+ text-align: center;
188
+ }
189
+ .wfb-empty-title { font-size: 14px; color: var(--dsw-alias-label-secondary); }
190
+ .wfb-name {
191
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
192
+ font-size: 17px;
193
+ font-weight: 600;
194
+ margin: 0 0 6px;
195
+ overflow-wrap: anywhere;
196
+ }
197
+ .wfb-desc { color: var(--dsw-alias-label-secondary); margin: 0 0 14px; }
198
+ .wfb-meta { color: var(--dsw-alias-label-tertiary); font-size: 12.5px; margin: 0 0 6px; }
199
+ .wfb-meta b { color: var(--dsw-alias-label-secondary); font-weight: 500; }
200
+ .wfb-section-title {
201
+ font-size: 12px;
202
+ text-transform: uppercase;
203
+ letter-spacing: 0.04em;
204
+ color: var(--dsw-alias-label-caption);
205
+ margin: 20px 0 8px;
206
+ }
207
+ .wfb-command {
208
+ display: flex;
209
+ align-items: center;
210
+ gap: 8px;
211
+ padding: 8px 10px;
212
+ border: 0.5px solid var(--dsw-alias-border-l2);
213
+ border-radius: 8px;
214
+ background: var(--dsw-alias-bg-layer-2);
215
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
216
+ font-size: 12px;
217
+ overflow-wrap: anywhere;
218
+ }
219
+ .wfb-command code { flex: 1; min-width: 0; }
220
+ .wfb-pre {
221
+ margin: 0;
222
+ padding: 12px 14px;
223
+ border: 0.5px solid var(--dsw-alias-border-l2);
224
+ border-radius: 8px;
225
+ background: var(--dsw-alias-markdown-code-block);
226
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
227
+ font-size: 12px;
228
+ line-height: 1.55;
229
+ white-space: pre-wrap;
230
+ overflow-wrap: anywhere;
231
+ max-height: 46vh;
232
+ overflow: auto;
233
+ }
234
+ .wfb-actions { display: flex; gap: 8px; margin-top: 18px; flex-wrap: wrap; }
235
+ .wfb-input, .wfb-textarea {
236
+ width: 100%;
237
+ border: 0.5px solid var(--dsw-alias-border-l3);
238
+ border-radius: 8px;
239
+ background: var(--dsw-alias-bg-layer-2);
240
+ color: var(--dsw-alias-label-primary);
241
+ font: inherit;
242
+ padding: 7px 10px;
243
+ }
244
+ .wfb-input:focus, .wfb-textarea:focus {
245
+ outline: 2px solid var(--dsw-alias-border-selected);
246
+ outline-offset: 1px;
247
+ border-color: var(--dsw-alias-border-selected);
248
+ }
249
+ .wfb-input:disabled { opacity: 0.6; }
250
+ .wfb-textarea {
251
+ font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
252
+ font-size: 12px;
253
+ line-height: 1.55;
254
+ resize: vertical;
255
+ min-height: 260px;
256
+ }
257
+ .wfb-field { margin-bottom: 14px; }
258
+ .wfb-label { display: block; font-size: 12px; color: var(--dsw-alias-label-secondary); margin-bottom: 5px; }
259
+ .wfb-hint { font-size: 11.5px; color: var(--dsw-alias-label-caption); margin-top: 4px; }
260
+ .wfb-error { font-size: 12px; color: var(--dsw-alias-state-error-primary); margin-bottom: 10px; }
261
+ .wfb-notice {
262
+ font-size: 12px;
263
+ padding: 7px 10px;
264
+ border-radius: 8px;
265
+ margin-bottom: 12px;
266
+ border: 0.5px solid var(--dsw-alias-border-l2);
267
+ background: var(--dsw-alias-bg-layer-2);
268
+ }
269
+ .wfb-notice[data-tone='error'] {
270
+ color: var(--dsw-alias-state-error-primary);
271
+ border-color: var(--dsw-alias-state-error-primary);
272
+ }
273
+ .wfb-broken {
274
+ margin-top: 10px;
275
+ font-size: 11.5px;
276
+ color: var(--dsw-alias-state-warn-label);
277
+ }
278
+ .wfb-form-actions { display: flex; gap: 8px; margin-top: 14px; align-items: center; }
279
+ .wfb-grow { flex: 1; }
280
+ @media (max-width: 720px) {
281
+ .wfb-body { flex-direction: column; }
282
+ .wfb-list {
283
+ width: auto;
284
+ min-width: 0;
285
+ border-right: none;
286
+ border-bottom: 0.5px solid var(--dsw-alias-border-l2);
287
+ max-height: 40%;
288
+ }
289
+ .wfb-dir { display: none; }
290
+ }
291
+ `
292
+
293
+ /** Install the page stylesheet once per page, removed on plugin disposal. */
294
+ function installStyles() {
295
+ const existing = document.getElementById('dsh-workflow-bar-styles')
296
+ if (existing) return () => {}
297
+ const style = document.createElement('style')
298
+ style.id = 'dsh-workflow-bar-styles'
299
+ style.textContent = STYLES
300
+ document.head.appendChild(style)
301
+ return () => {
302
+ if (style.parentNode) style.parentNode.removeChild(style)
303
+ }
304
+ }
305
+
306
+ /** Small shared button that never submits a form by accident. */
307
+ function Button({ variant, onClick, disabled, title, children }) {
308
+ return h('button', {
309
+ type: 'button',
310
+ className: 'wfb-btn',
311
+ 'data-variant': variant,
312
+ onClick,
313
+ disabled,
314
+ title,
315
+ }, children)
316
+ }
317
+
318
+ /** Labelled form control; `htmlFor` associates the label with its input. */
319
+ function Field({ id, label, hint, children }) {
320
+ return h('div', { className: 'wfb-field' },
321
+ h('label', { className: 'wfb-label', htmlFor: id }, label),
322
+ children,
323
+ hint ? h('div', { className: 'wfb-hint' }, hint) : null)
324
+ }
325
+
326
+ /** One blank editable record. */
327
+ const BLANK = { name: '', description: '', whenToUse: '', argsHint: '', defaultInput: '', script: '' }
328
+
329
+ /** The management page. */
330
+ function WorkflowPanel(props) {
331
+ const closePanel = props?.close
332
+ const [status, setStatus] = useState('loading')
333
+ const [loadError, setLoadError] = useState('')
334
+ const [library, setLibrary] = useState({ directory: '', workflows: [], broken: [] })
335
+ const [query, setQuery] = useState('')
336
+ const [selected, setSelected] = useState(null)
337
+ const [detail, setDetail] = useState(null)
338
+ const [mode, setMode] = useState('view')
339
+ const [form, setForm] = useState(BLANK)
340
+ const [formError, setFormError] = useState('')
341
+ const [allowOverwrite, setAllowOverwrite] = useState(false)
342
+ const [notice, setNotice] = useState(null)
343
+ const [busy, setBusy] = useState(false)
344
+ const [confirmRemove, setConfirmRemove] = useState(false)
345
+ const noticeTimer = useRef(null)
346
+ const confirmTimer = useRef(null)
347
+ const latestDetail = useRef(0)
348
+ const alive = useRef(true)
349
+
350
+ useEffect(() => () => {
351
+ alive.current = false
352
+ if (noticeTimer.current !== null) clearTimeout(noticeTimer.current)
353
+ if (confirmTimer.current !== null) clearTimeout(confirmTimer.current)
354
+ }, [])
355
+
356
+ /** Arm the two-step delete; it disarms itself so a stale click cannot delete. */
357
+ const armRemove = useCallback((armed) => {
358
+ setConfirmRemove(armed)
359
+ if (confirmTimer.current !== null) clearTimeout(confirmTimer.current)
360
+ confirmTimer.current = null
361
+ if (!armed) return
362
+ confirmTimer.current = setTimeout(() => {
363
+ confirmTimer.current = null
364
+ if (alive.current) setConfirmRemove(false)
365
+ }, 5000)
366
+ }, [])
367
+
368
+ const notify = useCallback((text, tone) => {
369
+ if (!alive.current) return
370
+ setNotice({ text, tone: tone ?? 'info' })
371
+ if (noticeTimer.current !== null) clearTimeout(noticeTimer.current)
372
+ noticeTimer.current = setTimeout(() => {
373
+ noticeTimer.current = null
374
+ if (alive.current) setNotice(null)
375
+ }, 4000)
376
+ }, [])
377
+
378
+ const refresh = useCallback(async (keepSelection) => {
379
+ try {
380
+ const payload = await call('list')
381
+ if (!alive.current) return
382
+ setLibrary({
383
+ directory: payload.directory ?? '',
384
+ workflows: Array.isArray(payload.workflows) ? payload.workflows : [],
385
+ broken: Array.isArray(payload.broken) ? payload.broken : [],
386
+ })
387
+ setStatus('ready')
388
+ setLoadError('')
389
+ if (keepSelection === undefined) return
390
+ const names = (payload.workflows ?? []).map(workflow => workflow.name)
391
+ if (keepSelection && names.includes(keepSelection)) {
392
+ setSelected(keepSelection)
393
+ const request = ++latestDetail.current
394
+ const payloadDetail = await call('detail', { name: keepSelection })
395
+ if (alive.current && latestDetail.current === request) setDetail(payloadDetail.workflow)
396
+ } else {
397
+ setSelected(null)
398
+ setDetail(null)
399
+ }
400
+ } catch (error) {
401
+ if (!alive.current) return
402
+ setStatus('failed')
403
+ setLoadError(error.message)
404
+ notify(error.message, 'error')
405
+ }
406
+ }, [notify])
407
+
408
+ useEffect(() => {
409
+ refresh(undefined)
410
+ }, [refresh])
411
+
412
+ // A workflow saved from another surface (the agent tool, /workflow-add)
413
+ // reaches this already-mounted page when the window regains focus.
414
+ useEffect(() => {
415
+ const onVisible = () => {
416
+ if (document.visibilityState === 'visible') refresh(selected)
417
+ }
418
+ window.addEventListener('focus', onVisible)
419
+ document.addEventListener('visibilitychange', onVisible)
420
+ return () => {
421
+ window.removeEventListener('focus', onVisible)
422
+ document.removeEventListener('visibilitychange', onVisible)
423
+ }
424
+ }, [refresh, selected])
425
+
426
+ /** Whether the open form holds anything worth keeping. */
427
+ const formDirty = useCallback(() => mode !== 'view'
428
+ && (form.name.trim() !== '' || form.description.trim() !== '' || form.script.trim() !== ''), [form, mode])
429
+
430
+ const openDetail = useCallback(async (name) => {
431
+ if (formDirty() && !window.confirm('放弃未保存的内容?')) return
432
+ setSelected(name)
433
+ setMode('view')
434
+ setAllowOverwrite(false)
435
+ armRemove(false)
436
+ setDetail(null)
437
+ const request = ++latestDetail.current
438
+ try {
439
+ const payload = await call('detail', { name })
440
+ if (alive.current && latestDetail.current === request) setDetail(payload.workflow)
441
+ } catch (error) {
442
+ if (alive.current && latestDetail.current === request) notify(error.message, 'error')
443
+ }
444
+ }, [armRemove, formDirty, notify])
445
+
446
+ const startCreate = useCallback(() => {
447
+ if (formDirty() && !window.confirm('放弃未保存的内容?')) return
448
+ setMode('create')
449
+ setForm(BLANK)
450
+ setFormError('')
451
+ setAllowOverwrite(false)
452
+ setSelected(null)
453
+ setDetail(null)
454
+ armRemove(false)
455
+ }, [armRemove, formDirty])
456
+
457
+ const startEdit = useCallback(() => {
458
+ if (!detail) return
459
+ setMode('edit')
460
+ setForm({
461
+ name: detail.name,
462
+ description: detail.description,
463
+ whenToUse: detail.whenToUse ?? '',
464
+ argsHint: detail.argsHint ?? '',
465
+ defaultInput: detail.defaultInput ?? '',
466
+ script: detail.script,
467
+ })
468
+ setFormError('')
469
+ setAllowOverwrite(false)
470
+ armRemove(false)
471
+ }, [armRemove, detail])
472
+
473
+ const submit = useCallback(async () => {
474
+ const name = form.name.trim()
475
+ if (!NAME_PATTERN.test(name)) {
476
+ setFormError('名称必须是以字母开头的小写 slug(字母、数字、- 或 _,最多 64 字符)。')
477
+ return
478
+ }
479
+ if (form.description.trim().length === 0) {
480
+ setFormError('描述不能为空。')
481
+ return
482
+ }
483
+ if (form.script.trim().length === 0) {
484
+ setFormError('脚本不能为空。')
485
+ return
486
+ }
487
+ setBusy(true)
488
+ setFormError('')
489
+ const overwrite = mode === 'edit' || allowOverwrite
490
+ try {
491
+ await call('save', {
492
+ name,
493
+ description: form.description,
494
+ whenToUse: form.whenToUse,
495
+ argsHint: form.argsHint,
496
+ defaultInput: form.defaultInput,
497
+ script: form.script,
498
+ overwrite,
499
+ })
500
+ setMode('view')
501
+ setAllowOverwrite(false)
502
+ await refresh(name)
503
+ notify(mode === 'edit' || allowOverwrite ? `已更新「${name}」。` : `已保存「${name}」。`)
504
+ } catch (error) {
505
+ if (!alive.current) return
506
+ if (error.code === 'exists') {
507
+ setAllowOverwrite(true)
508
+ setFormError(`名称「${name}」已被占用。改用另一个名称,或点“覆盖保存”替换它。`)
509
+ } else {
510
+ setFormError(error.message)
511
+ }
512
+ } finally {
513
+ if (alive.current) setBusy(false)
514
+ }
515
+ }, [allowOverwrite, form, mode, notify, refresh])
516
+
517
+ const remove = useCallback(async () => {
518
+ if (!detail) return
519
+ if (!confirmRemove) {
520
+ armRemove(true)
521
+ return
522
+ }
523
+ setBusy(true)
524
+ try {
525
+ await call('remove', { name: detail.name })
526
+ notify(`已删除「${detail.name}」。`)
527
+ setMode('view')
528
+ setDetail(null)
529
+ setSelected(null)
530
+ armRemove(false)
531
+ await refresh(null)
532
+ } catch (error) {
533
+ if (alive.current) notify(error.message, 'error')
534
+ } finally {
535
+ if (alive.current) setBusy(false)
536
+ }
537
+ }, [armRemove, confirmRemove, detail, notify, refresh])
538
+
539
+ const copyCommand = useCallback(async () => {
540
+ if (!detail) return
541
+ const text = `/workflow ${detail.name} `
542
+ const copied = await copyText(text)
543
+ notify(copied ? `已复制运行命令:${text.trim()}` : `复制失败,请手动输入:${text.trim()}`, copied ? 'info' : 'error')
544
+ }, [detail, notify])
545
+
546
+ const visible = useMemo(() => {
547
+ const needle = query.trim().toLowerCase()
548
+ if (needle.length === 0) return library.workflows
549
+ return library.workflows.filter(workflow =>
550
+ workflow.name.includes(needle) || workflow.description.toLowerCase().includes(needle))
551
+ }, [library.workflows, query])
552
+
553
+ return h('div', { className: 'wfb-root' },
554
+ h('header', { className: 'wfb-header' },
555
+ h('span', { className: 'wfb-title' }, 'Workflow 库'),
556
+ h('span', { className: 'wfb-count' }, status === 'ready' ? `${library.workflows.length} 个` : ''),
557
+ status === 'ready' && library.directory
558
+ ? h('span', { className: 'wfb-dir', title: 'workflow 文件所在目录' }, library.directory)
559
+ : null,
560
+ h('span', { className: 'wfb-grow' }),
561
+ h(Button, { onClick: () => refresh(selected), disabled: busy }, '刷新'),
562
+ h(Button, { variant: 'primary', onClick: startCreate, disabled: busy }, '新建'),
563
+ closePanel
564
+ ? h(Button, { onClick: closePanel }, '返回对话')
565
+ : null),
566
+
567
+ h('div', { className: 'wfb-body' },
568
+ h('div', { className: 'wfb-list' },
569
+ h('input', {
570
+ className: 'wfb-input wfb-search',
571
+ type: 'search',
572
+ value: query,
573
+ placeholder: '过滤名称或描述',
574
+ 'aria-label': '过滤 workflow',
575
+ onChange: event => setQuery(event.target.value),
576
+ }),
577
+ h('div', { className: 'wfb-rows' },
578
+ status === 'loading' && library.workflows.length === 0
579
+ ? h('div', { className: 'wfb-meta' }, '加载中…')
580
+ : null,
581
+ status === 'ready' && visible.length === 0
582
+ ? h('div', { className: 'wfb-meta' },
583
+ query ? '没有匹配的 workflow。' : '还没有 workflow,点右上角“新建”。')
584
+ : null,
585
+ visible.map(workflow => h('button', {
586
+ key: workflow.name,
587
+ type: 'button',
588
+ className: 'wfb-row',
589
+ 'data-selected': selected === workflow.name ? 'true' : 'false',
590
+ 'aria-current': selected === workflow.name ? 'true' : undefined,
591
+ onClick: () => openDetail(workflow.name),
592
+ },
593
+ h('div', { className: 'wfb-row-name' }, workflow.name),
594
+ h('div', { className: 'wfb-row-desc' }, workflow.description || '(无描述)'))),
595
+ library.broken.length > 0
596
+ ? h('div', { className: 'wfb-broken' },
597
+ `${library.broken.length} 个文件无法解析:${library.broken.map(entry => entry.file).join('、')}`)
598
+ : null)),
599
+
600
+ h('section', { className: 'wfb-detail' },
601
+ notice
602
+ ? h('div', {
603
+ className: 'wfb-notice',
604
+ 'data-tone': notice.tone,
605
+ 'aria-live': 'polite',
606
+ }, notice.text)
607
+ : null,
608
+
609
+ mode === 'view' && detail
610
+ ? h('div', null,
611
+ h('h2', { className: 'wfb-name' }, detail.name),
612
+ h('p', { className: 'wfb-desc' }, detail.description),
613
+ detail.whenToUse
614
+ ? h('p', { className: 'wfb-meta' }, h('b', null, '适用时机:'), detail.whenToUse)
615
+ : null,
616
+ h('p', { className: 'wfb-meta' },
617
+ h('b', null, '输入:'),
618
+ detail.argsHint || '直接写在 /workflow 名称之后,脚本以 args.input 读取。'),
619
+ detail.defaultInput
620
+ ? h('p', { className: 'wfb-meta' }, h('b', null, '默认输入:'), detail.defaultInput)
621
+ : null,
622
+ h('p', { className: 'wfb-meta' },
623
+ h('b', null, '更新时间:'),
624
+ detail.updatedAt ? new Date(detail.updatedAt).toLocaleString() : '—'),
625
+ h('div', { className: 'wfb-section-title' }, '运行'),
626
+ h('div', { className: 'wfb-command' },
627
+ h('code', null, `/workflow ${detail.name} <输入>`),
628
+ h(Button, { onClick: copyCommand }, '复制')),
629
+ h('div', { className: 'wfb-hint' }, '复制后在输入框补上输入再回车;运行会新建一轮对话,由 agent 调用 workflow 工具。'),
630
+ h('div', { className: 'wfb-section-title' }, '脚本'),
631
+ h('pre', { className: 'wfb-pre' }, detail.script),
632
+ h('div', { className: 'wfb-actions' },
633
+ h(Button, { variant: 'primary', onClick: startEdit, disabled: busy }, '编辑'),
634
+ h(Button, {
635
+ variant: 'danger',
636
+ onClick: remove,
637
+ disabled: busy,
638
+ title: confirmRemove ? '再次点击确认删除' : '删除这个 workflow',
639
+ }, confirmRemove ? '确认删除?' : '删除'),
640
+ confirmRemove
641
+ ? h(Button, { onClick: () => armRemove(false), disabled: busy }, '取消')
642
+ : null))
643
+ : null,
644
+
645
+ mode === 'view' && !detail && status !== 'failed'
646
+ ? (selected
647
+ ? h('div', { className: 'wfb-empty' }, h('div', { className: 'wfb-empty-title' }, '加载中…'))
648
+ : h('div', { className: 'wfb-empty' },
649
+ h('div', { className: 'wfb-empty-title' }, library.workflows.length === 0 ? '还没有 workflow' : '选择一个 workflow'),
650
+ h('div', null, library.workflows.length === 0
651
+ ? '在这里手写脚本,或者在输入框用 /workflow-add <需求描述> 让 agent 帮你写。'
652
+ : '点左侧列表查看脚本、运行方式和编辑入口。')))
653
+ : null,
654
+
655
+ status === 'failed' && !detail
656
+ ? h('div', { className: 'wfb-empty' },
657
+ h('div', { className: 'wfb-empty-title' }, '读取 workflow 库失败'),
658
+ h('div', null, loadError || '宿主服务可能还在加载;重试一次,仍失败时看插件日志。'),
659
+ h(Button, { onClick: () => refresh(selected), disabled: busy }, '重试'))
660
+ : null,
661
+
662
+ mode === 'create' || mode === 'edit'
663
+ ? h('div', null,
664
+ h('h2', { className: 'wfb-name' }, mode === 'edit' ? `编辑 ${form.name}` : '新建 workflow'),
665
+ formError ? h('div', { className: 'wfb-error', role: 'alert' }, formError) : null,
666
+ h(Field, {
667
+ id: 'wfb-field-name',
668
+ label: '名称(slug)',
669
+ hint: '保存在 workflow 库里作为文件名,例如 parallel-search。',
670
+ }, h('input', {
671
+ id: 'wfb-field-name',
672
+ className: 'wfb-input',
673
+ value: form.name,
674
+ disabled: mode === 'edit',
675
+ placeholder: 'parallel-search',
676
+ onChange: event => setForm({ ...form, name: event.target.value }),
677
+ })),
678
+ h(Field, {
679
+ id: 'wfb-field-description',
680
+ label: '描述',
681
+ hint: '一句话说明这个 workflow 做什么。',
682
+ },
683
+ h('input', {
684
+ id: 'wfb-field-description',
685
+ className: 'wfb-input',
686
+ value: form.description,
687
+ onChange: event => setForm({ ...form, description: event.target.value }),
688
+ })),
689
+ h(Field, {
690
+ id: 'wfb-field-when',
691
+ label: '适用时机(可选)',
692
+ hint: '写进 workflow 工具的 meta.whenToUse。',
693
+ },
694
+ h('input', {
695
+ id: 'wfb-field-when',
696
+ className: 'wfb-input',
697
+ value: form.whenToUse,
698
+ onChange: event => setForm({ ...form, whenToUse: event.target.value }),
699
+ })),
700
+ h(Field, {
701
+ id: 'wfb-field-args',
702
+ label: '输入提示(可选)',
703
+ hint: '告诉使用者 /workflow 名称 后面该填什么;脚本从 args.input 读取。',
704
+ }, h('input', {
705
+ id: 'wfb-field-args',
706
+ className: 'wfb-input',
707
+ value: form.argsHint,
708
+ onChange: event => setForm({ ...form, argsHint: event.target.value }),
709
+ })),
710
+ h(Field, {
711
+ id: 'wfb-field-default',
712
+ label: '默认输入(可选)',
713
+ hint: '留空运行时用它。例如填「首页」,从 /workflow 选中后直接回车就能打开首页。',
714
+ }, h('input', {
715
+ id: 'wfb-field-default',
716
+ className: 'wfb-input',
717
+ value: form.defaultInput,
718
+ onChange: event => setForm({ ...form, defaultInput: event.target.value }),
719
+ })),
720
+ h(Field, {
721
+ id: 'wfb-field-script',
722
+ label: '脚本',
723
+ hint: 'workflow 工具的脚本正文:普通 JavaScript,允许顶层 await,可用 agent()、parallel()、pipeline()、phase()、log(),最后 return 一个 JSON 值。',
724
+ }, h('textarea', {
725
+ id: 'wfb-field-script',
726
+ className: 'wfb-textarea',
727
+ value: form.script,
728
+ spellCheck: false,
729
+ placeholder: 'const input = String((args && args.input) || "").trim()\nif (!input) throw new Error("args.input 必填")\n\nconst result = await parallel([\n () => agent("...")\n])\nreturn { input, result }',
730
+ onChange: event => setForm({ ...form, script: event.target.value }),
731
+ })),
732
+ h('div', { className: 'wfb-form-actions' },
733
+ h(Button, { variant: 'primary', onClick: submit, disabled: busy },
734
+ busy ? '保存中…' : allowOverwrite ? '覆盖保存' : '保存'),
735
+ h(Button, {
736
+ onClick: () => {
737
+ setMode('view')
738
+ setFormError('')
739
+ setAllowOverwrite(false)
740
+ },
741
+ disabled: busy,
742
+ }, '取消')))
743
+ : null)))
744
+ }
745
+
746
+ /** Sidebar row glyph: three phase nodes joined by a rail. */
747
+ function WorkflowIcon(props) {
748
+ const size = props?.size ?? 18
749
+ return h('svg', {
750
+ viewBox: '0 0 24 24',
751
+ width: size,
752
+ height: size,
753
+ fill: 'none',
754
+ stroke: 'currentColor',
755
+ strokeWidth: 1.6,
756
+ strokeLinecap: 'round',
757
+ strokeLinejoin: 'round',
758
+ 'aria-hidden': 'true',
759
+ style: { display: 'block' },
760
+ },
761
+ h('path', { d: 'M5 6h6M5 12h14M5 18h6' }),
762
+ h('circle', { cx: '19', cy: '6', r: '2.1' }),
763
+ h('circle', { cx: '19', cy: '18', r: '2.1' }),
764
+ h('circle', { cx: '5', cy: '12', r: '2.1' }))
765
+ }
766
+
767
+ return {
768
+ inject: ['slots'],
769
+ apply(ctx) {
770
+ // Each registration stands alone: a slot that is not declared yet (or an
771
+ // option it rejects) must not take the other surface down with it.
772
+ const attempt = (label, run) => {
773
+ try {
774
+ return run()
775
+ } catch (error) {
776
+ console.error(`[workflow-bar] ${label} registration failed:`, error)
777
+ return undefined
778
+ }
779
+ }
780
+
781
+ /** Return the main column to the Conversation. */
782
+ const closePanel = () => {
783
+ try {
784
+ ctx.get('layout')?.selectPanel?.(null)
785
+ } catch (error) {
786
+ console.warn('[workflow-bar] selectPanel(null) failed:', error)
787
+ }
788
+ }
789
+
790
+ attempt('styles', () => ctx.effect(() => installStyles(), 'workflow-bar: styles'))
791
+
792
+ // `/workflow` bare invocation lists the saved library instead of asking
793
+ // the user to remember names. A decoration keeps the Host command's
794
+ // catalog row, argument claim, and logging; it only replaces the bare
795
+ // pick. Choosing a row fills the composer with `/workflow <name> ` and
796
+ // returns focus there, so the user adds input and presses Enter.
797
+ attempt('workflow picker', () => ctx.inject(
798
+ ['commandUi', 'sessions', 'conversation'],
799
+ scope => scope.effect(() => scope.commandUi.decorate({
800
+ name: 'workflow',
801
+ available: () => true,
802
+ ui: {
803
+ kind: 'popupSelect',
804
+ searchMode: 'substring',
805
+ searchLabels: () => ({
806
+ placeholder: '搜索 workflow',
807
+ empty: '还没有 workflow。用 /workflow-add <需求描述> 创建,或在 Workflow 库面板里新建。',
808
+ noResults: '没有匹配的 workflow。',
809
+ }),
810
+ async options() {
811
+ const payload = await call('list')
812
+ return (payload.workflows ?? []).map(workflow => ({
813
+ id: workflow.name,
814
+ label: workflow.name,
815
+ detail: [
816
+ workflow.description,
817
+ workflow.argsHint ? `输入:${workflow.argsHint}` : '',
818
+ workflow.defaultInput ? `默认:${workflow.defaultInput}` : '',
819
+ ].filter(Boolean).join(' · '),
820
+ }))
821
+ },
822
+ onSelect(option, session) {
823
+ const actx = scope.sessions.scope(session.sessionId)
824
+ if (actx === undefined) throw new Error('这个会话还没被保留,先在输入框里重新试一次。')
825
+ const input = scope.conversation.input.for(actx)
826
+ input.setDraft(`/workflow ${option.id} `)
827
+ input.focus()
828
+ },
829
+ },
830
+ }), 'workflow-bar: /workflow picker'),
831
+ ))
832
+
833
+ attempt('main panel', () => ctx.slots.inject('main', () => ctx.slots.register({
834
+ name: 'main',
835
+ key: PANEL_ID,
836
+ inject: () => ({ close: closePanel }),
837
+ }, WorkflowPanel)))
838
+ attempt('sidebar row', () => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
839
+ name: 'sidebar.panellist',
840
+ id: PANEL_ID,
841
+ order: 42,
842
+ label: 'Workflow 库',
843
+ }, WorkflowIcon)))
844
+ },
845
+ }
846
+ },
847
+ })