dsh-powertools 0.2.1 → 0.2.2
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/README.md +20 -12
- package/client.js +1129 -95
- package/index.js +12 -1
- package/lib/credentials.js +173 -0
- package/lib/instructions.js +298 -0
- package/lib/sessions.js +144 -5
- package/lib/tasks.js +244 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -1
package/client.js
CHANGED
|
@@ -3,8 +3,43 @@ window.__ModuleLoader__.load({
|
|
|
3
3
|
factory(require) {
|
|
4
4
|
const React = require('react')
|
|
5
5
|
const { Button, IconChevronRightOutlineRegular, writeClipboard } = require('@deepseek-ai/dsh-client-ui-primitives')
|
|
6
|
-
const { createElement: h, useEffect, useLayoutEffect, useRef, useState } = React
|
|
6
|
+
const { createElement: h, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } = React
|
|
7
7
|
const PANEL = 'dsh-powertools'
|
|
8
|
+
const SESSION_LOCALE = `${PANEL}.sessions`
|
|
9
|
+
const sessionLocales = {
|
|
10
|
+
en: {
|
|
11
|
+
defaultWorkspace: 'Default workspace', ungrouped: 'Ungrouped', untitled: 'Untitled session', sessionId: 'Session ID',
|
|
12
|
+
workspaceDeleted: 'Workspace deleted', workspaceMissing: 'No registered workspace matches the working directory.',
|
|
13
|
+
delete: 'Delete session', deleteTitle: 'Delete “{title}”?', confirm: 'Confirm deletion',
|
|
14
|
+
cancel: 'Cancel', close: 'Close', checking: 'Checking session status…', deleting: 'Deleting session…',
|
|
15
|
+
missing: 'This session is no longer available.', blocked: 'This session cannot be deleted.',
|
|
16
|
+
running: 'Stop the running session before deleting it.', childRunning: 'Stop the linked subagent before deleting this session.',
|
|
17
|
+
resident: 'DSH is holding this session open. Restart DSH to release it before deleting.',
|
|
18
|
+
childResident: 'DSH is holding a linked subagent session open. Restart DSH to release it before deleting.',
|
|
19
|
+
storage: 'The session or a linked subagent is stored in a format that cannot be moved to recovery.',
|
|
20
|
+
recovery: 'The session and its linked subagent sessions will move to the recovery folder. Workspace files are kept.',
|
|
21
|
+
subagents: 'Linked subagent sessions: {count}',
|
|
22
|
+
deleted: 'Session moved to the recovery folder.', copyRecovery: 'Copy recovery path',
|
|
23
|
+
copyFailed: 'Could not copy the recovery path.',
|
|
24
|
+
refreshFailed: 'Session moved to the recovery folder. Reopen the app to refresh the list.',
|
|
25
|
+
},
|
|
26
|
+
zh: {
|
|
27
|
+
defaultWorkspace: '默认工作区', ungrouped: '未分组', untitled: '未命名会话', sessionId: '会话 ID',
|
|
28
|
+
workspaceDeleted: '工作区已删除', workspaceMissing: '工作目录没有对应的已登记工作区。',
|
|
29
|
+
delete: '删除会话', deleteTitle: '删除「{title}」?', confirm: '确认删除会话',
|
|
30
|
+
cancel: '取消', close: '关闭', checking: '正在核对会话状态…', deleting: '正在删除会话…',
|
|
31
|
+
missing: '目标会话不存在或已被移除。', blocked: '当前会话无法删除。',
|
|
32
|
+
running: '会话正在运行中,请先停止后再删除。', childRunning: '关联子 Agent 正在运行中,请先停止后再删除。',
|
|
33
|
+
resident: '会话正由当前 DSH 进程打开持有,请重启 DSH 释放后再删除。',
|
|
34
|
+
childResident: '关联子 Agent 会话仍由 DSH 持有,请重启 DSH 释放后再删除。',
|
|
35
|
+
storage: '会话或关联子 Agent 的存储格式不支持移至恢复目录。',
|
|
36
|
+
recovery: '会话及其关联的子 Agent 会话将移至恢复目录,工作区文件会保留。',
|
|
37
|
+
subagents: '关联的子 Agent 会话:{count} 条',
|
|
38
|
+
deleted: '会话已移至恢复目录。', copyRecovery: '复制恢复目录',
|
|
39
|
+
copyFailed: '无法复制恢复目录。',
|
|
40
|
+
refreshFailed: '会话已移至恢复目录。重新打开应用可刷新列表。',
|
|
41
|
+
},
|
|
42
|
+
}
|
|
8
43
|
|
|
9
44
|
// Lucide 1.61.0 icon geometry from Magi Code (web/src/lib/icons.ts), license in licenses/lucide.txt.
|
|
10
45
|
const ICONS = {
|
|
@@ -129,6 +164,36 @@ window.__ModuleLoader__.load({
|
|
|
129
164
|
['path', { d: 'm7 20 5-5 5 5' }],
|
|
130
165
|
['path', { d: 'm7 4 5 5 5-5' }],
|
|
131
166
|
],
|
|
167
|
+
'key-round': [
|
|
168
|
+
['path', { d: 'M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z' }],
|
|
169
|
+
['circle', { cx: 16.5, cy: 7.5, r: 0.5, fill: 'currentColor' }],
|
|
170
|
+
],
|
|
171
|
+
clock: [
|
|
172
|
+
['circle', { cx: 12, cy: 12, r: 10 }],
|
|
173
|
+
['polyline', { points: '12 6 12 12 16 14' }],
|
|
174
|
+
],
|
|
175
|
+
terminal: [
|
|
176
|
+
['polyline', { points: '4 17 10 11 4 5' }],
|
|
177
|
+
['line', { x1: 12, x2: 20, y1: 19, y2: 19 }],
|
|
178
|
+
],
|
|
179
|
+
'file-text': [
|
|
180
|
+
['path', { d: 'M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z' }],
|
|
181
|
+
['path', { d: 'M14 2v4a2 2 0 0 0 2 2h4' }],
|
|
182
|
+
['path', { d: 'M10 9H8' }],
|
|
183
|
+
['path', { d: 'M16 13H8' }],
|
|
184
|
+
['path', { d: 'M16 17H8' }],
|
|
185
|
+
],
|
|
186
|
+
pause: [
|
|
187
|
+
['rect', { x: 14, y: 4, width: 4, height: 16, rx: 1 }],
|
|
188
|
+
['rect', { x: 6, y: 4, width: 4, height: 16, rx: 1 }],
|
|
189
|
+
],
|
|
190
|
+
square: [
|
|
191
|
+
['rect', { width: 18, height: 18, x: 3, y: 3, rx: 2 }],
|
|
192
|
+
],
|
|
193
|
+
pin: [
|
|
194
|
+
['path', { d: 'M12 17v5' }],
|
|
195
|
+
['path', { d: 'M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z' }],
|
|
196
|
+
],
|
|
132
197
|
}
|
|
133
198
|
|
|
134
199
|
function Icon({ name, size = 14, className = '' }) {
|
|
@@ -335,6 +400,17 @@ window.__ModuleLoader__.load({
|
|
|
335
400
|
}
|
|
336
401
|
.dpt-switch[aria-checked='true'] .dpt-switch-thumb { transform: translateX(14px); }
|
|
337
402
|
.dpt-row-label { display: grid; gap: 1px; flex: 1; min-width: 0; }
|
|
403
|
+
.dpt-row-meta { display: flex; align-items: baseline; flex-wrap: wrap; gap: 2px 6px; min-width: 0; }
|
|
404
|
+
.dpt-row-meta .dpt-row-summary { flex: 1 1 10ch; }
|
|
405
|
+
.dpt-workspace-badges { display: inline-flex; align-items: center; flex-wrap: wrap; gap: 4px; min-width: 0; max-inline-size: 100%; }
|
|
406
|
+
.dpt-workspace-badge {
|
|
407
|
+
display: inline-block; max-inline-size: 100%; min-inline-size: 0;
|
|
408
|
+
padding: 0 6px; border: 1px solid color-mix(in srgb, var(--dpt-workspace-color) 48%, transparent);
|
|
409
|
+
border-radius: 999px; background: color-mix(in srgb, var(--dpt-workspace-color) 19%, transparent);
|
|
410
|
+
color: var(--dsw-alias-label-primary); font-size: 11px; line-height: 15px;
|
|
411
|
+
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
|
412
|
+
}
|
|
413
|
+
.dpt-workspace-badge[data-workspace-missing] { color: var(--dpt-workspace-color); }
|
|
338
414
|
.dpt-row-title { display: flex; align-items: center; gap: 6px; min-width: 0; }
|
|
339
415
|
.dpt-row-title strong { font-size: 13px; line-height: 20px; font-weight: 500; color: var(--dsw-alias-label-primary); }
|
|
340
416
|
.dpt-row-tag { min-width: 0; color: var(--dpt-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
@@ -400,12 +476,8 @@ window.__ModuleLoader__.load({
|
|
|
400
476
|
.dpt-toast[data-error='true'] { border-color: color-mix(in srgb, var(--dpt-danger) 45%, var(--dpt-line)); }
|
|
401
477
|
.dpt-toast-body { flex: 1; min-width: 0; display: grid; gap: 4px; padding-block: 2px; font-size: 12.5px; line-height: 18px; }
|
|
402
478
|
.dpt-toast[data-error='true'] .dpt-toast-body { color: var(--dpt-danger); }
|
|
403
|
-
.dpt-
|
|
404
|
-
.dpt-
|
|
405
|
-
.dpt-maintenance .dpt-row-title strong { font-size: 12.5px; color: var(--dpt-muted); font-weight: 500; }
|
|
406
|
-
.dpt-meta { display: grid; grid-template-columns: max-content minmax(0, 1fr); align-items: baseline; gap: 4px 12px; }
|
|
407
|
-
.dpt-meta dt, .dpt-field > span, .dpt-label { color: var(--dpt-muted); font-size: 12px; line-height: 18px; font-weight: 500; }
|
|
408
|
-
.dpt-meta dd, .dpt-message-text, .dpt-muted { min-width: 0; overflow-wrap: anywhere; }
|
|
479
|
+
.dpt-field > span, .dpt-label { color: var(--dpt-muted); font-size: 12px; line-height: 18px; font-weight: 500; }
|
|
480
|
+
.dpt-message-text, .dpt-muted { min-width: 0; overflow-wrap: anywhere; }
|
|
409
481
|
.dpt-muted, .dpt-summary { color: var(--dpt-muted); font-size: 12px; line-height: 18px; }
|
|
410
482
|
.dpt, .dpt-modal { font-variant-numeric: tabular-nums; }
|
|
411
483
|
.dpt .dpt-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; line-height: 18px; }
|
|
@@ -547,7 +619,53 @@ window.__ModuleLoader__.load({
|
|
|
547
619
|
return date.getFullYear() === now.getFullYear() ? `${md} ${hm}` : `${date.getFullYear()}/${md}`
|
|
548
620
|
}
|
|
549
621
|
const identity = value => value
|
|
550
|
-
const workspaceTitle = workspace => workspace.title === 'default-workspace'
|
|
622
|
+
const workspaceTitle = (workspace, t) => workspace.title === 'default-workspace'
|
|
623
|
+
? (t ? t('defaultWorkspace') : '默认工作区') : workspace.title
|
|
624
|
+
const workspaceBadgeColors = [
|
|
625
|
+
'var(--dsw-alias-state-business-primary)',
|
|
626
|
+
'var(--dsw-alias-state-warn-primary)',
|
|
627
|
+
'var(--dsw-static-violet-600)',
|
|
628
|
+
'var(--dsw-alias-state-success-primary)',
|
|
629
|
+
'color-mix(in oklch, var(--dsw-alias-state-business-primary), var(--dsw-alias-state-success-primary) 40%)',
|
|
630
|
+
'color-mix(in oklch, var(--dsw-alias-state-success-primary), var(--dsw-alias-state-warn-primary) 50%)',
|
|
631
|
+
]
|
|
632
|
+
|
|
633
|
+
function assignWorkspaceBadgeColors(workspaces) {
|
|
634
|
+
// The oldest workspace gets first choice regardless of sidebar order.
|
|
635
|
+
const ordered = [...workspaces].sort((a, b) =>
|
|
636
|
+
(a.createdAt ?? '').localeCompare(b.createdAt ?? '') || a.workspaceId.localeCompare(b.workspaceId))
|
|
637
|
+
const colors = new Map()
|
|
638
|
+
const used = new Set()
|
|
639
|
+
const count = workspaceBadgeColors.length
|
|
640
|
+
for (const workspace of ordered) {
|
|
641
|
+
if (used.size === count) used.clear()
|
|
642
|
+
let hash = 0
|
|
643
|
+
for (const char of workspace.workspaceId) hash = (Math.imul(hash, 31) + char.codePointAt(0)) >>> 0
|
|
644
|
+
let index = hash % count
|
|
645
|
+
while (used.has(index)) index = (index + 1) % count
|
|
646
|
+
used.add(index)
|
|
647
|
+
colors.set(workspace.workspaceId, workspaceBadgeColors[index])
|
|
648
|
+
}
|
|
649
|
+
return colors
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function WorkspaceBadge({ workspace, workspaceColors, orphanedCwd, t }) {
|
|
653
|
+
const label = workspace ? workspaceTitle(workspace, t) : t(orphanedCwd ? 'workspaceDeleted' : 'ungrouped')
|
|
654
|
+
let accent = 'var(--dsw-alias-label-tertiary)'
|
|
655
|
+
let title = label
|
|
656
|
+
if (workspace) {
|
|
657
|
+
accent = workspaceColors.get(workspace.workspaceId) ?? workspaceBadgeColors[0]
|
|
658
|
+
if (workspace.path) title = `${label}\n${workspace.path}`
|
|
659
|
+
} else if (orphanedCwd) {
|
|
660
|
+
accent = 'var(--dsw-alias-state-error-primary)'
|
|
661
|
+
title = `${t('workspaceMissing')}\n${orphanedCwd}`
|
|
662
|
+
}
|
|
663
|
+
return h('span', {
|
|
664
|
+
className: 'dpt-workspace-badge', title, dir: 'auto',
|
|
665
|
+
'data-workspace-badge': workspace?.workspaceId ?? '', 'data-workspace-missing': orphanedCwd ? true : undefined,
|
|
666
|
+
style: { '--dpt-workspace-color': accent },
|
|
667
|
+
}, label)
|
|
668
|
+
}
|
|
551
669
|
|
|
552
670
|
function Segmented({ label, value, onChange, items }) {
|
|
553
671
|
return h('div', { className: 'dpt-seg', role: 'group', 'aria-label': label }, items.map(item =>
|
|
@@ -630,8 +748,6 @@ window.__ModuleLoader__.load({
|
|
|
630
748
|
const empty = (message, onReset) => h('div', { className: `dpt-card dpt-empty${onReset ? ' dpt-empty-row' : ''}` },
|
|
631
749
|
muted(message, { role: 'status' }),
|
|
632
750
|
onReset && button('重置筛选', onReset, { icon: 'x', iconSize: 13 }))
|
|
633
|
-
const facts = entries => h('dl', { className: 'dpt-meta' }, entries.map(([label, value]) =>
|
|
634
|
-
h(React.Fragment, { key: label }, h('dt', null, label), h('dd', null, value))))
|
|
635
751
|
const pill = (text, tone = 'idle', id) => h('span', { id, className: 'dpt-pill', 'data-tone': tone }, text)
|
|
636
752
|
|
|
637
753
|
function useHostStatus() {
|
|
@@ -683,11 +799,12 @@ window.__ModuleLoader__.load({
|
|
|
683
799
|
}
|
|
684
800
|
|
|
685
801
|
function DisclosureRow({
|
|
686
|
-
title, tag, chips, detail, badge, tone = 'idle', expanded, onToggle,
|
|
802
|
+
title, tag, chips, detail, workspaceBadges, badge, tone = 'idle', expanded, onToggle,
|
|
687
803
|
selectable, quickActions, alwaysActions, children, ...props
|
|
688
804
|
}) {
|
|
689
805
|
const id = React.useId()
|
|
690
|
-
const descriptions = [tag && `${id}-tag`, detail && `${id}-detail`, badge && `${id}-status`].filter(Boolean).join(' ')
|
|
806
|
+
const descriptions = [tag && `${id}-tag`, workspaceBadges && `${id}-workspaces`, detail && `${id}-detail`, badge && `${id}-status`].filter(Boolean).join(' ')
|
|
807
|
+
const summary = detail && h('span', { id: `${id}-detail`, className: 'dpt-muted dpt-ellipsis dpt-row-summary', dir: 'auto' }, detail)
|
|
691
808
|
return h('li', {
|
|
692
809
|
className: 'dpt-row', 'data-open': expanded || undefined,
|
|
693
810
|
'data-selected': selectable?.checked || undefined, ...props,
|
|
@@ -714,7 +831,9 @@ window.__ModuleLoader__.load({
|
|
|
714
831
|
h('strong', { className: 'dpt-ellipsis', dir: 'auto' }, title),
|
|
715
832
|
tag && h('span', { id: `${id}-tag`, className: 'dpt-row-tag dpt-mono', dir: 'ltr' }, tag),
|
|
716
833
|
chips),
|
|
717
|
-
|
|
834
|
+
workspaceBadges
|
|
835
|
+
? h('span', { className: 'dpt-row-meta' }, h('span', { id: `${id}-workspaces`, className: 'dpt-workspace-badges' }, workspaceBadges), summary)
|
|
836
|
+
: summary)),
|
|
718
837
|
h('div', { className: 'dpt-row-end' },
|
|
719
838
|
quickActions && h('div', { className: 'dpt-quick-actions dpt-quick-actions--hover' }, quickActions),
|
|
720
839
|
alwaysActions && h('div', { className: 'dpt-quick-actions' }, alwaysActions),
|
|
@@ -743,20 +862,21 @@ window.__ModuleLoader__.load({
|
|
|
743
862
|
return bind
|
|
744
863
|
}
|
|
745
864
|
|
|
746
|
-
function Modal({ title, close, review = false, children }) {
|
|
865
|
+
function Modal({ title, close, closeLabel = '关闭', busy = false, review = false, children }) {
|
|
747
866
|
const dialog = useRef(null)
|
|
748
867
|
const heading = React.useId()
|
|
749
868
|
useLayoutEffect(() => {
|
|
750
869
|
const node = dialog.current
|
|
751
870
|
node.showModal()
|
|
871
|
+
node.querySelector('[data-dpt-initial-focus]')?.focus()
|
|
752
872
|
return () => node.close()
|
|
753
873
|
}, [])
|
|
754
874
|
return h('dialog', {
|
|
755
875
|
ref: dialog, className: `dpt dpt-modal${review ? ' dpt-review' : ''}`, 'aria-labelledby': heading,
|
|
756
|
-
onCancel: e => { e.preventDefault(); close() },
|
|
876
|
+
onCancel: e => { e.preventDefault(); if (!busy) close() },
|
|
757
877
|
},
|
|
758
878
|
h('style', null, css),
|
|
759
|
-
h('header', { className: 'dpt-modal-head' }, h('h2', { id: heading }, title), button(
|
|
879
|
+
h('header', { className: 'dpt-modal-head' }, h('h2', { id: heading }, title), button(closeLabel, close, { icon: 'x', iconSize: 13, disabled: busy })), children)
|
|
760
880
|
}
|
|
761
881
|
|
|
762
882
|
function useAction() {
|
|
@@ -814,9 +934,24 @@ window.__ModuleLoader__.load({
|
|
|
814
934
|
return parts.join(' · ')
|
|
815
935
|
}
|
|
816
936
|
|
|
937
|
+
function safeFilename(title, fallback) {
|
|
938
|
+
const cleaned = (title || '').replace(/[\\/:*?"<>|\x00-\x1f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 60)
|
|
939
|
+
return cleaned || fallback
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
function triggerDownload(url, filename) {
|
|
943
|
+
const anchor = document.createElement('a')
|
|
944
|
+
anchor.href = url
|
|
945
|
+
anchor.download = filename
|
|
946
|
+
anchor.rel = 'noopener'
|
|
947
|
+
document.body.appendChild(anchor)
|
|
948
|
+
anchor.click()
|
|
949
|
+
anchor.remove()
|
|
950
|
+
}
|
|
951
|
+
|
|
817
952
|
function SessionRow({
|
|
818
|
-
row, id, title, workspaces, isArchived,
|
|
819
|
-
notify, disclosure, selectable,
|
|
953
|
+
row, id, title, workspaces, isArchived, isPinned, matchSnippet, subagents, totalBytes, navigation,
|
|
954
|
+
onArchived, onPinned, onDeleted, notify, disclosure, selectable, workspaceColors, t,
|
|
820
955
|
}) {
|
|
821
956
|
const [status, run, dismiss] = useAction()
|
|
822
957
|
const [removal, setRemoval] = useState(false)
|
|
@@ -833,13 +968,42 @@ window.__ModuleLoader__.load({
|
|
|
833
968
|
onArchived(isArchived ? '会话已恢复' : '会话已归档')
|
|
834
969
|
})
|
|
835
970
|
}
|
|
971
|
+
async function togglePin() {
|
|
972
|
+
await run(async () => {
|
|
973
|
+
await request('sessions', { action: isPinned ? 'unpin' : 'pin', sessionId: id })
|
|
974
|
+
onPinned(isPinned ? '已取消置顶' : '会话已置顶')
|
|
975
|
+
})
|
|
976
|
+
}
|
|
977
|
+
async function exportMarkdown(mode) {
|
|
978
|
+
await run(async () => {
|
|
979
|
+
const response = await fetch(`api/session.markdown?sessionId=${encodeURIComponent(id)}`)
|
|
980
|
+
if (!response.ok) throw new Error('无法导出会话 Markdown,请确认会话已包含内容。')
|
|
981
|
+
const markdown = await response.text()
|
|
982
|
+
if (mode === 'copy') {
|
|
983
|
+
if (!await writeClipboard(markdown)) throw new Error('无法访问剪贴板,请改用下载 Markdown。')
|
|
984
|
+
notify('已复制会话 Markdown')
|
|
985
|
+
return
|
|
986
|
+
}
|
|
987
|
+
const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' })
|
|
988
|
+
const objectUrl = URL.createObjectURL(blob)
|
|
989
|
+
try {
|
|
990
|
+
triggerDownload(objectUrl, `${safeFilename(title, id)}.md`)
|
|
991
|
+
} finally {
|
|
992
|
+
setTimeout(() => URL.revokeObjectURL(objectUrl), 4000)
|
|
993
|
+
}
|
|
994
|
+
notify('已开始下载会话 Markdown')
|
|
995
|
+
})
|
|
996
|
+
}
|
|
997
|
+
function exportZip() {
|
|
998
|
+
triggerDownload(`api/session.export?sessionId=${encodeURIComponent(id)}`, `${safeFilename(title, id)}.zip`)
|
|
999
|
+
notify('已开始下载会话 ZIP 归档')
|
|
1000
|
+
}
|
|
836
1001
|
const timeSummary = formatShortTime(row.updatedAt || row.createdAt)
|
|
837
1002
|
const sizeSummary = totalBytes !== null ? formatBytes(totalBytes) : ''
|
|
838
|
-
const
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
timeSummary
|
|
842
|
-
].filter(Boolean)
|
|
1003
|
+
const lineageSummary = row.isSubagent && (row.orphanSubagent ? '孤儿子会话(父会话已移除)' : `隶属 ${row.parentSessionId}`)
|
|
1004
|
+
const detailParts = matchSnippet
|
|
1005
|
+
? [row.orphanSubagent && lineageSummary, `命中:${matchSnippet}`]
|
|
1006
|
+
: [lineageSummary, sizeSummary, timeSummary]
|
|
843
1007
|
const badge = row.running ? '运行中' : row.isSubagent ? '子 Agent' : isArchived ? '已归档' : undefined
|
|
844
1008
|
const tone = row.running ? 'info' : row.isSubagent ? 'attention' : 'idle'
|
|
845
1009
|
const removedItems = [
|
|
@@ -854,11 +1018,21 @@ window.__ModuleLoader__.load({
|
|
|
854
1018
|
? (subagents.length > 0 ? `关联删除(含 ${subagents.length} 条子会话)` : '删除会话')
|
|
855
1019
|
: (row.deleteReason || '当前不可删除')
|
|
856
1020
|
|
|
1021
|
+
const chips = (isPinned || subagents.length > 0) && h(React.Fragment, null,
|
|
1022
|
+
isPinned && pill('已置顶', 'info'),
|
|
1023
|
+
subagents.length > 0 && pill(`${subagents.length} 子会话`))
|
|
1024
|
+
|
|
857
1025
|
const quickActions = h(React.Fragment, null,
|
|
858
1026
|
!row.isSubagent && button('打开', () => run(() => navigation.openSession(id)), {
|
|
859
1027
|
icon: 'external-link', iconSize: 13, className: 'dpt-row-btn', disabled: status.busy,
|
|
860
1028
|
'aria-label': `打开 ${title}`,
|
|
861
1029
|
}),
|
|
1030
|
+
!row.isSubagent && !isArchived && iconButton(
|
|
1031
|
+
`${isPinned ? '取消置顶' : '置顶'} ${title}`,
|
|
1032
|
+
'pin',
|
|
1033
|
+
togglePin,
|
|
1034
|
+
{ className: 'dpt-row-icon-btn', iconSize: 13, title: isPinned ? '取消置顶' : '置顶会话', disabled: status.busy },
|
|
1035
|
+
),
|
|
862
1036
|
!row.isSubagent && iconButton(
|
|
863
1037
|
`${isArchived ? '恢复' : '归档'} ${title}`,
|
|
864
1038
|
isArchived ? 'archive-restore' : 'archive',
|
|
@@ -876,9 +1050,14 @@ window.__ModuleLoader__.load({
|
|
|
876
1050
|
'data-session-id': id, 'data-session-kind': row.isSubagent ? 'subagent' : 'session',
|
|
877
1051
|
title,
|
|
878
1052
|
tag: row.isSubagent ? (row.agentPreset || (row.delegationDepth ? `L${row.delegationDepth}` : undefined)) : undefined,
|
|
879
|
-
chips
|
|
880
|
-
|
|
1053
|
+
chips,
|
|
1054
|
+
workspaceBadges: workspaces.length
|
|
1055
|
+
? workspaces.map(workspace => h(WorkspaceBadge, { key: workspace.workspaceId, workspace, workspaceColors, t }))
|
|
1056
|
+
: h(WorkspaceBadge, { orphanedCwd: row.orphanWorkspace ? row.cwd : undefined, t }),
|
|
1057
|
+
detail: detailParts.filter(Boolean).join(' · '),
|
|
1058
|
+
badge, tone, selectable, quickActions, ...disclosure,
|
|
881
1059
|
},
|
|
1060
|
+
matchSnippet && muted(`正文命中摘录:${matchSnippet}`),
|
|
882
1061
|
h('div', { className: 'dpt-drawer-bar' },
|
|
883
1062
|
h('div', { className: 'dpt-drawer-facts' },
|
|
884
1063
|
h('span', null, '会话 ID', code(id)),
|
|
@@ -890,10 +1069,15 @@ window.__ModuleLoader__.load({
|
|
|
890
1069
|
: formatBytes(totalBytes)))),
|
|
891
1070
|
h('div', { className: 'dpt-actions' },
|
|
892
1071
|
!row.isSubagent && button('打开', () => run(() => navigation.openSession(id)), { icon: 'external-link', disabled: status.busy }),
|
|
1072
|
+
!row.isSubagent && !isArchived && button(isPinned ? '取消置顶' : '置顶', togglePin, { icon: 'pin', disabled: status.busy }),
|
|
893
1073
|
!row.isSubagent && button(isArchived ? '恢复' : '归档', archive, { icon: isArchived ? 'archive-restore' : 'archive', disabled: status.busy || (!isArchived && row.running) }),
|
|
1074
|
+
button('复制 Markdown', () => exportMarkdown('copy'), { icon: 'copy', disabled: status.busy }),
|
|
1075
|
+
button('下载 .md', () => exportMarkdown('download'), { icon: 'download', disabled: status.busy }),
|
|
1076
|
+
button('ZIP', exportZip, { icon: 'download', disabled: status.busy, title: '下载 DSH 原始会话 ZIP 归档' }),
|
|
894
1077
|
button(subagents.length > 0 ? `关联删除(${subagents.length + 1})` : '删除', () => setRemoval(true), {
|
|
895
1078
|
icon: 'trash', className: 'dpt-danger', disabled: status.busy || !row.deletable, title: deleteHint,
|
|
896
1079
|
}))),
|
|
1080
|
+
row.orphanWorkspace && muted(t('workspaceMissing')),
|
|
897
1081
|
row.cwd && h(PathLine, { value: row.cwd }),
|
|
898
1082
|
subagents.length > 0 && h('div', { className: 'dpt-drawer-split' },
|
|
899
1083
|
h('div', { className: 'dpt-drawer-bar' },
|
|
@@ -901,7 +1085,8 @@ window.__ModuleLoader__.load({
|
|
|
901
1085
|
subagents.length > 6 && button(showAllSubagents ? '收起列表' : `展开全部 ${subagents.length} 条`, () => setShowAllSubagents(!showAllSubagents))),
|
|
902
1086
|
h('ul', { className: `dpt-file-list${showAllSubagents && subagents.length > 8 ? ' dpt-scroll-box' : ''}` }, visibleSubagents.map(child =>
|
|
903
1087
|
h('li', { key: child.id, 'data-subagent-id': child.id },
|
|
904
|
-
h('span', null, subagentLabel(child), ' ', code(child.id)
|
|
1088
|
+
h('span', null, subagentLabel(child), ' ', code(child.id), child.orphanWorkspace && h(React.Fragment, null,
|
|
1089
|
+
' ', h(WorkspaceBadge, { orphanedCwd: child.cwd, t }))),
|
|
905
1090
|
h('span', null, [
|
|
906
1091
|
child.running ? '运行中' : child.resident ? '打开中' : '',
|
|
907
1092
|
Number.isFinite(child.sizeBytes) ? formatBytes(child.sizeBytes) : '',
|
|
@@ -922,8 +1107,10 @@ window.__ModuleLoader__.load({
|
|
|
922
1107
|
}))
|
|
923
1108
|
}
|
|
924
1109
|
|
|
925
|
-
function SessionPanel({ sessionList, workspaceList, navigation, refresh, host, toast }) {
|
|
1110
|
+
function SessionPanel({ sessionList, workspaceList, navigation, refresh, host, toast, t }) {
|
|
926
1111
|
const [query, search] = useState('')
|
|
1112
|
+
const [searchScope, setSearchScope] = useState('title')
|
|
1113
|
+
const [contentSearch, setContentSearch] = useState({ loading: false, query: '', hits: null, error: '' })
|
|
927
1114
|
const [workspace, selectWorkspace] = useState('all')
|
|
928
1115
|
const [viewMode, setViewMode] = useState('active')
|
|
929
1116
|
const [sortBy, setSortBy] = useState('recent')
|
|
@@ -933,11 +1120,52 @@ window.__ModuleLoader__.load({
|
|
|
933
1120
|
const [status, run, dismiss] = useAction()
|
|
934
1121
|
const lastClickedIndex = useRef(-1)
|
|
935
1122
|
const disclosure = useDisclosure()
|
|
936
|
-
const hostSessions = useHostSessions(`${sessionList.ids.length}:${workspaceList.archivedSessionIds.length}`, host.info)
|
|
1123
|
+
const hostSessions = useHostSessions(`${sessionList.ids.length}:${workspaceList.archivedSessionIds.length}:${workspaceList.pinnedSessionIds?.length ?? 0}`, host.info)
|
|
937
1124
|
const archived = new Set(workspaceList.archivedSessionIds)
|
|
1125
|
+
const clientPinned = Array.isArray(workspaceList.pinnedSessionIds) ? workspaceList.pinnedSessionIds : []
|
|
1126
|
+
const clientPinnedOrder = new Map(clientPinned.map((id, index) => [id, index]))
|
|
938
1127
|
const groups = new Map()
|
|
939
|
-
|
|
940
|
-
|
|
1128
|
+
const workspacesByPath = new Map()
|
|
1129
|
+
const workspaceColors = React.useMemo(() => assignWorkspaceBadgeColors(workspaceList.items), [workspaceList.items])
|
|
1130
|
+
const workspacesReady = workspaceList.phase === 'ready'
|
|
1131
|
+
for (const item of workspaceList.items) {
|
|
1132
|
+
if (item.path) workspacesByPath.set(item.path, item)
|
|
1133
|
+
for (const id of item.sessionIds) groups.set(id, [...(groups.get(id) ?? []), item])
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
useEffect(() => {
|
|
1137
|
+
if (workspacesReady && !['all', 'none', 'orphan'].includes(workspace)
|
|
1138
|
+
&& !workspaceList.items.some(item => item.workspaceId === workspace)) selectWorkspace('all')
|
|
1139
|
+
}, [workspace, workspacesReady, workspaceList.items])
|
|
1140
|
+
|
|
1141
|
+
const trimmedQuery = query.trim()
|
|
1142
|
+
useEffect(() => {
|
|
1143
|
+
if (searchScope !== 'content' || !trimmedQuery) {
|
|
1144
|
+
setContentSearch({ loading: false, query: '', hits: null, error: '' })
|
|
1145
|
+
return
|
|
1146
|
+
}
|
|
1147
|
+
const abort = new AbortController()
|
|
1148
|
+
setContentSearch(previous => ({ ...previous, loading: true, error: '' }))
|
|
1149
|
+
const timer = setTimeout(async () => {
|
|
1150
|
+
try {
|
|
1151
|
+
const result = await request('sessions', { action: 'search', query: trimmedQuery, limit: 50 }, abort.signal)
|
|
1152
|
+
if (!abort.signal.aborted) {
|
|
1153
|
+
setContentSearch({ loading: false, query: trimmedQuery, hits: result.hits ?? [], error: '' })
|
|
1154
|
+
}
|
|
1155
|
+
} catch (err) {
|
|
1156
|
+
if (!abort.signal.aborted) {
|
|
1157
|
+
setContentSearch({ loading: false, query: trimmedQuery, hits: [], error: err.message })
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
}, 220)
|
|
1161
|
+
return () => { clearTimeout(timer); abort.abort() }
|
|
1162
|
+
}, [searchScope, trimmedQuery])
|
|
1163
|
+
|
|
1164
|
+
const contentHitBySession = new Map()
|
|
1165
|
+
if (searchScope === 'content' && trimmedQuery && contentSearch.hits) {
|
|
1166
|
+
contentSearch.hits.forEach((hit, index) => {
|
|
1167
|
+
if (!contentHitBySession.has(hit.sessionId)) contentHitBySession.set(hit.sessionId, { ...hit, rank: index })
|
|
1168
|
+
})
|
|
941
1169
|
}
|
|
942
1170
|
|
|
943
1171
|
const mergedById = new Map()
|
|
@@ -950,6 +1178,8 @@ window.__ModuleLoader__.load({
|
|
|
950
1178
|
updatedAt: clientRow.updatedAt ?? 0,
|
|
951
1179
|
createdAt: 0,
|
|
952
1180
|
running: Boolean(clientRow.running),
|
|
1181
|
+
pinned: clientPinnedOrder.has(id),
|
|
1182
|
+
pinnedRank: clientPinnedOrder.get(id) ?? -1,
|
|
953
1183
|
isSubagent: false,
|
|
954
1184
|
orphanSubagent: false,
|
|
955
1185
|
parentSessionId: null,
|
|
@@ -957,18 +1187,14 @@ window.__ModuleLoader__.load({
|
|
|
957
1187
|
sizeBytes: null,
|
|
958
1188
|
deletable: false,
|
|
959
1189
|
deleteReason: '正在核对会话持久化状态…',
|
|
960
|
-
workspaces:
|
|
1190
|
+
workspaces: [],
|
|
961
1191
|
})
|
|
962
1192
|
}
|
|
963
1193
|
for (const hRow of hostSessions.items ?? []) {
|
|
964
1194
|
const existing = mergedById.get(hRow.id)
|
|
965
|
-
const byCwd = hRow.cwd ? workspaceList.items.filter(item => item.path && item.path === hRow.cwd) : []
|
|
966
|
-
const wsList = existing?.workspaces?.length
|
|
967
|
-
? existing.workspaces
|
|
968
|
-
: (hRow.workspaces?.length
|
|
969
|
-
? hRow.workspaces
|
|
970
|
-
: (groups.get(hRow.id) ?? (hRow.rootSessionId ? groups.get(hRow.rootSessionId) : undefined) ?? byCwd))
|
|
971
1195
|
const fallbackTitle = hRow.isSubagent ? subagentLabel(hRow) : '未命名会话'
|
|
1196
|
+
const pinned = Boolean(hRow.pinned || clientPinnedOrder.has(hRow.id))
|
|
1197
|
+
const pinnedRank = hRow.pinnedRank >= 0 ? hRow.pinnedRank : (clientPinnedOrder.get(hRow.id) ?? -1)
|
|
972
1198
|
mergedById.set(hRow.id, {
|
|
973
1199
|
...(existing ?? {}),
|
|
974
1200
|
...hRow,
|
|
@@ -976,14 +1202,25 @@ window.__ModuleLoader__.load({
|
|
|
976
1202
|
cwd: existing?.cwd || hRow.cwd || '',
|
|
977
1203
|
updatedAt: existing?.updatedAt || hRow.createdAt || 0,
|
|
978
1204
|
running: Boolean(existing?.running || hRow.running),
|
|
979
|
-
|
|
1205
|
+
pinned,
|
|
1206
|
+
pinnedRank,
|
|
980
1207
|
})
|
|
981
1208
|
}
|
|
982
1209
|
|
|
983
1210
|
const allMerged = [...mergedById.values()]
|
|
1211
|
+
for (const row of allMerged) {
|
|
1212
|
+
const pathMatch = workspacesByPath.get(row.cwd)
|
|
1213
|
+
const inherited = !row.cwd ? groups.get(row.rootSessionId) : undefined
|
|
1214
|
+
// The live workspace projection supersedes the host session list's older memberships.
|
|
1215
|
+
row.workspaces = groups.get(row.id) ?? (pathMatch ? [pathMatch] : inherited)
|
|
1216
|
+
?? (workspacesReady ? [] : row.workspaces ?? [])
|
|
1217
|
+
row.orphanWorkspace = workspacesReady && Boolean(row.cwd) && row.workspaces.length === 0
|
|
1218
|
+
}
|
|
984
1219
|
const inSelectedWorkspace = row => {
|
|
985
|
-
|
|
986
|
-
|
|
1220
|
+
if (workspace === 'all') return true
|
|
1221
|
+
if (workspace === 'orphan') return row.orphanWorkspace
|
|
1222
|
+
if (workspace === 'none') return row.workspaces.length === 0 && !row.orphanWorkspace
|
|
1223
|
+
return row.workspaces.some(item => item.workspaceId === workspace)
|
|
987
1224
|
}
|
|
988
1225
|
|
|
989
1226
|
// Counts on the segmented tabs reflect workspace filter so numbers always match what you click into.
|
|
@@ -992,8 +1229,10 @@ window.__ModuleLoader__.load({
|
|
|
992
1229
|
const archivedCount = wsScoped.filter(item => !item.isSubagent && archived.has(item.id)).length
|
|
993
1230
|
const subagentCount = wsScoped.filter(item => item.isSubagent).length
|
|
994
1231
|
|
|
1232
|
+
const usingContentSearch = searchScope === 'content' && Boolean(trimmedQuery)
|
|
995
1233
|
const rows = wsScoped.flatMap(row => {
|
|
996
1234
|
const isArchived = archived.has(row.id)
|
|
1235
|
+
const isPinned = Boolean(row.pinned) && !isArchived
|
|
997
1236
|
if (viewMode === 'active') {
|
|
998
1237
|
if ((row.isSubagent && !row.orphanSubagent) || isArchived) return []
|
|
999
1238
|
} else if (viewMode === 'archived') {
|
|
@@ -1002,24 +1241,38 @@ window.__ModuleLoader__.load({
|
|
|
1002
1241
|
if (!row.isSubagent) return []
|
|
1003
1242
|
}
|
|
1004
1243
|
const subagents = (row.descendantSubagentIds ?? []).map(subId => mergedById.get(subId)).filter(Boolean)
|
|
1005
|
-
|
|
1006
|
-
|
|
1244
|
+
let matchSnippet = ''
|
|
1245
|
+
let matchRank = -1
|
|
1246
|
+
if (usingContentSearch) {
|
|
1247
|
+
const directHit = contentHitBySession.get(row.id)
|
|
1248
|
+
const subHit = !directHit && subagents.map(sub => contentHitBySession.get(sub.id)).find(Boolean)
|
|
1249
|
+
const hit = directHit || subHit
|
|
1250
|
+
if (!hit) return []
|
|
1251
|
+
matchSnippet = hit.snippet || ''
|
|
1252
|
+
matchRank = hit.rank
|
|
1253
|
+
} else {
|
|
1254
|
+
const subagentText = subagents.map(sub => `${sub.id} ${sub.agentPreset ?? ''}`).join(' ')
|
|
1255
|
+
if (!matches(query, row.title, row.id, row.agentPreset ?? '', subagentText)) return []
|
|
1256
|
+
}
|
|
1007
1257
|
const ownBytes = Number.isFinite(row.sizeBytes) ? row.sizeBytes : 0
|
|
1008
1258
|
const subBytes = subagents.reduce((sum, sub) => sum + (Number.isFinite(sub.sizeBytes) ? sub.sizeBytes : 0), 0)
|
|
1009
1259
|
const totalBytes = Number.isFinite(row.sizeBytes) || subagents.some(sub => Number.isFinite(sub.sizeBytes))
|
|
1010
1260
|
? ownBytes + subBytes : null
|
|
1011
|
-
return [{ row, id: row.id, title: row.title, workspaces: row.workspaces ?? [], isArchived, subagents, totalBytes }]
|
|
1261
|
+
return [{ row, id: row.id, title: row.title, workspaces: row.workspaces ?? [], isArchived, isPinned, matchSnippet, matchRank, subagents, totalBytes }]
|
|
1012
1262
|
}).sort((a, b) => {
|
|
1263
|
+
if (usingContentSearch) return a.matchRank - b.matchRank
|
|
1013
1264
|
const recentDiff = (b.row.updatedAt || b.row.createdAt) - (a.row.updatedAt || a.row.createdAt)
|
|
1014
1265
|
if (sortBy === 'oldest') return ((a.row.createdAt || a.row.updatedAt) - (b.row.createdAt || b.row.updatedAt)) || -recentDiff
|
|
1015
1266
|
if (sortBy === 'size') return ((b.totalBytes ?? -1) - (a.totalBytes ?? -1)) || recentDiff
|
|
1016
1267
|
if (sortBy === 'subagents') return (b.subagents.length - a.subagents.length) || recentDiff
|
|
1268
|
+
if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1
|
|
1269
|
+
if (a.isPinned && b.isPinned && a.row.pinnedRank !== b.row.pinnedRank) return a.row.pinnedRank - b.row.pinnedRank
|
|
1017
1270
|
return recentDiff
|
|
1018
1271
|
})
|
|
1019
1272
|
|
|
1020
|
-
const hasActiveFilter = Boolean(
|
|
1021
|
-
const resetFilters = () => { search(''); selectWorkspace('all'); setSortBy('recent') }
|
|
1022
|
-
const scroller = useInfiniteScroll(rows.length, `${viewMode}\n${query}\n${workspace}\n${sortBy}`, 50)
|
|
1273
|
+
const hasActiveFilter = Boolean(trimmedQuery) || searchScope !== 'title' || workspace !== 'all' || sortBy !== 'recent'
|
|
1274
|
+
const resetFilters = () => { search(''); setSearchScope('title'); selectWorkspace('all'); setSortBy('recent') }
|
|
1275
|
+
const scroller = useInfiniteScroll(rows.length, `${viewMode}\n${searchScope}\n${query}\n${workspace}\n${sortBy}`, 50)
|
|
1023
1276
|
const visibleRows = rows.slice(0, scroller.limit)
|
|
1024
1277
|
const openKeys = visibleRows.filter(item => disclosure.isOpen(item.id)).map(item => item.id)
|
|
1025
1278
|
|
|
@@ -1118,6 +1371,7 @@ window.__ModuleLoader__.load({
|
|
|
1118
1371
|
return h('div', { className: 'dpt-panel' },
|
|
1119
1372
|
feedback(host.error, true, host.dismiss),
|
|
1120
1373
|
feedback(hostSessions.error, true, hostSessions.dismissError),
|
|
1374
|
+
feedback(contentSearch.error, true, () => setContentSearch(previous => ({ ...previous, error: '' }))),
|
|
1121
1375
|
feedback(status.error ? status.message : '', true, dismiss),
|
|
1122
1376
|
h('div', { className: 'dpt-toolbar' },
|
|
1123
1377
|
h(Segmented, {
|
|
@@ -1130,11 +1384,16 @@ window.__ModuleLoader__.load({
|
|
|
1130
1384
|
],
|
|
1131
1385
|
}),
|
|
1132
1386
|
h('div', { className: 'dpt-toolbar-right' },
|
|
1133
|
-
filterInput('搜索会话标题', query, search),
|
|
1387
|
+
filterInput(searchScope === 'content' ? '搜索会话正文' : '搜索会话标题', query, search),
|
|
1388
|
+
host.info?.sessionSearch !== false && pick('搜索范围', searchScope, setSearchScope, [
|
|
1389
|
+
option('title', '搜标题'),
|
|
1390
|
+
option('content', '搜正文'),
|
|
1391
|
+
]),
|
|
1134
1392
|
pick('工作区', workspace, selectWorkspace, [
|
|
1135
1393
|
option('all', '全部工作区'),
|
|
1136
|
-
option('none', '
|
|
1137
|
-
|
|
1394
|
+
option('none', t('ungrouped')),
|
|
1395
|
+
option('orphan', t('workspaceDeleted')),
|
|
1396
|
+
...workspaceList.items.map(item => option(item.workspaceId, workspaceTitle(item, t))),
|
|
1138
1397
|
]),
|
|
1139
1398
|
pick('排序方式', sortBy, setSortBy, [
|
|
1140
1399
|
option('recent', '最近活跃'),
|
|
@@ -1145,14 +1404,17 @@ window.__ModuleLoader__.load({
|
|
|
1145
1404
|
hasActiveFilter && rows.length > 0 && button('重置筛选', resetFilters, { icon: 'x', iconSize: 13 }),
|
|
1146
1405
|
openKeys.length >= 2 && button('收起全部', () => disclosure.collapseAll(openKeys), { icon: 'chevrons-down-up', iconSize: 13 }),
|
|
1147
1406
|
iconButton('刷新会话', 'refresh-cw', silentRefresh, {
|
|
1148
|
-
iconClass: (refreshing || hostSessions.reloading) ? 'dpt-spin' : '',
|
|
1407
|
+
iconClass: (refreshing || hostSessions.reloading || contentSearch.loading) ? 'dpt-spin' : '',
|
|
1149
1408
|
disabled: refreshing, 'aria-busy': refreshing,
|
|
1150
1409
|
}))),
|
|
1151
1410
|
rows.length === 0
|
|
1152
|
-
? empty(
|
|
1411
|
+
? empty(usingContentSearch && contentSearch.loading
|
|
1412
|
+
? '正在检索会话正文…'
|
|
1413
|
+
: (sessionList.phase === 'ready' ? '没有符合条件的会话。' : '正在读取会话…'),
|
|
1414
|
+
sessionList.phase === 'ready' && hasActiveFilter ? resetFilters : undefined)
|
|
1153
1415
|
: h('ul', { className: 'dpt-card', 'data-selecting': selectedRows.length > 0 || undefined },
|
|
1154
1416
|
visibleRows.map((item, index) => h(SessionRow, {
|
|
1155
|
-
...item, key: item.id, navigation, notify: toast.show,
|
|
1417
|
+
...item, key: item.id, navigation, notify: toast.show, workspaceColors, t,
|
|
1156
1418
|
disclosure: disclosure(item.id),
|
|
1157
1419
|
selectable: {
|
|
1158
1420
|
checked: selectedIds.has(item.id),
|
|
@@ -1160,6 +1422,7 @@ window.__ModuleLoader__.load({
|
|
|
1160
1422
|
onChange: (checked, shiftKey) => toggleSelect(index, item.id, checked, shiftKey),
|
|
1161
1423
|
},
|
|
1162
1424
|
onArchived: message => { toast.show(message); void hostSessions.reload() },
|
|
1425
|
+
onPinned: message => { toast.show(message); void silentRefresh() },
|
|
1163
1426
|
onDeleted: handleDeleted,
|
|
1164
1427
|
})),
|
|
1165
1428
|
scroller.sentinel),
|
|
@@ -1253,25 +1516,39 @@ window.__ModuleLoader__.load({
|
|
|
1253
1516
|
return { name: name?.trim() ?? '', transport, values }
|
|
1254
1517
|
}
|
|
1255
1518
|
|
|
1256
|
-
function McpListFields({ fieldName, label, values, update, pairs }) {
|
|
1519
|
+
function McpListFields({ fieldName, label, values, update, pairs, credentialNames = [], bearerHint = false }) {
|
|
1257
1520
|
const rows = values ?? []
|
|
1258
1521
|
function change(index, column, value) {
|
|
1259
1522
|
update(rows.map((row, i) => i === index ? row.map((part, j) => j === column ? value : part) : row))
|
|
1260
1523
|
}
|
|
1524
|
+
function addFromCredential(credName) {
|
|
1525
|
+
if (!credName) return
|
|
1526
|
+
const ref = bearerHint ? `Bearer \${credential:${credName}}` : `\${credential:${credName}}`
|
|
1527
|
+
const defaultKey = bearerHint ? 'Authorization' : credName
|
|
1528
|
+
update([...rows, [defaultKey, ref]])
|
|
1529
|
+
}
|
|
1261
1530
|
return h('div', { className: 'dpt-edit' },
|
|
1262
1531
|
h('span', { className: 'dpt-label' }, label),
|
|
1263
1532
|
rows.map((row, index) => h('div', { key: index, className: 'dpt-argument-row' },
|
|
1264
1533
|
row.map((part, column) => h('input', {
|
|
1265
1534
|
key: column, className: 'dpt-mono', dir: 'ltr', spellCheck: false,
|
|
1266
1535
|
'aria-label': pairs ? `${fieldName} ${index + 1} ${column ? '值' : '名称'}` : `参数 ${index + 1}`,
|
|
1267
|
-
placeholder: pairs ? column ? 'Bearer ${credential:MCP_TOKEN}' : '名称' : '参数',
|
|
1536
|
+
placeholder: pairs ? column ? (bearerHint ? 'Bearer ${credential:MCP_TOKEN}' : '${credential:MCP_TOKEN}') : '名称' : '参数',
|
|
1268
1537
|
value: part, onChange: e => change(index, column, e.target.value),
|
|
1269
1538
|
})),
|
|
1270
1539
|
button('', () => update(rows.filter((_, i) => i !== index)), { icon: 'x', iconSize: 13, className: 'dpt-danger', 'aria-label': `移除${fieldName} ${index + 1}` }))),
|
|
1271
|
-
h('div', { className: 'dpt-actions' },
|
|
1540
|
+
h('div', { className: 'dpt-actions' },
|
|
1541
|
+
pairs && credentialNames.length > 0 && h('select', {
|
|
1542
|
+
'aria-label': `插入已有凭据到${fieldName}`,
|
|
1543
|
+
value: '',
|
|
1544
|
+
onChange: e => { addFromCredential(e.target.value); e.target.value = '' },
|
|
1545
|
+
},
|
|
1546
|
+
option('', '插入已有凭据…'),
|
|
1547
|
+
...credentialNames.map(cred => option(cred, cred))),
|
|
1548
|
+
button(`添加${fieldName}`, () => update([...rows, pairs ? ['', ''] : ['']]), { icon: 'plus', iconSize: 13 })))
|
|
1272
1549
|
}
|
|
1273
1550
|
|
|
1274
|
-
function McpEditor({ row, revision, close, saved }) {
|
|
1551
|
+
function McpEditor({ row, revision, credentialNames = [], close, saved }) {
|
|
1275
1552
|
const [status, run, dismiss] = useAction()
|
|
1276
1553
|
const [mode, setMode] = useState('form')
|
|
1277
1554
|
const [name, setName] = useState(row?.name ?? '')
|
|
@@ -1355,10 +1632,10 @@ window.__ModuleLoader__.load({
|
|
|
1355
1632
|
transport === 'stdio' ? h(React.Fragment, null,
|
|
1356
1633
|
input('command', '可执行文件', 'node 或 node.exe'), input('cwd', '启动目录(绝对路径,可选)', ''),
|
|
1357
1634
|
h(McpListFields, { fieldName: '参数', label: '进程参数', values: values.args, update: value => set('args', value) }),
|
|
1358
|
-
h(McpListFields, { fieldName: '环境变量', label: '环境变量 · DSH 凭据引用', values: values.env, pairs: true, update: value => set('env', value) }))
|
|
1635
|
+
h(McpListFields, { fieldName: '环境变量', label: '环境变量 · DSH 凭据引用', values: values.env, pairs: true, credentialNames, update: value => set('env', value) }))
|
|
1359
1636
|
: h(React.Fragment, null,
|
|
1360
1637
|
input('url', 'MCP 地址', 'https://example.com/mcp', 'url'),
|
|
1361
|
-
h(McpListFields, { fieldName: '请求头', label: '请求头 · DSH 凭据引用', values: values.headers, pairs: true, update: value => set('headers', value) }))),
|
|
1638
|
+
h(McpListFields, { fieldName: '请求头', label: '请求头 · DSH 凭据引用', values: values.headers, pairs: true, bearerHint: true, credentialNames, update: value => set('headers', value) }))),
|
|
1362
1639
|
feedback(modeError, true, () => setModeError('')), feedback(status.message, status.error, dismiss),
|
|
1363
1640
|
h('div', { className: 'dpt-actions' },
|
|
1364
1641
|
button('取消编辑', close, { disabled: status.busy }),
|
|
@@ -1402,7 +1679,154 @@ window.__ModuleLoader__.load({
|
|
|
1402
1679
|
return { view, error, reloading, refresh: () => refresh(undefined, true), dismissError: () => setError('') }
|
|
1403
1680
|
}
|
|
1404
1681
|
|
|
1405
|
-
|
|
1682
|
+
const credentialSources = { file: '凭据文件', env: '环境变量', 'project-env': '项目 .env', 'user-env': '用户 .env' }
|
|
1683
|
+
|
|
1684
|
+
function CredentialRow({ row, disclosure, onUpdated, notify }) {
|
|
1685
|
+
const [editing, setEditing] = useState(false)
|
|
1686
|
+
const [value, setValue] = useState('')
|
|
1687
|
+
const [removal, setRemoval] = useState(false)
|
|
1688
|
+
const [status, run, dismiss] = useAction()
|
|
1689
|
+
|
|
1690
|
+
async function copyRef() {
|
|
1691
|
+
const ref = `\${credential:${row.name}}`
|
|
1692
|
+
try {
|
|
1693
|
+
if (!await writeClipboard(ref)) throw new Error('clipboard unavailable')
|
|
1694
|
+
notify(`已复制 ${ref}`)
|
|
1695
|
+
} catch {
|
|
1696
|
+
notify('无法访问剪贴板,请手动复制凭据引用。', { error: true })
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
const missing = !row.configured
|
|
1701
|
+
const detailParts = [
|
|
1702
|
+
row.source ? credentialSources[row.source] ?? row.source : '尚未配置值',
|
|
1703
|
+
row.referencedBy?.length > 0 ? `被 ${row.referencedBy.join('、')} 引用` : '',
|
|
1704
|
+
].filter(Boolean)
|
|
1705
|
+
|
|
1706
|
+
const quickActions = h(React.Fragment, null,
|
|
1707
|
+
iconButton(`复制 ${row.name} 引用`, 'copy', copyRef, {
|
|
1708
|
+
className: 'dpt-row-icon-btn', iconSize: 13, title: `复制 \${credential:${row.name}}`,
|
|
1709
|
+
}),
|
|
1710
|
+
row.writable && iconButton(`更新 ${row.name}`, 'square-pen', () => { setEditing(true); disclosure.open() }, {
|
|
1711
|
+
className: 'dpt-row-icon-btn', iconSize: 13, title: missing ? '设置凭据值' : '更新凭据值', disabled: status.busy,
|
|
1712
|
+
}))
|
|
1713
|
+
|
|
1714
|
+
return h(DisclosureRow, {
|
|
1715
|
+
'data-credential-name': row.name,
|
|
1716
|
+
title: row.name,
|
|
1717
|
+
tag: row.masked || (missing ? '未设置' : undefined),
|
|
1718
|
+
detail: detailParts.join(' · '),
|
|
1719
|
+
badge: missing ? '缺失' : '已配置',
|
|
1720
|
+
tone: missing ? 'attention' : 'ready',
|
|
1721
|
+
quickActions,
|
|
1722
|
+
...disclosure,
|
|
1723
|
+
},
|
|
1724
|
+
h('div', { className: 'dpt-drawer-bar' },
|
|
1725
|
+
h('div', { className: 'dpt-drawer-facts' },
|
|
1726
|
+
h('span', null, '引用模板', code(`\${credential:${row.name}}`)),
|
|
1727
|
+
row.source && h('span', null, '当前来源', h('strong', null, credentialSources[row.source] ?? row.source)),
|
|
1728
|
+
row.masked && h('span', null, '脱敏预览', code(row.masked))),
|
|
1729
|
+
h('div', { className: 'dpt-actions' },
|
|
1730
|
+
button('复制引用', copyRef, { icon: 'copy', iconSize: 13 }),
|
|
1731
|
+
row.writable && !editing && button(missing ? '设置值' : '更新值', () => setEditing(true), { icon: 'square-pen', disabled: status.busy }),
|
|
1732
|
+
row.source === 'file' && row.writable && button('移除', () => setRemoval(true), { icon: 'trash', className: 'dpt-danger', disabled: status.busy }))),
|
|
1733
|
+
row.referencedBy?.length > 0 && muted(`引用的 MCP 服务器:${row.referencedBy.join('、')}`),
|
|
1734
|
+
editing && h('form', {
|
|
1735
|
+
className: 'dpt-form dpt-drawer-split',
|
|
1736
|
+
onSubmit: e => {
|
|
1737
|
+
e.preventDefault()
|
|
1738
|
+
void run(async () => {
|
|
1739
|
+
await request('credentials', { action: 'set', name: row.name, value })
|
|
1740
|
+
setValue(''); setEditing(false)
|
|
1741
|
+
notify(`凭据 ${row.name} 已更新`)
|
|
1742
|
+
await onUpdated()
|
|
1743
|
+
})
|
|
1744
|
+
},
|
|
1745
|
+
},
|
|
1746
|
+
field('新凭据值(仅写入 DSH 凭据文件,不回显原文)', h('input', {
|
|
1747
|
+
type: 'password', autoComplete: 'new-password', required: true, autoFocus: true,
|
|
1748
|
+
dir: 'ltr', className: 'dpt-mono', value, onChange: e => setValue(e.target.value),
|
|
1749
|
+
})),
|
|
1750
|
+
h('div', { className: 'dpt-actions' },
|
|
1751
|
+
button('取消', () => { setEditing(false); setValue(''); dismiss() }, { disabled: status.busy }),
|
|
1752
|
+
primary('保存凭据', undefined, { type: 'submit', icon: 'check', disabled: status.busy, 'aria-busy': status.busy }))),
|
|
1753
|
+
feedback(status.error ? status.message : '', true, dismiss),
|
|
1754
|
+
removal && h(Confirm, {
|
|
1755
|
+
title: `移除凭据 ${row.name}`,
|
|
1756
|
+
label: '确认移除凭据',
|
|
1757
|
+
removed: [`DSH 托管凭据文件中的 ${row.name}`],
|
|
1758
|
+
preserved: ['进程环境变量与 .env 文件中的同名项(若存在将自动回退生效)', '引用该凭据的 MCP 配置条目'],
|
|
1759
|
+
close: () => setRemoval(false),
|
|
1760
|
+
confirm: async () => {
|
|
1761
|
+
const result = await request('credentials', { action: 'unset', name: row.name, confirm: row.name })
|
|
1762
|
+
setRemoval(false)
|
|
1763
|
+
notify(result.credential?.configured
|
|
1764
|
+
? `已从凭据文件移除 ${row.name}(当前由${credentialSources[result.credential.source] ?? result.credential.source}继续提供)`
|
|
1765
|
+
: `已移除凭据 ${row.name}`)
|
|
1766
|
+
await onUpdated()
|
|
1767
|
+
},
|
|
1768
|
+
}))
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
function CredentialsPanel({ rows, error, onRefresh, onUpdated, notify }) {
|
|
1772
|
+
const [name, setName] = useState('')
|
|
1773
|
+
const [value, setValue] = useState('')
|
|
1774
|
+
const [lookupResult, setLookupResult] = useState(null)
|
|
1775
|
+
const [status, run, dismiss] = useAction()
|
|
1776
|
+
const disclosure = useDisclosure()
|
|
1777
|
+
const items = rows ?? []
|
|
1778
|
+
const missingCount = items.filter(item => !item.configured).length
|
|
1779
|
+
|
|
1780
|
+
async function saveNew() {
|
|
1781
|
+
const cleanName = name.trim()
|
|
1782
|
+
await request('credentials', { action: 'set', name: cleanName, value })
|
|
1783
|
+
setName(''); setValue(''); setLookupResult(null)
|
|
1784
|
+
notify(`凭据 ${cleanName} 已保存`)
|
|
1785
|
+
await onUpdated()
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
async function checkName() {
|
|
1789
|
+
const cleanName = name.trim()
|
|
1790
|
+
if (!cleanName) return
|
|
1791
|
+
await run(async () => {
|
|
1792
|
+
const result = await request('credentials', { action: 'describe', name: cleanName })
|
|
1793
|
+
setLookupResult(result.credential)
|
|
1794
|
+
})
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
return h(PanelSection, {
|
|
1798
|
+
title: 'DSH 凭据',
|
|
1799
|
+
summary: rows ? `${items.length} 项${missingCount > 0 ? ` · ${missingCount} 项缺失` : ''} · 仅写不读` : undefined,
|
|
1800
|
+
},
|
|
1801
|
+
h('div', { className: 'dpt-card dpt-empty dpt-edit' },
|
|
1802
|
+
h('form', { className: 'dpt-form', onSubmit: e => { e.preventDefault(); void run(saveNew) } },
|
|
1803
|
+
h('div', { className: 'dpt-form-row' },
|
|
1804
|
+
field('凭据名称(环境变量标识符)', h('input', {
|
|
1805
|
+
value: name, required: true, dir: 'ltr', className: 'dpt-mono', spellCheck: false, autoComplete: 'off',
|
|
1806
|
+
placeholder: '例如 MCP_GITHUB_TOKEN',
|
|
1807
|
+
onChange: e => { setName(e.target.value); setLookupResult(null) },
|
|
1808
|
+
})),
|
|
1809
|
+
field('凭据值(不回显原文)', h('input', {
|
|
1810
|
+
type: 'password', autoComplete: 'new-password', required: true, dir: 'ltr', className: 'dpt-mono',
|
|
1811
|
+
placeholder: '输入密钥或令牌', value, onChange: e => setValue(e.target.value),
|
|
1812
|
+
}))),
|
|
1813
|
+
h('div', { className: 'dpt-actions' },
|
|
1814
|
+
button('查询环境变量状态', checkName, { icon: 'eye', disabled: status.busy || !name.trim() }),
|
|
1815
|
+
primary('保存凭据', undefined, { type: 'submit', icon: 'check', disabled: status.busy, 'aria-busy': status.busy }))),
|
|
1816
|
+
lookupResult && muted(lookupResult.configured
|
|
1817
|
+
? `${lookupResult.name} 已配置(来源:${credentialSources[lookupResult.source] ?? lookupResult.source}${lookupResult.masked ? ` · ${lookupResult.masked}` : ''})`
|
|
1818
|
+
: `${lookupResult.name} 尚未配置,可直接填写上方凭据值保存。`),
|
|
1819
|
+
feedback(error, true, onRefresh),
|
|
1820
|
+
feedback(status.error ? status.message : '', true, dismiss)),
|
|
1821
|
+
items.length > 0
|
|
1822
|
+
? h('ul', { className: 'dpt-card' }, items.map(row => h(CredentialRow, {
|
|
1823
|
+
key: row.name, row, notify, onUpdated,
|
|
1824
|
+
disclosure: disclosure(row.name, !row.configured),
|
|
1825
|
+
})))
|
|
1826
|
+
: empty(rows ? '尚未在 DSH 凭据文件中保存凭据,也没有待配置的 MCP 凭据引用。' : error ? '凭据列表暂不可用。' : '正在读取凭据状态…'))
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
function McpRow({ row, revision, credentialNames, refresh, removed, disclosure, onProbed, notify }) {
|
|
1406
1830
|
const [editing, setEditing] = useState(null)
|
|
1407
1831
|
const [removal, setRemoval] = useState(null)
|
|
1408
1832
|
const [probedTools, setProbedTools] = useState(null)
|
|
@@ -1501,7 +1925,7 @@ window.__ModuleLoader__.load({
|
|
|
1501
1925
|
issue && muted(issue),
|
|
1502
1926
|
feedback(status.error ? status.message : '', true, dismiss),
|
|
1503
1927
|
editing && h('div', { className: 'dpt-drawer-split' }, h(McpEditor, {
|
|
1504
|
-
row, ...editing, close: () => setEditing(null), saved: message => {
|
|
1928
|
+
row, ...editing, credentialNames, close: () => setEditing(null), saved: message => {
|
|
1505
1929
|
dismiss(); notify(message); setEditing(null); void refresh()
|
|
1506
1930
|
},
|
|
1507
1931
|
})),
|
|
@@ -1523,12 +1947,35 @@ window.__ModuleLoader__.load({
|
|
|
1523
1947
|
const [statusFilter, setStatusFilter] = useState('all')
|
|
1524
1948
|
const [probedByServer, setProbedByServer] = useState({})
|
|
1525
1949
|
const [editor, setEditor] = useState(null)
|
|
1950
|
+
const [credentialsOpen, setCredentialsOpen] = useState(false)
|
|
1951
|
+
const [credentials, setCredentials] = useState(null)
|
|
1952
|
+
const [credentialsError, setCredentialsError] = useState('')
|
|
1526
1953
|
const disclosure = useDisclosure()
|
|
1527
1954
|
const rows = (view?.servers ?? []).filter(row => row.source !== 'retired')
|
|
1528
1955
|
const connectedCount = rows.filter(row => row.status === 'connected').length
|
|
1529
1956
|
const issueCount = rows.filter(row => row.enabled && mcpIssues[row.status]).length
|
|
1530
1957
|
const disabledCount = rows.filter(row => !row.enabled).length
|
|
1531
1958
|
|
|
1959
|
+
async function reloadCredentials(signal) {
|
|
1960
|
+
if (host.info?.credentials === false) return
|
|
1961
|
+
try {
|
|
1962
|
+
const result = await request('credentials', { action: 'list' }, signal)
|
|
1963
|
+
if (!signal?.aborted) { setCredentials(result.credentials); setCredentialsError('') }
|
|
1964
|
+
} catch (err) {
|
|
1965
|
+
if (!signal?.aborted) setCredentialsError(err.message)
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
useEffect(() => {
|
|
1970
|
+
if (host.info?.credentials === false) return
|
|
1971
|
+
const abort = new AbortController()
|
|
1972
|
+
void reloadCredentials(abort.signal)
|
|
1973
|
+
return () => abort.abort()
|
|
1974
|
+
}, [host.info?.credentials, view?.revision])
|
|
1975
|
+
|
|
1976
|
+
const credentialNames = (credentials ?? []).map(item => item.name)
|
|
1977
|
+
const missingCredentials = (credentials ?? []).filter(item => !item.configured).length
|
|
1978
|
+
|
|
1532
1979
|
const filtered = rows.filter(row => {
|
|
1533
1980
|
if (sourceFilter !== 'all' && row.source !== sourceFilter) return false
|
|
1534
1981
|
if (statusFilter === 'connected' && row.status !== 'connected') return false
|
|
@@ -1566,11 +2013,17 @@ window.__ModuleLoader__.load({
|
|
|
1566
2013
|
]),
|
|
1567
2014
|
hasActiveFilter && filtered.length > 0 && button('重置筛选', resetFilters, { icon: 'x', iconSize: 13 }),
|
|
1568
2015
|
openKeys.length >= 2 && button('收起全部', () => disclosure.collapseAll(openKeys), { icon: 'chevrons-down-up', iconSize: 13 }),
|
|
1569
|
-
iconButton('刷新 MCP', 'refresh-cw', refresh, { iconClass: reloading ? 'dpt-spin' : '', disabled: reloading, 'aria-busy': reloading }),
|
|
2016
|
+
iconButton('刷新 MCP', 'refresh-cw', () => { void refresh(); void reloadCredentials() }, { iconClass: reloading ? 'dpt-spin' : '', disabled: reloading, 'aria-busy': reloading }),
|
|
2017
|
+
host.info?.credentials !== false && button(missingCredentials > 0 ? `凭据管理 (${missingCredentials})` : '凭据管理', () => setCredentialsOpen(!credentialsOpen), { icon: 'key-round', 'aria-expanded': credentialsOpen }),
|
|
1570
2018
|
primary('新增服务器', () => setEditor({ revision: view.revision }), { icon: 'plus', disabled: !view?.writable || Boolean(editor) }))),
|
|
2019
|
+
credentialsOpen && h(CredentialsPanel, {
|
|
2020
|
+
rows: credentials, error: credentialsError, notify: toast.show,
|
|
2021
|
+
onRefresh: () => void reloadCredentials(),
|
|
2022
|
+
onUpdated: async () => { await Promise.all([reloadCredentials(), refresh()]) },
|
|
2023
|
+
}),
|
|
1571
2024
|
editor && h('div', { className: 'dpt-card dpt-empty' }, h(McpEditor, {
|
|
1572
|
-
...editor, close: () => setEditor(null), saved: message => {
|
|
1573
|
-
toast.show(message); setEditor(null); void refresh()
|
|
2025
|
+
...editor, credentialNames, close: () => setEditor(null), saved: message => {
|
|
2026
|
+
toast.show(message); setEditor(null); void refresh(); void reloadCredentials()
|
|
1574
2027
|
},
|
|
1575
2028
|
})),
|
|
1576
2029
|
filtered.length ? h('ul', { className: 'dpt-card' }, (() => {
|
|
@@ -1578,10 +2031,10 @@ window.__ModuleLoader__.load({
|
|
|
1578
2031
|
return groups.map(([source, title, group]) => h(React.Fragment, { key: source },
|
|
1579
2032
|
groups.length > 1 && h('li', { className: 'dpt-subhead' }, title),
|
|
1580
2033
|
group.map(row => h(McpRow, {
|
|
1581
|
-
key: row.name, row, revision: view.revision, refresh, notify: toast.show,
|
|
2034
|
+
key: row.name, row, revision: view.revision, credentialNames, refresh, notify: toast.show,
|
|
1582
2035
|
disclosure: disclosure(row.name, Boolean(row.enabled && mcpIssues[row.status])),
|
|
1583
2036
|
onProbed: (serverName, names) => setProbedByServer(previous => ({ ...previous, [serverName]: names })),
|
|
1584
|
-
removed: name => toast.show(`已移除服务器 · ${name}`),
|
|
2037
|
+
removed: name => { toast.show(`已移除服务器 · ${name}`); void reloadCredentials() },
|
|
1585
2038
|
}))))
|
|
1586
2039
|
})(), scroller.sentinel)
|
|
1587
2040
|
: empty(rows.length ? '没有符合条件的 MCP 服务器。' : view ? '暂无 MCP 服务器,点击右上角「新增服务器」添加。' : error ? '服务器列表暂不可用。' : '正在读取 MCP 服务器…', rows.length && hasActiveFilter ? resetFilters : undefined))
|
|
@@ -1877,6 +2330,147 @@ window.__ModuleLoader__.load({
|
|
|
1877
2330
|
(!repositories || !repositories.length) && empty(repositories ? '尚未添加 Skill 仓库。' : failure ? '仓库列表暂不可用。' : '正在读取 Skill 仓库…'))
|
|
1878
2331
|
}
|
|
1879
2332
|
|
|
2333
|
+
function InstructionRow({ row, workspaceId, disclosure, refresh, notify }) {
|
|
2334
|
+
const [preview, setPreview] = useState(null)
|
|
2335
|
+
const [editing, setEditing] = useState(false)
|
|
2336
|
+
const [content, setContent] = useState('')
|
|
2337
|
+
const [removal, setRemoval] = useState(false)
|
|
2338
|
+
const [status, run, dismiss] = useAction()
|
|
2339
|
+
|
|
2340
|
+
async function openMode(startEditing) {
|
|
2341
|
+
await run(async () => {
|
|
2342
|
+
const data = await request('instructions', { action: 'preview', workspaceId, id: row.id })
|
|
2343
|
+
setPreview(data)
|
|
2344
|
+
setContent(data.content ?? '')
|
|
2345
|
+
setEditing(startEditing)
|
|
2346
|
+
disclosure.open()
|
|
2347
|
+
})
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2350
|
+
const detailParts = [
|
|
2351
|
+
row.scopeLabel,
|
|
2352
|
+
row.exists ? formatBytes(row.bytes) : '尚未创建,可一键新建',
|
|
2353
|
+
row.exists && row.mtimeMs > 0 ? formatShortTime(row.mtimeMs) : '',
|
|
2354
|
+
].filter(Boolean)
|
|
2355
|
+
|
|
2356
|
+
const badge = !row.exists ? '未创建' : row.symlink ? '符号链接' : row.editable ? '已生效' : '只读'
|
|
2357
|
+
const tone = !row.exists ? 'idle' : row.editable ? 'ready' : 'idle'
|
|
2358
|
+
|
|
2359
|
+
const quickActions = h(React.Fragment, null,
|
|
2360
|
+
row.exists && !row.symlink && iconButton(`预览 ${row.displayPath}`, 'eye', () => openMode(false), {
|
|
2361
|
+
className: 'dpt-row-icon-btn', iconSize: 13, title: '预览内容', disabled: status.busy,
|
|
2362
|
+
}),
|
|
2363
|
+
row.editable && iconButton(`${row.exists ? '编辑' : '创建'} ${row.displayPath}`, row.exists ? 'square-pen' : 'plus', () => openMode(true), {
|
|
2364
|
+
className: 'dpt-row-icon-btn', iconSize: 13, title: row.exists ? '编辑指令文件' : '创建指令文件', disabled: status.busy,
|
|
2365
|
+
}))
|
|
2366
|
+
|
|
2367
|
+
return h(DisclosureRow, {
|
|
2368
|
+
'data-instruction-id': row.id,
|
|
2369
|
+
title: row.displayPath,
|
|
2370
|
+
tag: row.localOverlay ? '本地覆盖' : undefined,
|
|
2371
|
+
detail: detailParts.join(' · '),
|
|
2372
|
+
badge,
|
|
2373
|
+
tone,
|
|
2374
|
+
quickActions,
|
|
2375
|
+
...disclosure,
|
|
2376
|
+
},
|
|
2377
|
+
h('div', { className: 'dpt-drawer-bar' },
|
|
2378
|
+
h('div', { className: 'dpt-drawer-facts' },
|
|
2379
|
+
h('span', null, '作用域', h('strong', null, row.scopeLabel)),
|
|
2380
|
+
row.exists && h('span', null, '大小', h('strong', null, formatBytes(row.bytes)))),
|
|
2381
|
+
h('div', { className: 'dpt-actions' },
|
|
2382
|
+
row.exists && !row.symlink && !preview && button('预览', () => openMode(false), { icon: 'eye', disabled: status.busy }),
|
|
2383
|
+
row.editable && !editing && button(row.exists ? '编辑' : '创建', () => openMode(true), { icon: row.exists ? 'square-pen' : 'plus', disabled: status.busy }),
|
|
2384
|
+
row.exists && row.editable && button('移除', () => run(async () => {
|
|
2385
|
+
const current = await request('instructions', { action: 'preview', workspaceId, id: row.id })
|
|
2386
|
+
setPreview(current); setEditing(false); setRemoval(true)
|
|
2387
|
+
}), { icon: 'trash', className: 'dpt-danger', disabled: status.busy }))),
|
|
2388
|
+
h(PathLine, { value: row.path, label: '文件路径' }),
|
|
2389
|
+
feedback(status.error ? status.message : '', true, dismiss),
|
|
2390
|
+
preview && h('div', { className: 'dpt-drawer-split' }, editing
|
|
2391
|
+
? h('form', {
|
|
2392
|
+
className: 'dpt-form',
|
|
2393
|
+
onSubmit: e => {
|
|
2394
|
+
e.preventDefault()
|
|
2395
|
+
void run(async () => {
|
|
2396
|
+
await request('instructions', { action: 'save', workspaceId, id: row.id, revision: preview.revision, content })
|
|
2397
|
+
setPreview(null); setEditing(false)
|
|
2398
|
+
notify(`${row.displayPath} 已保存`)
|
|
2399
|
+
await refresh()
|
|
2400
|
+
})
|
|
2401
|
+
},
|
|
2402
|
+
},
|
|
2403
|
+
field(`${row.displayPath} 内容`, h('textarea', {
|
|
2404
|
+
rows: 11, className: 'dpt-mono dpt-fixed-editor', value: content,
|
|
2405
|
+
onChange: e => setContent(e.target.value),
|
|
2406
|
+
})),
|
|
2407
|
+
h('div', { className: 'dpt-actions' },
|
|
2408
|
+
button('取消', () => { setEditing(false); if (!row.exists) setPreview(null); dismiss() }, { disabled: status.busy }),
|
|
2409
|
+
primary(row.exists ? '保存修改' : '创建文件', undefined, { type: 'submit', icon: 'check', disabled: status.busy, 'aria-busy': status.busy })))
|
|
2410
|
+
: h(React.Fragment, null,
|
|
2411
|
+
h('div', { className: 'dpt-drawer-bar' },
|
|
2412
|
+
muted(`${row.displayPath} · ${formatBytes(preview.bytes)}`),
|
|
2413
|
+
h('div', { className: 'dpt-actions' },
|
|
2414
|
+
row.editable && button('编辑', () => setEditing(true), { icon: 'square-pen' }),
|
|
2415
|
+
button('关闭预览', () => setPreview(null), { icon: 'x', iconSize: 13 }))),
|
|
2416
|
+
h('pre', { className: 'dpt-mono', dir: 'ltr' }, preview.content || '(空文件)'))),
|
|
2417
|
+
preview && removal && h(Confirm, {
|
|
2418
|
+
title: `移除 ${row.displayPath}`,
|
|
2419
|
+
label: '确认移除',
|
|
2420
|
+
removed: [`指令文件 ${row.displayPath}`],
|
|
2421
|
+
preserved: ['Profile 恢复目录中的原始文件备份', '其他工作区与全局指令文件'],
|
|
2422
|
+
close: () => setRemoval(false),
|
|
2423
|
+
confirm: async () => {
|
|
2424
|
+
const result = await request('instructions', { action: 'remove', workspaceId, id: row.id, revision: preview.revision, confirm: row.id })
|
|
2425
|
+
setRemoval(false); setPreview(null)
|
|
2426
|
+
notify(h(React.Fragment, null,
|
|
2427
|
+
h('p', null, `已移除 ${row.displayPath} 至恢复目录`),
|
|
2428
|
+
h(PathLine, { value: result.recovery, label: '恢复目录' })), { sticky: true })
|
|
2429
|
+
await refresh()
|
|
2430
|
+
},
|
|
2431
|
+
}))
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
function InstructionsPanel({ workspaceId, notify }) {
|
|
2435
|
+
const [rows, setRows] = useState(null)
|
|
2436
|
+
const [error, setError] = useState('')
|
|
2437
|
+
const disclosure = useDisclosure()
|
|
2438
|
+
const generation = useRef(0)
|
|
2439
|
+
|
|
2440
|
+
async function refresh(signal) {
|
|
2441
|
+
const current = ++generation.current
|
|
2442
|
+
try {
|
|
2443
|
+
const result = await request('instructions', { action: 'list', workspaceId }, signal)
|
|
2444
|
+
if (current === generation.current && !signal?.aborted) { setRows(result.instructions); setError('') }
|
|
2445
|
+
} catch (err) {
|
|
2446
|
+
if (current === generation.current && !signal?.aborted) setError(err.message)
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
useEffect(() => {
|
|
2451
|
+
const abort = new AbortController()
|
|
2452
|
+
setRows(null); setError('')
|
|
2453
|
+
void refresh(abort.signal)
|
|
2454
|
+
return () => { generation.current++; abort.abort() }
|
|
2455
|
+
}, [workspaceId])
|
|
2456
|
+
|
|
2457
|
+
const activeRows = (rows ?? []).filter(item => item.exists)
|
|
2458
|
+
const totalBytes = activeRows.reduce((sum, item) => sum + (item.bytes ?? 0), 0)
|
|
2459
|
+
|
|
2460
|
+
return h(PanelSection, {
|
|
2461
|
+
title: '指令文件',
|
|
2462
|
+
summary: rows ? `${activeRows.length} 个已生效${totalBytes > 0 ? ` · 共 ${formatBytes(totalBytes)}` : ''}` : undefined,
|
|
2463
|
+
},
|
|
2464
|
+
feedback(error, true, () => setError('')),
|
|
2465
|
+
rows?.length > 0
|
|
2466
|
+
? h('ul', { className: 'dpt-card' }, rows.map(row => h(InstructionRow, {
|
|
2467
|
+
key: `${workspaceId}:${row.id}`, row, workspaceId, notify,
|
|
2468
|
+
disclosure: disclosure(row.id),
|
|
2469
|
+
refresh: () => refresh(),
|
|
2470
|
+
})))
|
|
2471
|
+
: empty(rows ? '当前作用域没有可管理的指令文件。' : error ? '指令文件暂不可用。' : '正在扫描指令文件…'))
|
|
2472
|
+
}
|
|
2473
|
+
|
|
1880
2474
|
function SkillsPanel({ workspaceList, sessionList, navigation, host, toast }) {
|
|
1881
2475
|
const main = Object.values(sessionList.byId).find(item => item.retainedBy?.mainView > 0)
|
|
1882
2476
|
const current = workspaceList.items.find(item => item.sessionIds.includes(main?.id) || item.path === main?.cwd)
|
|
@@ -1890,6 +2484,7 @@ window.__ModuleLoader__.load({
|
|
|
1890
2484
|
const [reloading, setReloading] = useState(false)
|
|
1891
2485
|
const [importing, setImporting] = useState(false)
|
|
1892
2486
|
const [library, setLibrary] = useState(false)
|
|
2487
|
+
const [instructionsOpen, setInstructionsOpen] = useState(false)
|
|
1893
2488
|
const disclosure = useDisclosure()
|
|
1894
2489
|
const scope = { workspaceId: workspace, sessionId: main?.id }
|
|
1895
2490
|
const generation = useRef(0)
|
|
@@ -1973,8 +2568,10 @@ window.__ModuleLoader__.load({
|
|
|
1973
2568
|
hasActiveFilter && shown.length > 0 && button('重置筛选', resetFilters, { icon: 'x', iconSize: 13 }),
|
|
1974
2569
|
openKeys.length >= 2 && button('收起全部', () => disclosure.collapseAll(openKeys), { icon: 'chevrons-down-up', iconSize: 13 }),
|
|
1975
2570
|
iconButton('刷新 Skill', 'refresh-cw', () => refresh(undefined, true), { iconClass: reloading ? 'dpt-spin' : '', disabled: reloading, 'aria-busy': reloading }),
|
|
2571
|
+
host.info?.instructions !== false && button('指令文件', () => setInstructionsOpen(!instructionsOpen), { icon: 'file-text', 'aria-expanded': instructionsOpen }),
|
|
1976
2572
|
button('仓库管理', () => setLibrary(!library), { icon: 'git-branch', 'aria-expanded': library }),
|
|
1977
2573
|
primary('导入 Skill', () => setImporting(true), { icon: 'folder-plus', disabled: !rows || importing }))),
|
|
2574
|
+
instructionsOpen && h(InstructionsPanel, { key: workspace, workspaceId: workspace, notify: toast.show }),
|
|
1978
2575
|
library && h(SkillRepositoryPanel, {
|
|
1979
2576
|
key: workspace, scope, installedRows: rows, notify: toast.show,
|
|
1980
2577
|
onInstall: async name => { toast.show(`已从仓库安装 ${name}`); await refresh() },
|
|
@@ -1999,32 +2596,376 @@ window.__ModuleLoader__.load({
|
|
|
1999
2596
|
: empty(rows ? '没有符合条件的 Skill。' : error ? 'Skill 列表暂不可用。' : '正在发现 Skill…', rows && hasActiveFilter ? resetFilters : undefined))
|
|
2000
2597
|
}
|
|
2001
2598
|
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2599
|
+
const jobStates = { running: '运行中', stopping: '停止中', completed: '已完成', killed: '已停止', failed: '已失败' }
|
|
2600
|
+
const scheduleStates = { active: '活跃', paused: '已暂停', ended: '已结束' }
|
|
2601
|
+
const weekdayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
|
|
2602
|
+
|
|
2603
|
+
function formatDurationSeconds(seconds) {
|
|
2604
|
+
if (!Number.isFinite(seconds) || seconds <= 0) return ''
|
|
2605
|
+
if (seconds % 3600 === 0) return `${seconds / 3600} 小时`
|
|
2606
|
+
if (seconds % 60 === 0) return `${seconds / 60} 分钟`
|
|
2607
|
+
return `${seconds} 秒`
|
|
2608
|
+
}
|
|
2609
|
+
|
|
2610
|
+
function scheduleRuleLabel(item) {
|
|
2611
|
+
if (item.kind === 'after') return item.afterSeconds ? `${formatDurationSeconds(item.afterSeconds)}后单次` : '延时单次'
|
|
2612
|
+
if (item.kind === 'at') return '定时单次'
|
|
2613
|
+
if (item.kind === 'every') return item.everySeconds ? `每 ${formatDurationSeconds(item.everySeconds)}` : '循环间隔'
|
|
2614
|
+
if (item.kind === 'daily') return `每天 ${item.time ?? ''}`.trim()
|
|
2615
|
+
if (item.kind === 'weekly') {
|
|
2616
|
+
const days = (item.weekdays ?? []).map(day => weekdayNames[day] ?? day).join('、')
|
|
2617
|
+
return `每周 ${days} ${item.time ?? ''}`.trim()
|
|
2618
|
+
}
|
|
2619
|
+
if (item.kind === 'cron') return `Cron ${item.expression ?? ''}`.trim()
|
|
2620
|
+
if (item.kind === 'rrule') return `RRule`
|
|
2621
|
+
return item.kind
|
|
2622
|
+
}
|
|
2623
|
+
|
|
2624
|
+
function formatIsoShort(iso) {
|
|
2625
|
+
if (!iso) return ''
|
|
2626
|
+
const ts = Date.parse(iso)
|
|
2627
|
+
return Number.isFinite(ts) ? formatShortTime(ts) : iso
|
|
2628
|
+
}
|
|
2629
|
+
|
|
2630
|
+
function useTasksData(host) {
|
|
2631
|
+
const [jobs, setJobs] = useState(null)
|
|
2632
|
+
const [schedules, setSchedules] = useState(null)
|
|
2633
|
+
const [error, setError] = useState('')
|
|
2634
|
+
const [reloading, setReloading] = useState(false)
|
|
2635
|
+
const generation = useRef(0)
|
|
2636
|
+
|
|
2637
|
+
async function refresh(signal, manual = false) {
|
|
2638
|
+
const current = ++generation.current
|
|
2639
|
+
if (manual) setReloading(true)
|
|
2640
|
+
const errs = []
|
|
2641
|
+
const jobsPromise = host.info?.jobs === false
|
|
2642
|
+
? Promise.resolve(null)
|
|
2643
|
+
: request('jobs', { action: 'list' }, signal).then(res => res.jobs, err => { if (!signal?.aborted) errs.push(err.message); return null })
|
|
2644
|
+
const schedulePromise = host.info?.schedule === false
|
|
2645
|
+
? Promise.resolve(null)
|
|
2646
|
+
: request('schedule', { action: 'list' }, signal).then(res => res.schedules, err => { if (!signal?.aborted) errs.push(err.message); return null })
|
|
2647
|
+
try {
|
|
2648
|
+
const [nextJobs, nextSchedules] = await Promise.all([jobsPromise, schedulePromise])
|
|
2649
|
+
if (current === generation.current && !signal?.aborted) {
|
|
2650
|
+
if (nextJobs !== null) setJobs(nextJobs)
|
|
2651
|
+
if (nextSchedules !== null) setSchedules(nextSchedules)
|
|
2652
|
+
setError(errs.join(';'))
|
|
2653
|
+
}
|
|
2654
|
+
} finally {
|
|
2655
|
+
if (manual && current === generation.current) setReloading(false)
|
|
2656
|
+
}
|
|
2657
|
+
}
|
|
2658
|
+
|
|
2659
|
+
useEffect(() => {
|
|
2660
|
+
const abort = new AbortController()
|
|
2661
|
+
void refresh(abort.signal)
|
|
2662
|
+
const timer = setInterval(() => refresh(abort.signal), 2500)
|
|
2663
|
+
return () => { clearInterval(timer); abort.abort(); generation.current++ }
|
|
2664
|
+
}, [host.info?.jobs, host.info?.schedule])
|
|
2665
|
+
|
|
2666
|
+
return { jobs, schedules, error, reloading, refresh: () => refresh(undefined, true), dismissError: () => setError('') }
|
|
2667
|
+
}
|
|
2668
|
+
|
|
2669
|
+
function JobRow({ job, sessionTitle, navigation, disclosure, refresh, notify }) {
|
|
2670
|
+
const [output, setOutput] = useState(null)
|
|
2671
|
+
const [killing, setKilling] = useState(false)
|
|
2672
|
+
const [status, run, dismiss] = useAction()
|
|
2673
|
+
const live = job.status === 'running' || job.status === 'stopping'
|
|
2674
|
+
const tone = job.status === 'running' ? 'info' : job.status === 'completed' ? 'ready' : job.status === 'stopping' || job.status === 'failed' ? 'attention' : 'idle'
|
|
2675
|
+
|
|
2676
|
+
const detailParts = [
|
|
2677
|
+
job.owner ? `会话 ${sessionTitle || job.owner}` : '全局任务',
|
|
2678
|
+
job.progress || job.detail || '',
|
|
2679
|
+
job.output?.total > 0 ? `输出 ${formatBytes(job.output.total)}` : '',
|
|
2680
|
+
job.startedAt > 0 ? formatShortTime(job.startedAt) : '',
|
|
2681
|
+
].filter(Boolean)
|
|
2682
|
+
|
|
2683
|
+
async function loadOutput() {
|
|
2684
|
+
await run(async () => {
|
|
2685
|
+
const result = await request('jobs', { action: 'output', id: job.id })
|
|
2686
|
+
setOutput(result)
|
|
2687
|
+
disclosure.open()
|
|
2688
|
+
})
|
|
2689
|
+
}
|
|
2690
|
+
|
|
2691
|
+
const quickActions = h(React.Fragment, null,
|
|
2692
|
+
job.owner && iconButton(`打开所属会话 ${job.label}`, 'external-link', () => run(() => navigation.openSession(job.owner)), {
|
|
2693
|
+
className: 'dpt-row-icon-btn', iconSize: 13, title: '打开所属会话', disabled: status.busy,
|
|
2694
|
+
}),
|
|
2695
|
+
live
|
|
2696
|
+
? iconButton(`停止任务 ${job.label}`, 'square', () => setKilling(true), {
|
|
2697
|
+
className: 'dpt-row-icon-btn dpt-danger', iconSize: 13, title: '停止后台任务', disabled: status.busy,
|
|
2698
|
+
})
|
|
2699
|
+
: iconButton(`清除记录 ${job.label}`, 'trash', () => run(async () => {
|
|
2700
|
+
await request('jobs', { action: 'remove', id: job.id })
|
|
2701
|
+
notify('已清除后台任务记录')
|
|
2702
|
+
await refresh()
|
|
2703
|
+
}), {
|
|
2704
|
+
className: 'dpt-row-icon-btn', iconSize: 13, title: '清除已结束记录', disabled: status.busy,
|
|
2705
|
+
}))
|
|
2706
|
+
|
|
2707
|
+
return h(DisclosureRow, {
|
|
2708
|
+
'data-job-id': job.id,
|
|
2709
|
+
title: job.label,
|
|
2710
|
+
tag: job.kind,
|
|
2711
|
+
detail: detailParts.join(' · '),
|
|
2712
|
+
badge: jobStates[job.status] ?? job.status,
|
|
2713
|
+
tone,
|
|
2714
|
+
quickActions,
|
|
2715
|
+
...disclosure,
|
|
2716
|
+
},
|
|
2717
|
+
h('div', { className: 'dpt-drawer-bar' },
|
|
2718
|
+
h('div', { className: 'dpt-drawer-facts' },
|
|
2719
|
+
h('span', null, '任务 ID', code(job.id)),
|
|
2720
|
+
job.owner && h('span', null, '所属会话', code(job.owner)),
|
|
2721
|
+
job.startedAt > 0 && h('span', null, '启动', h('strong', null, new Date(job.startedAt).toLocaleString())),
|
|
2722
|
+
job.finishedAt > 0 && h('span', null, '结束', h('strong', null, new Date(job.finishedAt).toLocaleString())),
|
|
2723
|
+
Number.isInteger(job.exitCode) && h('span', null, '退出码', code(String(job.exitCode)))),
|
|
2724
|
+
h('div', { className: 'dpt-actions' },
|
|
2725
|
+
job.owner && button('打开会话', () => run(() => navigation.openSession(job.owner)), { icon: 'external-link', disabled: status.busy }),
|
|
2726
|
+
button(output ? '刷新输出' : '查看输出', loadOutput, { icon: 'terminal', disabled: status.busy }),
|
|
2727
|
+
live
|
|
2728
|
+
? button('停止任务', () => setKilling(true), { icon: 'square', className: 'dpt-danger', disabled: status.busy })
|
|
2729
|
+
: button('清除记录', () => run(async () => {
|
|
2730
|
+
await request('jobs', { action: 'remove', id: job.id })
|
|
2731
|
+
notify('已清除后台任务记录')
|
|
2732
|
+
await refresh()
|
|
2733
|
+
}), { icon: 'trash', disabled: status.busy }))),
|
|
2734
|
+
job.detail && muted(`详情:${job.detail}`),
|
|
2735
|
+
feedback(status.error ? status.message : '', true, dismiss),
|
|
2736
|
+
output && h('div', { className: 'dpt-drawer-split' },
|
|
2737
|
+
h('div', { className: 'dpt-drawer-bar' },
|
|
2738
|
+
muted(`最近输出${output.truncated ? '(仅展示末尾 16 KiB)' : ''} · 总计 ${formatBytes(output.total)}`),
|
|
2739
|
+
button('关闭输出', () => setOutput(null), { icon: 'x', iconSize: 13 })),
|
|
2740
|
+
h('pre', { className: 'dpt-mono', dir: 'ltr' }, output.text || '(暂无输出)')),
|
|
2741
|
+
killing && h(Confirm, {
|
|
2742
|
+
title: `停止任务 ${job.label}`,
|
|
2743
|
+
label: '确认停止任务',
|
|
2744
|
+
removed: [`正在运行的后台任务「${job.label}」(${job.id})`],
|
|
2745
|
+
preserved: ['所属会话的历史记录与工作区文件'],
|
|
2746
|
+
close: () => setKilling(false),
|
|
2747
|
+
confirm: async () => {
|
|
2748
|
+
const result = await request('jobs', { action: 'kill', id: job.id, confirm: job.id })
|
|
2749
|
+
setKilling(false)
|
|
2750
|
+
notify(result.outcome === 'already-finished' ? '任务已自行结束' : '已请求停止任务')
|
|
2751
|
+
await refresh()
|
|
2752
|
+
},
|
|
2753
|
+
}))
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2756
|
+
function ScheduleRow({ item, sessionTitle, navigation, disclosure, refresh, notify }) {
|
|
2757
|
+
const [history, setHistory] = useState(null)
|
|
2758
|
+
const [removal, setRemoval] = useState(false)
|
|
2759
|
+
const [optimisticActive, setOptimisticActive] = useState(null)
|
|
2760
|
+
const [status, run, dismiss] = useAction()
|
|
2761
|
+
useEffect(() => { setOptimisticActive(null) }, [item.status, item.updatedAt])
|
|
2762
|
+
|
|
2763
|
+
const isEnded = item.status === 'ended'
|
|
2764
|
+
const effectiveActive = optimisticActive ?? (item.status === 'active')
|
|
2765
|
+
const targetSessionId = item.target?.sessionId || item.lastDelivery?.targetSessionId || item.involvedSessionIds?.[0] || null
|
|
2766
|
+
const tone = item.executionActive ? 'info' : effectiveActive ? 'ready' : item.status === 'paused' ? 'attention' : 'idle'
|
|
2767
|
+
const badge = item.executionActive ? '执行中' : scheduleStates[effectiveActive ? 'active' : isEnded ? 'ended' : 'paused'] ?? item.status
|
|
2768
|
+
|
|
2769
|
+
const detailParts = [
|
|
2770
|
+
item.target?.kind === 'new' ? '每次新建会话' : item.target?.kind === 'new_once' ? '首次新建会话' : (targetSessionId ? `会话 ${sessionTitle || targetSessionId}` : '目标会话'),
|
|
2771
|
+
!isEnded && item.scheduledAt ? `下次 ${formatIsoShort(item.scheduledAt)}` : '',
|
|
2772
|
+
item.lastDelivery?.deliveredAt ? `上次 ${formatIsoShort(item.lastDelivery.deliveredAt)}` : '',
|
|
2773
|
+
].filter(Boolean)
|
|
2774
|
+
|
|
2775
|
+
function toggleActive(nextActive) {
|
|
2776
|
+
if (isEnded) return
|
|
2777
|
+
setOptimisticActive(nextActive)
|
|
2778
|
+
void run(async () => {
|
|
2779
|
+
try {
|
|
2780
|
+
await request('schedule', { action: 'toggle', id: item.id, active: nextActive, expectedUpdatedAt: item.updatedAt })
|
|
2781
|
+
notify(`${item.title} ${nextActive ? '已恢复调度' : '已暂停'}`)
|
|
2782
|
+
await refresh()
|
|
2783
|
+
} catch (err) {
|
|
2784
|
+
setOptimisticActive(null)
|
|
2785
|
+
throw err
|
|
2786
|
+
}
|
|
2787
|
+
})
|
|
2009
2788
|
}
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2789
|
+
|
|
2790
|
+
async function runNow() {
|
|
2791
|
+
await run(async () => {
|
|
2792
|
+
await request('schedule', { action: 'run', id: item.id })
|
|
2793
|
+
notify(`已触发定时任务:${item.title}`)
|
|
2794
|
+
await refresh()
|
|
2795
|
+
})
|
|
2796
|
+
}
|
|
2797
|
+
|
|
2798
|
+
async function loadHistory() {
|
|
2799
|
+
await run(async () => {
|
|
2800
|
+
const result = await request('schedule', { action: 'history', id: item.id })
|
|
2801
|
+
setHistory(result)
|
|
2802
|
+
disclosure.open()
|
|
2803
|
+
})
|
|
2804
|
+
}
|
|
2805
|
+
|
|
2806
|
+
const quickActions = h(React.Fragment, null,
|
|
2807
|
+
!isEnded && iconButton(`立即运行 ${item.title}`, 'play', runNow, {
|
|
2808
|
+
className: 'dpt-row-icon-btn', iconSize: 13, title: '立即触发一次', disabled: status.busy || item.executionActive,
|
|
2809
|
+
}),
|
|
2810
|
+
targetSessionId && iconButton(`打开目标会话 ${item.title}`, 'external-link', () => run(() => navigation.openSession(targetSessionId)), {
|
|
2811
|
+
className: 'dpt-row-icon-btn', iconSize: 13, title: '打开目标会话', disabled: status.busy,
|
|
2812
|
+
}))
|
|
2813
|
+
|
|
2814
|
+
const alwaysActions = !isEnded && h(Switch, {
|
|
2815
|
+
checked: effectiveActive,
|
|
2816
|
+
disabled: status.busy,
|
|
2817
|
+
label: `${effectiveActive ? '暂停' : '恢复'} ${item.title}`,
|
|
2818
|
+
onChange: toggleActive,
|
|
2819
|
+
})
|
|
2820
|
+
|
|
2821
|
+
return h(DisclosureRow, {
|
|
2822
|
+
'data-schedule-id': item.id,
|
|
2823
|
+
title: item.title,
|
|
2824
|
+
tag: scheduleRuleLabel(item),
|
|
2825
|
+
detail: detailParts.join(' · '),
|
|
2826
|
+
badge,
|
|
2827
|
+
tone,
|
|
2828
|
+
quickActions,
|
|
2829
|
+
alwaysActions,
|
|
2830
|
+
...disclosure,
|
|
2831
|
+
},
|
|
2832
|
+
h('div', { className: 'dpt-drawer-bar' },
|
|
2833
|
+
h('div', { className: 'dpt-drawer-facts' },
|
|
2834
|
+
h('span', null, '任务 ID', code(item.id)),
|
|
2835
|
+
item.scheduledAt && !isEnded && h('span', null, '下次触发', h('strong', null, new Date(item.scheduledAt).toLocaleString())),
|
|
2836
|
+
item.timeZone && h('span', null, '时区', code(item.timeZone)),
|
|
2837
|
+
targetSessionId && h('span', null, '目标会话', code(targetSessionId))),
|
|
2838
|
+
h('div', { className: 'dpt-actions' },
|
|
2839
|
+
!isEnded && button('立即运行', runNow, { icon: 'play', disabled: status.busy || item.executionActive }),
|
|
2840
|
+
!isEnded && button(effectiveActive ? '暂停' : '恢复', () => toggleActive(!effectiveActive), { icon: effectiveActive ? 'pause' : 'play', disabled: status.busy }),
|
|
2841
|
+
targetSessionId && button('打开会话', () => run(() => navigation.openSession(targetSessionId)), { icon: 'external-link', disabled: status.busy }),
|
|
2842
|
+
button(history ? '刷新历史' : '投递历史', loadHistory, { icon: 'clock', disabled: status.busy }),
|
|
2843
|
+
button('删除', () => setRemoval(true), { icon: 'trash', className: 'dpt-danger', disabled: status.busy }))),
|
|
2844
|
+
item.prompt && h('pre', { className: 'dpt-mono', dir: 'auto' }, item.prompt),
|
|
2845
|
+
feedback(status.error ? status.message : '', true, dismiss),
|
|
2846
|
+
history && h('div', { className: 'dpt-drawer-split' },
|
|
2847
|
+
h('div', { className: 'dpt-drawer-bar' },
|
|
2848
|
+
h('span', { className: 'dpt-label' }, `最近投递记录(${history.records.length})${history.earlierRecordsPruned ? ' · 更早记录已按保留窗口清理' : ''}`),
|
|
2849
|
+
button('关闭历史', () => setHistory(null), { icon: 'x', iconSize: 13 })),
|
|
2850
|
+
history.records.length > 0
|
|
2851
|
+
? h('ul', { className: 'dpt-file-list dpt-scroll-box' }, history.records.map(rec => h('li', { key: rec.messageId || rec.deliveredAt },
|
|
2852
|
+
h('span', null, new Date(rec.deliveredAt).toLocaleString(), ' · ', code(rec.targetSessionId)),
|
|
2853
|
+
h('span', null, `计划 ${formatIsoShort(rec.scheduledAt)}`))))
|
|
2854
|
+
: muted('尚无投递记录。')),
|
|
2855
|
+
removal && h(Confirm, {
|
|
2856
|
+
title: `删除定时任务 ${item.title}`,
|
|
2857
|
+
label: '确认删除定时任务',
|
|
2858
|
+
removed: [`定时任务「${item.title}」(${item.id})及未执行的后续触发计划`],
|
|
2859
|
+
preserved: ['目标会话与历史已投递的消息记录'],
|
|
2860
|
+
close: () => setRemoval(false),
|
|
2861
|
+
confirm: async () => {
|
|
2862
|
+
await request('schedule', { action: 'delete', id: item.id, confirm: item.id, expectedUpdatedAt: item.updatedAt })
|
|
2863
|
+
setRemoval(false)
|
|
2864
|
+
notify(`已删除定时任务 ${item.title}`)
|
|
2865
|
+
await refresh()
|
|
2015
2866
|
},
|
|
2016
|
-
|
|
2017
|
-
facts([['插件版本', host.info?.version ? code(host.info.version) : '—'],
|
|
2018
|
-
['MCP 管理', status(host.info?.mcp)], ['Skill 管理', status(host.info?.skills)],
|
|
2019
|
-
['提示词增强', status(host.info?.enhance)], ['会话清理', status(host.info?.sessionDelete)]]),
|
|
2020
|
-
host.info?.profilePath && h('div', { className: 'dpt-drawer-split' },
|
|
2021
|
-
h('h3', null, 'Profile 配置'), h(PathLine, { value: host.info.profilePath })),
|
|
2022
|
-
embedded && h('div', { className: 'dpt-drawer-split' },
|
|
2023
|
-
h('h3', null, '会话与工作区偏好'), muted('工具箱尚无已保存的覆盖规则。')),
|
|
2024
|
-
h('div', { className: 'dpt-actions' }, button('重新检查宿主', host.check, { icon: 'refresh-cw', disabled: host.loading, 'aria-busy': host.loading }))))
|
|
2867
|
+
}))
|
|
2025
2868
|
}
|
|
2026
2869
|
|
|
2027
|
-
function
|
|
2870
|
+
function TasksPanel({ sessionList, navigation, host, toast }) {
|
|
2871
|
+
const { jobs, schedules, error, reloading, refresh, dismissError } = useTasksData(host)
|
|
2872
|
+
const [kindFilter, setKindFilter] = useState('all')
|
|
2873
|
+
const [stateFilter, setStateFilter] = useState('all')
|
|
2874
|
+
const [query, search] = useState('')
|
|
2875
|
+
const [clearingEnded, setClearingEnded] = useState(false)
|
|
2876
|
+
const disclosure = useDisclosure()
|
|
2877
|
+
|
|
2878
|
+
const jobItems = jobs ?? []
|
|
2879
|
+
const scheduleItems = schedules ?? []
|
|
2880
|
+
const liveJobCount = jobItems.filter(item => item.status === 'running' || item.status === 'stopping').length
|
|
2881
|
+
const activeScheduleCount = scheduleItems.filter(item => item.status === 'active').length
|
|
2882
|
+
const endedScheduleCount = scheduleItems.filter(item => item.status === 'ended').length
|
|
2883
|
+
|
|
2884
|
+
const sessionTitleById = id => {
|
|
2885
|
+
if (!id) return ''
|
|
2886
|
+
const row = sessionList.byId?.[id]
|
|
2887
|
+
return row?.title || (row?.displayTitle !== id && row?.displayTitle) || ''
|
|
2888
|
+
}
|
|
2889
|
+
|
|
2890
|
+
const filteredJobs = kindFilter === 'schedule' ? [] : jobItems.filter(job => {
|
|
2891
|
+
const live = job.status === 'running' || job.status === 'stopping'
|
|
2892
|
+
if (stateFilter === 'active' && !live) return false
|
|
2893
|
+
if (stateFilter === 'paused') return false
|
|
2894
|
+
if (stateFilter === 'ended' && live) return false
|
|
2895
|
+
return matches(query, job.label, job.id, job.kind, job.owner ?? '', sessionTitleById(job.owner), job.detail ?? '')
|
|
2896
|
+
})
|
|
2897
|
+
|
|
2898
|
+
const filteredSchedules = kindFilter === 'jobs' ? [] : scheduleItems.filter(item => {
|
|
2899
|
+
if (stateFilter === 'active' && item.status !== 'active') return false
|
|
2900
|
+
if (stateFilter === 'paused' && item.status !== 'paused') return false
|
|
2901
|
+
if (stateFilter === 'ended' && item.status !== 'ended') return false
|
|
2902
|
+
const targetId = item.target?.sessionId ?? ''
|
|
2903
|
+
return matches(query, item.title, item.id, item.prompt, scheduleRuleLabel(item), targetId, sessionTitleById(targetId))
|
|
2904
|
+
})
|
|
2905
|
+
|
|
2906
|
+
const totalShown = filteredJobs.length + filteredSchedules.length
|
|
2907
|
+
const hasActiveFilter = Boolean(query.trim()) || stateFilter !== 'all'
|
|
2908
|
+
const resetFilters = () => { search(''); setStateFilter('all') }
|
|
2909
|
+
const ready = jobs !== null || schedules !== null || (host.info?.jobs === false && host.info?.schedule === false)
|
|
2910
|
+
|
|
2911
|
+
return h('div', { className: 'dpt-panel' },
|
|
2912
|
+
feedback(host.error || (host.info?.jobs === false && host.info?.schedule === false ? '当前 DSH 配置未加载后台任务与定时调度服务。' : ''), true, host.dismiss),
|
|
2913
|
+
feedback(error, true, dismissError),
|
|
2914
|
+
h('div', { className: 'dpt-toolbar' },
|
|
2915
|
+
h(Segmented, {
|
|
2916
|
+
label: '任务类型筛选', value: kindFilter, onChange: setKindFilter,
|
|
2917
|
+
items: [
|
|
2918
|
+
{ value: 'all', label: '全部', count: ready ? jobItems.length + scheduleItems.length : null },
|
|
2919
|
+
{ value: 'jobs', label: '后台任务', count: jobs ? jobItems.length : null, alert: liveJobCount > 0 },
|
|
2920
|
+
{ value: 'schedule', label: '定时调度', count: schedules ? scheduleItems.length : null, alert: activeScheduleCount > 0 },
|
|
2921
|
+
],
|
|
2922
|
+
}),
|
|
2923
|
+
h('div', { className: 'dpt-toolbar-right' },
|
|
2924
|
+
filterInput('搜索任务或提示词', query, search),
|
|
2925
|
+
pick('任务状态筛选', stateFilter, setStateFilter, [
|
|
2926
|
+
option('all', '全部状态'),
|
|
2927
|
+
option('active', '运行中 / 活跃'),
|
|
2928
|
+
option('paused', '已暂停'),
|
|
2929
|
+
option('ended', '已结束'),
|
|
2930
|
+
]),
|
|
2931
|
+
hasActiveFilter && totalShown > 0 && button('重置筛选', resetFilters, { icon: 'x', iconSize: 13 }),
|
|
2932
|
+
endedScheduleCount > 0 && kindFilter !== 'jobs' && button(`清理已结束 (${endedScheduleCount})`, () => setClearingEnded(true), { icon: 'trash', iconSize: 13 }),
|
|
2933
|
+
iconButton('刷新任务与调度', 'refresh-cw', refresh, { iconClass: reloading ? 'dpt-spin' : '', disabled: reloading, 'aria-busy': reloading }))),
|
|
2934
|
+
totalShown > 0
|
|
2935
|
+
? h('ul', { className: 'dpt-card' },
|
|
2936
|
+
filteredJobs.length > 0 && h(React.Fragment, null,
|
|
2937
|
+
kindFilter === 'all' && h('li', { className: 'dpt-subhead' }, `后台任务(${filteredJobs.length})`),
|
|
2938
|
+
filteredJobs.map(job => h(JobRow, {
|
|
2939
|
+
key: `job:${job.id}`, job, sessionTitle: sessionTitleById(job.owner),
|
|
2940
|
+
navigation, refresh, notify: toast.show,
|
|
2941
|
+
disclosure: disclosure(`job:${job.id}`),
|
|
2942
|
+
}))),
|
|
2943
|
+
filteredSchedules.length > 0 && h(React.Fragment, null,
|
|
2944
|
+
kindFilter === 'all' && h('li', { className: 'dpt-subhead' }, `定时调度(${filteredSchedules.length})`),
|
|
2945
|
+
filteredSchedules.map(item => h(ScheduleRow, {
|
|
2946
|
+
key: `schedule:${item.id}`, item, sessionTitle: sessionTitleById(item.target?.sessionId),
|
|
2947
|
+
navigation, refresh, notify: toast.show,
|
|
2948
|
+
disclosure: disclosure(`schedule:${item.id}`),
|
|
2949
|
+
}))))
|
|
2950
|
+
: empty(ready
|
|
2951
|
+
? (hasActiveFilter ? '没有符合条件的任务或定时调度。' : '当前没有后台任务或定时调度。')
|
|
2952
|
+
: '正在读取后台任务与定时调度…', ready && hasActiveFilter ? resetFilters : undefined),
|
|
2953
|
+
clearingEnded && h(Confirm, {
|
|
2954
|
+
title: `清理 ${endedScheduleCount} 条已结束的定时任务`,
|
|
2955
|
+
label: '确认清理',
|
|
2956
|
+
removed: [`${endedScheduleCount} 条状态为「已结束」的定时调度记录`],
|
|
2957
|
+
preserved: ['所有活跃与暂停中的定时调度', '历史已投递的会话消息'],
|
|
2958
|
+
close: () => setClearingEnded(false),
|
|
2959
|
+
confirm: async () => {
|
|
2960
|
+
const result = await request('schedule', { action: 'delete-inactive', confirm: true })
|
|
2961
|
+
setClearingEnded(false)
|
|
2962
|
+
toast.show(`已清理 ${result.deleted ?? endedScheduleCount} 条已结束的定时任务`)
|
|
2963
|
+
await refresh()
|
|
2964
|
+
},
|
|
2965
|
+
}))
|
|
2966
|
+
}
|
|
2967
|
+
|
|
2968
|
+
function PowerTools({ useSessions, useWorkspaces, navigation, refresh, t, embedded = false }) {
|
|
2028
2969
|
const [tab, select] = useState('sessions')
|
|
2029
2970
|
const sessionList = useSessions(identity)
|
|
2030
2971
|
const workspaceList = useWorkspaces(identity)
|
|
@@ -2032,11 +2973,12 @@ window.__ModuleLoader__.load({
|
|
|
2032
2973
|
const toast = useToast()
|
|
2033
2974
|
const controls = h('div', { className: 'dpt-controls' },
|
|
2034
2975
|
h('nav', { className: 'dpt-nav', 'aria-label': '工具箱功能' },
|
|
2035
|
-
[['sessions', '会话', 'message-square'], ['mcp', 'MCP', 'plug'], ['skills', 'Skill', 'wand-sparkles']].map(([id, label, icon]) =>
|
|
2976
|
+
[['sessions', '会话', 'message-square'], ['mcp', 'MCP', 'plug'], ['skills', 'Skill', 'wand-sparkles'], ['tasks', '任务与调度', 'clock']].map(([id, label, icon]) =>
|
|
2036
2977
|
button(label, () => select(id), { key: id, icon, className: 'dpt-tab', 'aria-pressed': tab === id }))),
|
|
2037
|
-
tab === 'sessions' ? h(SessionPanel, { sessionList, workspaceList, navigation, refresh, host, toast })
|
|
2038
|
-
: tab === 'mcp' ? h(McpPanel, { host, toast })
|
|
2039
|
-
|
|
2978
|
+
tab === 'sessions' ? h(SessionPanel, { sessionList, workspaceList, navigation, refresh, host, toast, t })
|
|
2979
|
+
: tab === 'mcp' ? h(McpPanel, { host, toast })
|
|
2980
|
+
: tab === 'skills' ? h(SkillsPanel, { sessionList, workspaceList, navigation, host, toast })
|
|
2981
|
+
: h(TasksPanel, { sessionList, navigation, host, toast }),
|
|
2040
2982
|
toast.node)
|
|
2041
2983
|
const stylesheet = h('style', null, css)
|
|
2042
2984
|
if (embedded) return h('div', { className: 'dpt dpt-inline' }, stylesheet, controls)
|
|
@@ -2158,16 +3100,108 @@ window.__ModuleLoader__.load({
|
|
|
2158
3100
|
return h(Enhance, { key: props.sessionId, ...props })
|
|
2159
3101
|
}
|
|
2160
3102
|
|
|
3103
|
+
function SidebarSessionDelete({ target, close, refresh, notify, t }) {
|
|
3104
|
+
const { sessionId, displayTitle } = target
|
|
3105
|
+
const [preview, setPreview] = useState(null)
|
|
3106
|
+
const [status, run, dismiss] = useAction()
|
|
3107
|
+
useEffect(() => {
|
|
3108
|
+
const abort = new AbortController()
|
|
3109
|
+
request('sessions', { action: 'list' }, abort.signal).then(({ sessions }) => {
|
|
3110
|
+
if (!abort.signal.aborted) setPreview({ row: sessions.find(row => row.id === sessionId) })
|
|
3111
|
+
}).catch(error => {
|
|
3112
|
+
if (!abort.signal.aborted) setPreview({ error: error.message })
|
|
3113
|
+
})
|
|
3114
|
+
return () => abort.abort()
|
|
3115
|
+
}, [sessionId])
|
|
3116
|
+
|
|
3117
|
+
const row = preview?.row
|
|
3118
|
+
const subagents = row?.descendantSubagentIds.length ?? 0
|
|
3119
|
+
const error = preview?.error || (preview && !row ? t('missing') : '')
|
|
3120
|
+
|| (row && !row.deletable ? (row.deleteBlocker ? t(row.deleteBlocker) : row.deleteReason || t('blocked')) : '')
|
|
3121
|
+
function confirm() {
|
|
3122
|
+
return run(async () => {
|
|
3123
|
+
const result = await request('sessions', { action: 'delete', sessionId, confirm: sessionId })
|
|
3124
|
+
const copyRecovery = {
|
|
3125
|
+
label: t('copyRecovery'), failureLabel: t('copyFailed'),
|
|
3126
|
+
run: async () => { if (!await writeClipboard(result.recovery)) throw new Error(t('copyFailed')) },
|
|
3127
|
+
}
|
|
3128
|
+
try {
|
|
3129
|
+
await refresh()
|
|
3130
|
+
notify(t('deleted'), true, copyRecovery)
|
|
3131
|
+
} catch {
|
|
3132
|
+
notify(t('refreshFailed'), false, copyRecovery)
|
|
3133
|
+
}
|
|
3134
|
+
close()
|
|
3135
|
+
})
|
|
3136
|
+
}
|
|
3137
|
+
return h(Modal, { title: t('deleteTitle', { title: displayTitle || t('untitled') }), close, closeLabel: t('close'), busy: status.busy },
|
|
3138
|
+
h('div', { className: 'dpt-form' },
|
|
3139
|
+
h('div', { className: 'dpt-drawer-facts' }, h('span', null, t('sessionId'), code(sessionId))),
|
|
3140
|
+
!preview && h('p', { role: 'status' }, t('checking')),
|
|
3141
|
+
status.busy && h('p', { role: 'status' }, t('deleting')),
|
|
3142
|
+
error && feedback(error, true),
|
|
3143
|
+
row?.deletable && h('p', null, t('recovery')),
|
|
3144
|
+
subagents > 0 && h('p', null, t('subagents', { count: subagents })),
|
|
3145
|
+
feedback(status.message, status.error, dismiss),
|
|
3146
|
+
h('div', { className: 'dpt-actions' },
|
|
3147
|
+
button(t('cancel'), close, { 'data-dpt-initial-focus': true, disabled: status.busy }),
|
|
3148
|
+
button(t('confirm'), confirm, { icon: 'trash', className: 'dpt-danger', disabled: status.busy || !row?.deletable, 'aria-busy': status.busy }))))
|
|
3149
|
+
}
|
|
3150
|
+
|
|
3151
|
+
function SessionOverlay({ deletion, refresh, notify, t }) {
|
|
3152
|
+
const target = useSyncExternalStore(deletion.subscribe, deletion.getSnapshot)
|
|
3153
|
+
return target && h(SidebarSessionDelete, { key: target.sessionId, target, close: () => deletion.set(null), refresh, notify, t })
|
|
3154
|
+
}
|
|
3155
|
+
|
|
2161
3156
|
function PowerToolsIcon({ size = 16 }) {
|
|
2162
3157
|
return h(Icon, { name: 'layout-grid', size })
|
|
2163
3158
|
}
|
|
2164
3159
|
|
|
2165
3160
|
return {
|
|
2166
|
-
inject: ['slots', 'uiWorkspace', 'sessions'],
|
|
3161
|
+
inject: ['slots', 'uiWorkspace', 'sessions', 'locale', 'contextMenus'],
|
|
2167
3162
|
apply(ctx) {
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
3163
|
+
ctx.effect(() => ctx.locale.register(SESSION_LOCALE, sessionLocales), 'PowerTools session translations')
|
|
3164
|
+
const t = ctx.locale.bind(SESSION_LOCALE)
|
|
3165
|
+
const refresh = () => ctx.sessions.refresh()
|
|
3166
|
+
const panelProps = () => ({ navigation: ctx.uiWorkspace, refresh })
|
|
3167
|
+
ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL, locale: SESSION_LOCALE, inject: panelProps }, PowerTools))
|
|
3168
|
+
ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ name: 'plugins.bundle.config', key: PANEL, locale: SESSION_LOCALE, inject: panelProps }, PowerToolsConfig))
|
|
3169
|
+
|
|
3170
|
+
let deleteTarget = null
|
|
3171
|
+
const listeners = new Set()
|
|
3172
|
+
const deletion = {
|
|
3173
|
+
getSnapshot: () => deleteTarget,
|
|
3174
|
+
subscribe(listener) {
|
|
3175
|
+
listeners.add(listener)
|
|
3176
|
+
return () => listeners.delete(listener)
|
|
3177
|
+
},
|
|
3178
|
+
set(target) {
|
|
3179
|
+
deleteTarget = target
|
|
3180
|
+
for (const listener of listeners) listener()
|
|
3181
|
+
},
|
|
3182
|
+
}
|
|
3183
|
+
const notify = (...args) => ctx.contextMenus.notify(...args)
|
|
3184
|
+
ctx.slots.inject('shell.overlay', () => ctx.slots.register({
|
|
3185
|
+
name: 'shell.overlay', id: PANEL, locale: SESSION_LOCALE,
|
|
3186
|
+
inject: () => ({ deletion, refresh, notify }),
|
|
3187
|
+
}, SessionOverlay))
|
|
3188
|
+
const deleteIcon = `${PANEL}.delete-session`
|
|
3189
|
+
ctx.slots.inject('contextMenu.icon', () => ctx.slots.register({
|
|
3190
|
+
name: 'contextMenu.icon', key: deleteIcon,
|
|
3191
|
+
}, () => h(Icon, { name: 'trash' })))
|
|
3192
|
+
ctx.effect(() => ctx.contextMenus.register({
|
|
3193
|
+
id: deleteIcon, target: 'session', order: 700,
|
|
3194
|
+
observe: () => [ctx.locale],
|
|
3195
|
+
resolve(target) {
|
|
3196
|
+
const summary = ctx.sessions.list.getSnapshot().byId[target.sessionId]
|
|
3197
|
+
if (!summary || summary.blank) return []
|
|
3198
|
+
return [{
|
|
3199
|
+
id: 'delete', label: t('delete'), icon: { key: deleteIcon },
|
|
3200
|
+
danger: true, separatorBefore: true, afterContent: true,
|
|
3201
|
+
run: () => deletion.set(target),
|
|
3202
|
+
}]
|
|
3203
|
+
},
|
|
3204
|
+
}), 'PowerTools session deletion menu')
|
|
2171
3205
|
ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: PANEL, order: 20, label: '工具箱' }, PowerToolsIcon))
|
|
2172
3206
|
ctx.slots.inject('conversation.input.activity', () => ctx.slots.register({
|
|
2173
3207
|
name: 'conversation.input.activity', id: PANEL, order: 15,
|